From 5f721e3825dff324bb9baf7c0907ff8c1cde700d Mon Sep 17 00:00:00 2001 From: Jacob Dent Date: Tue, 29 Sep 2026 10:38:56 -0500 Subject: [PATCH] Add the TypeScript and Python SDKs (sdk/), publish workflow for sdk-v* and pysdk-v* tags Moved from the private app repo so the source is public and matches the package metadata. Both generated from sdk/openapi.json (copy of provable.io/openapi.json). Adds the missing rotateServerSeed + getPublicMetrics (TS) and get_public_metrics (py) methods, and a TS test that every spec path has a client method. --- .github/workflows/ci.yml | 15 + .github/workflows/publish-sdk.yml | 61 + .gitignore | 3 + sdk/openapi.json | 3413 +++++++++++++++++++++ sdk/python/LICENSE | 178 ++ sdk/python/README.md | 78 + sdk/python/generate_models.py | 264 ++ sdk/python/pyproject.toml | 40 + sdk/python/src/provableio/__init__.py | 7 + sdk/python/src/provableio/client.py | 254 ++ sdk/python/src/provableio/models.py | 401 +++ sdk/python/src/provableio/operations.py | 5 + sdk/python/src/provableio/py.typed | 0 sdk/python/tests/test_client.py | 87 + sdk/python/tests/test_openapi_coverage.py | 89 + sdk/typescript/LICENSE | 178 ++ sdk/typescript/README.md | 133 + sdk/typescript/package-lock.json | 398 +++ sdk/typescript/package.json | 65 + sdk/typescript/src/index.ts | 428 +++ sdk/typescript/src/openapi-types.ts | 2474 +++++++++++++++ sdk/typescript/test/client.test.mjs | 120 + sdk/typescript/tsconfig.json | 20 + 23 files changed, 8711 insertions(+) create mode 100644 .github/workflows/publish-sdk.yml create mode 100644 sdk/openapi.json create mode 100644 sdk/python/LICENSE create mode 100644 sdk/python/README.md create mode 100644 sdk/python/generate_models.py create mode 100644 sdk/python/pyproject.toml create mode 100644 sdk/python/src/provableio/__init__.py create mode 100644 sdk/python/src/provableio/client.py create mode 100644 sdk/python/src/provableio/models.py create mode 100644 sdk/python/src/provableio/operations.py create mode 100644 sdk/python/src/provableio/py.typed create mode 100644 sdk/python/tests/test_client.py create mode 100644 sdk/python/tests/test_openapi_coverage.py create mode 100644 sdk/typescript/LICENSE create mode 100644 sdk/typescript/README.md create mode 100644 sdk/typescript/package-lock.json create mode 100644 sdk/typescript/package.json create mode 100644 sdk/typescript/src/index.ts create mode 100644 sdk/typescript/src/openapi-types.ts create mode 100644 sdk/typescript/test/client.test.mjs create mode 100644 sdk/typescript/tsconfig.json diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c4dc9b5..a37795f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,3 +20,18 @@ jobs: - run: corepack enable - run: yarn install --immutable - run: yarn test + + sdk: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - run: npm ci && npm run build && git diff --exit-code -- src/openapi-types.ts && npm test + working-directory: sdk/typescript + - run: python generate_models.py && git diff --exit-code -- src/provableio && pip install pytest . && pytest + working-directory: sdk/python diff --git a/.github/workflows/publish-sdk.yml b/.github/workflows/publish-sdk.yml new file mode 100644 index 0000000..e210e6e --- /dev/null +++ b/.github/workflows/publish-sdk.yml @@ -0,0 +1,61 @@ +name: Publish SDKs + +# Tags publish the SDKs in sdk/ (the core package keeps its own vX.Y.Z tags): +# sdk-vX.Y.Z -> @provableio/sdk on npm (version must match sdk/typescript/package.json) +# pysdk-vX.Y.Z -> provableio on PyPI (version must match sdk/python/pyproject.toml) +# Both registries use trusted publishing (OIDC): no tokens are stored. + +on: + push: + tags: ["sdk-v[0-9]+.[0-9]+.[0-9]+", "pysdk-v[0-9]+.[0-9]+.[0-9]+"] + +permissions: + contents: read + id-token: write + +jobs: + npm: + if: startsWith(github.ref_name, 'sdk-v') + runs-on: ubuntu-latest + defaults: + run: + working-directory: sdk/typescript + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 24 + registry-url: https://registry.npmjs.org + - name: Tag must match package.json + run: test "sdk-v$(node -p "require('./package.json').version")" = "$GITHUB_REF_NAME" + - run: npm ci + - run: npm run build + - name: Generated types match sdk/openapi.json + run: git diff --exit-code -- src/openapi-types.ts + - run: npm test + - run: npm publish --access public + + pypi: + if: startsWith(github.ref_name, 'pysdk-v') + runs-on: ubuntu-latest + environment: pypi + defaults: + run: + working-directory: sdk/python + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: Tag must match pyproject.toml + run: test "pysdk-v$(python -c 'import tomllib; print(tomllib.load(open("pyproject.toml", "rb"))["project"]["version"])')" = "$GITHUB_REF_NAME" + - name: Generated models match sdk/openapi.json + run: | + python generate_models.py + git diff --exit-code -- src/provableio/models.py src/provableio/operations.py + - run: python -m pip install build pytest . + - run: pytest + - run: python -m build + - uses: pypa/gh-action-pypi-publish@release/v1 + with: + packages-dir: sdk/python/dist/ diff --git a/.gitignore b/.gitignore index 68fc02d..b836a7c 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,6 @@ node_modules dist .yarn/ .pnp.* +__pycache__/ +.pytest_cache/ +*.egg-info/ diff --git a/sdk/openapi.json b/sdk/openapi.json new file mode 100644 index 0000000..e8ca0c0 --- /dev/null +++ b/sdk/openapi.json @@ -0,0 +1,3413 @@ +{ + "openapi": "3.0.3", + "info": { + "title": "Provable.io Random Generator API", + "description": "Cryptographically verifiable random number generation. Generate random floats and integers, verify outcomes, and list per-seed history. Every endpoint is callable anonymously (rate-limited by IP); authenticated calls are attributed to your account for usage tracking, daily quotas, and webhook delivery.", + "version": "1.0.0", + "contact": { + "name": "Provable.io Support", + "email": "support@provable.io", + "url": "https://provable.io" + }, + "license": { + "name": "Proprietary", + "url": "https://provable.io/terms" + } + }, + "servers": [ + { + "url": "https://api.provable.io", + "description": "Production — the single base URL for all traffic. There is no separate sandbox host: test mode is selected per request by authenticating with a `pk_test_…` API key (deterministic outcomes, excluded from usage stats, no webhooks), while `pk_live_…` keys and anonymous calls hit live randomness on the same host." + } + ], + "externalDocs": { + "description": "Human-readable API reference", + "url": "https://provable.io/api-docs" + }, + "tags": [ + { + "name": "Random", + "description": "Generate random values" + }, + { + "name": "Verification", + "description": "Verify and look up past outcomes" + }, + { + "name": "Transparency", + "description": "Daily Merkle roots and inclusion proofs over all outcomes" + }, + { + "name": "System", + "description": "Service health" + } + ], + "security": [ + { + "ApiKeyAuth": [] + }, + { + "BearerAuth": [] + }, + {} + ], + "paths": { + "/api/batch": { + "post": { + "tags": [ + "Random" + ], + "summary": "Run many draws in one round trip", + "description": "Accepts up to 50 independent draws across any of the random-generating endpoints (`floats`, `ints`, `shuffle`, `pick`, `bytes`, `dice`, `gaussian`) and returns one result per draw in the same order.\n\n- Each draw uses its own `clientSeed`/`cursor`/`nonce`, so any single outcome is independently verifiable via `/api/verifyServerHash` and gets its own `shortId`/`permalink`.\n- A failing draw is reported as `{ ok: false, error }` and does **not** abort the batch — successful draws still persist their outcomes.\n- Authenticated calls bump usage counters once per **successful** draw. If the daily quota is reached mid-batch, the remaining draws short-circuit with `{ ok: false, error: \"…\", code: \"quota_exceeded\" }` instead of running.\n- One `Idempotency-Key` covers the whole batch: a retry with the same key replays the identical `results` array and does not re-run any draw.", + "operationId": "batchDraw", + "parameters": [ + { + "$ref": "#/components/parameters/IdempotencyKey" + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BatchRequest" + }, + "example": { + "draws": [ + { + "endpoint": "ints", + "params": { + "clientSeed": "chest-1", + "count": 1, + "min": 1, + "max": 100 + } + }, + { + "endpoint": "ints", + "params": { + "clientSeed": "chest-2", + "count": 1, + "min": 1, + "max": 100 + } + }, + { + "endpoint": "pick", + "params": { + "clientSeed": "loot-3", + "items": [ + "common", + "rare", + "legendary" + ], + "weights": [ + 70, + 25, + 5 + ] + } + } + ] + } + } + } + }, + "responses": { + "200": { + "description": "One result per draw, in request order.", + "headers": { + "Server-Timing": { + "$ref": "#/components/headers/ServerTiming" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BatchResponse" + }, + "example": { + "results": [ + { + "ok": true, + "outcome": { + "outcome": [ + 42 + ], + "clientSeed": "chest-1", + "serverHash": "9f86d081884c7d65...", + "nonce": 0, + "cursor": 0, + "count": 1, + "min": 1, + "max": 100, + "endpoint": "ints", + "created": 1716566400000, + "shortId": "k7Qm2A9bXz", + "permalink": "https://provable.io/o/k7Qm2A9bXz" + } + }, + { + "ok": true, + "outcome": { + "outcome": [ + 73 + ], + "clientSeed": "chest-2", + "serverHash": "5e3b...", + "nonce": 0, + "cursor": 0, + "count": 1, + "min": 1, + "max": 100, + "endpoint": "ints", + "created": 1716566400000, + "shortId": "9aB2c3D4eF", + "permalink": "https://provable.io/o/9aB2c3D4eF" + } + }, + { + "ok": true, + "outcome": { + "outcome": "legendary", + "index": 2, + "clientSeed": "loot-3", + "serverHash": "0a1b...", + "nonce": 0, + "cursor": 0, + "count": 1, + "weights": [ + 70, + 25, + 5 + ], + "endpoint": "pick", + "created": 1716566400000, + "shortId": "P9q8R7s6T5", + "permalink": "https://provable.io/o/P9q8R7s6T5" + } + } + ] + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { "$ref": "#/components/responses/InvalidApiKey" }, + "409": { + "$ref": "#/components/responses/IdempotencyConflict" + }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/ServerError" + } + } + } + }, + "/api/bytes": { + "get": { + "tags": [ + "Random" + ], + "summary": "Generate random bytes", + "description": "Return `count` random bytes encoded as `hex` (default) or `base64`. Useful for tokens, salts, and key material.", + "operationId": "getBytes", + "parameters": [ + { + "$ref": "#/components/parameters/ClientSeed" + }, + { + "name": "count", + "in": "query", + "description": "Number of bytes to generate (1-1024).", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 1024, + "default": 32 + } + }, + { + "name": "encoding", + "in": "query", + "description": "Output encoding.", + "required": false, + "schema": { + "type": "string", + "enum": [ + "hex", + "base64" + ], + "default": "hex" + } + }, + { + "$ref": "#/components/parameters/IdempotencyKey" + } + ], + "responses": { + "200": { + "description": "An encoded byte string and the associated server hash.", + "headers": { + "Server-Timing": { + "$ref": "#/components/headers/ServerTiming" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BytesOutcome" + }, + "example": { + "outcome": "3f0a8b7d1c4e6f209a8c5b4d2e1f0a8b", + "clientSeed": "my-app", + "serverHash": "9f86d081884c7d65...", + "nonce": 0, + "cursor": 0, + "count": 16, + "encoding": "hex", + "endpoint": "bytes", + "created": 1716566400000 + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { "$ref": "#/components/responses/InvalidApiKey" }, + "409": { + "$ref": "#/components/responses/IdempotencyConflict" + }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/ServerError" + } + } + } + }, + "/api/commit": { + "post": { + "tags": [ + "Random" + ], + "summary": "Commit a server seed (commit-reveal step 1)", + "description": "Stronger fairness guarantee than `/api/floats` and `/api/ints`. The server generates a fresh `serverSeed`, publishes its `serverHash`, and holds the seed secret until you reveal. Because the hash is published *before* you submit your `clientSeed`, the server cannot pick its seed in response to yours. Follow with `POST /api/reveal` within the commit's TTL (default 10 minutes).", + "operationId": "createCommit", + "responses": { + "200": { + "description": "A new commit. Save `commitId` and `serverHash` for verification, then call `/api/reveal`.", + "headers": { + "Server-Timing": { + "$ref": "#/components/headers/ServerTiming" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Commit" + }, + "example": { + "commitId": "8c3d7b9e-1f2a-4c5d-9e8f-7a6b5c4d3e2f", + "serverHash": "9f86d081884c7d65...", + "expiresAt": 1716567000000 + } + } + } + }, + "401": { "$ref": "#/components/responses/InvalidApiKey" }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/ServerError" + } + } + } + }, + "/api/dice": { + "get": { + "tags": [ + "Random" + ], + "summary": "Roll dice", + "description": "Roll dice using standard tabletop notation. Returns the individual rolls, the modifier, and the total.", + "operationId": "rollDice", + "parameters": [ + { + "$ref": "#/components/parameters/ClientSeed" + }, + { + "name": "notation", + "in": "query", + "description": "Dice notation `NdM`, `NdM+K`, or `NdM-K`. N: 1-100 dice. M: 2-1,000,000 sides. K: integer modifier added to the total. Examples: `3d6`, `2d20+5`, `1d100-10`.", + "required": true, + "example": "3d6+2", + "schema": { + "type": "string", + "pattern": "^(\\d+)?d\\d+(\\s*[+-]\\s*\\d+)?$" + } + }, + { + "$ref": "#/components/parameters/IdempotencyKey" + } + ], + "responses": { + "200": { + "description": "Per-die rolls, modifier, and total.", + "headers": { + "Server-Timing": { + "$ref": "#/components/headers/ServerTiming" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/DiceOutcome" + }, + "example": { + "outcome": { + "notation": "3d6+2", + "rolls": [ + 4, + 6, + 3 + ], + "modifier": 2, + "total": 15 + }, + "clientSeed": "tabletop", + "serverHash": "9f86d081884c7d65...", + "nonce": 0, + "cursor": 0, + "count": 3, + "sides": 6, + "modifier": 2, + "endpoint": "dice", + "created": 1716566400000 + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { "$ref": "#/components/responses/InvalidApiKey" }, + "409": { + "$ref": "#/components/responses/IdempotencyConflict" + }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/ServerError" + } + } + } + }, + "/api/floats": { + "get": { + "tags": [ + "Random" + ], + "summary": "Generate random floats", + "description": "Generate cryptographically verifiable random floating-point numbers in the range [0, 1).", + "operationId": "getFloats", + "parameters": [ + { + "$ref": "#/components/parameters/ClientSeed" + }, + { + "$ref": "#/components/parameters/Count" + }, + { + "$ref": "#/components/parameters/IdempotencyKey" + } + ], + "responses": { + "200": { + "description": "A batch of random floats and the associated server hash.", + "headers": { + "Server-Timing": { + "$ref": "#/components/headers/ServerTiming" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/FloatOutcome" + }, + "example": { + "outcome": [ + 0.4823, + 0.1175, + 0.9034, + 0.5567, + 0.2218 + ], + "clientSeed": "my-app", + "serverHash": "9f86d081884c7d65...", + "nonce": 0, + "cursor": 5, + "count": 5, + "endpoint": "floats", + "created": 1716566400000, + "shortId": "k7Qm2A9bXz", + "permalink": "https://provable.io/o/k7Qm2A9bXz" + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { "$ref": "#/components/responses/InvalidApiKey" }, + "409": { + "$ref": "#/components/responses/IdempotencyConflict" + }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/ServerError" + } + } + } + }, + "/api/gaussian": { + "get": { + "tags": [ + "Random" + ], + "summary": "Sample a statistical distribution", + "description": "Draw samples from a `normal`, `exponential`, or `poisson` distribution with caller-supplied parameters.", + "operationId": "gaussian", + "parameters": [ + { + "$ref": "#/components/parameters/ClientSeed" + }, + { + "$ref": "#/components/parameters/Count" + }, + { + "name": "distribution", + "in": "query", + "description": "Which distribution to sample.", + "required": false, + "schema": { + "type": "string", + "enum": [ + "normal", + "exponential", + "poisson" + ], + "default": "normal" + } + }, + { + "name": "mean", + "in": "query", + "description": "Mean (μ) for `normal`. Defaults to 0.", + "required": false, + "schema": { + "type": "number", + "default": 0 + } + }, + { + "name": "stddev", + "in": "query", + "description": "Standard deviation (σ) for `normal`. Must be > 0. Defaults to 1.", + "required": false, + "schema": { + "type": "number", + "exclusiveMinimum": 0, + "default": 1 + } + }, + { + "name": "lambda", + "in": "query", + "description": "Rate parameter (λ) for `exponential` (> 0) or `poisson` (> 0, ≤ 100). Defaults to 1.", + "required": false, + "schema": { + "type": "number", + "exclusiveMinimum": 0, + "default": 1 + } + }, + { + "$ref": "#/components/parameters/IdempotencyKey" + } + ], + "responses": { + "200": { + "description": "An array of samples from the requested distribution.", + "headers": { + "Server-Timing": { + "$ref": "#/components/headers/ServerTiming" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GaussianOutcome" + }, + "example": { + "outcome": [ + -0.42, + 1.05, + 0.18, + -1.21, + 0.66 + ], + "clientSeed": "stats", + "serverHash": "9f86d081884c7d65...", + "nonce": 0, + "cursor": 0, + "count": 5, + "distribution": "normal", + "mean": 0, + "stddev": 1, + "endpoint": "gaussian", + "created": 1716566400000 + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { "$ref": "#/components/responses/InvalidApiKey" }, + "409": { + "$ref": "#/components/responses/IdempotencyConflict" + }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/ServerError" + } + } + } + }, + "/api/health": { + "get": { + "tags": [ + "System" + ], + "summary": "Service health", + "description": "Service health, version, and uptime. Returns 503 when the database is unreachable or the server is shutting down.", + "operationId": "getHealth", + "security": [], + "responses": { + "200": { + "description": "Service is healthy.", + "headers": { + "Server-Timing": { + "$ref": "#/components/headers/ServerTiming" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Health" + }, + "example": { + "status": "ok", + "db": "ok", + "version": "1.0.0", + "uptime": 12345, + "timestamp": "2026-05-24T12:00:00.000Z" + } + } + } + }, + "401": { "$ref": "#/components/responses/InvalidApiKey" }, + "503": { + "description": "Service is degraded or shutting down.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Health" + } + } + } + } + } + } + }, + "/api/public-metrics": { + "get": { + "tags": [ + "System" + ], + "summary": "Public service metrics", + "description": "Privacy-safe aggregate adoption and operational metrics for the homepage. The account value is the current account total. The outcome value is a persisted lifetime total that includes anonymous traffic and excludes test mode. Counts contain no account or outcome details. Response time covers only successful, completed, non-test, non-stream requests to public product API endpoints in the recent in-memory window on the current server instance.", + "operationId": "getPublicMetrics", + "security": [], + "responses": { + "200": { + "description": "Current metrics, with unavailable aggregate values represented as null when the database cannot be reached.", + "headers": { + "Server-Timing": { + "$ref": "#/components/headers/ServerTiming" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PublicMetrics" + } + } + } + }, + "401": { "$ref": "#/components/responses/InvalidApiKey" }, + "429": { + "$ref": "#/components/responses/RateLimited" + } + } + } + }, + "/api/incrementCursor": { + "get": { + "tags": [ + "Verification" + ], + "summary": "Advance the cursor for a client seed", + "description": "Bumps the cursor for the given `clientSeed`; `nonce` keeps counting up so no earlier draw is ever repeated. The next call to `/api/floats` or `/api/ints` for this seed will derive from a fresh row in the underlying HMAC stream. Use this to rotate to a new \"round\" of draws without changing the seed pair. Returns `400` if the client seed has no recorded state yet.", + "operationId": "incrementCursor", + "parameters": [ + { + "$ref": "#/components/parameters/ClientSeed" + } + ], + "responses": { + "200": { + "description": "The new cursor/nonce pair for this seed, with the current `serverHash` echoed back.", + "headers": { + "Server-Timing": { + "$ref": "#/components/headers/ServerTiming" + } + }, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "clientSeed": { + "type": "string" + }, + "cursor": { + "type": "integer", + "minimum": 0 + }, + "nonce": { + "type": "integer", + "minimum": 0 + }, + "serverHash": { + "type": "string" + }, + "created": { + "type": "integer", + "format": "int64", + "description": "Unix ms when the cursor was bumped." + } + }, + "required": [ + "clientSeed", + "cursor", + "nonce", + "serverHash", + "created" + ] + }, + "example": { + "clientSeed": "my-app", + "cursor": 6, + "nonce": 0, + "serverHash": "9f86d081884c7d65...", + "created": 1716566400000 + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { "$ref": "#/components/responses/InvalidApiKey" }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/ServerError" + } + } + } + }, + "/api/ints": { + "get": { + "tags": [ + "Random" + ], + "summary": "Generate random integers", + "description": "Generate cryptographically verifiable random integers within a custom inclusive range.", + "operationId": "getInts", + "parameters": [ + { + "$ref": "#/components/parameters/ClientSeed" + }, + { + "$ref": "#/components/parameters/Count" + }, + { + "name": "min", + "in": "query", + "description": "Minimum value (inclusive).", + "required": false, + "schema": { + "type": "integer", + "minimum": 0, + "default": 1 + } + }, + { + "name": "max", + "in": "query", + "description": "Maximum value (inclusive). The range max - min + 1 may be at most 2^32 (4294967296).", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "default": 100 + } + }, + { + "$ref": "#/components/parameters/ToolMeta" + }, + { + "$ref": "#/components/parameters/IdempotencyKey" + } + ], + "responses": { + "200": { + "description": "A batch of random integers and the associated server hash.", + "headers": { + "Server-Timing": { + "$ref": "#/components/headers/ServerTiming" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/IntOutcome" + }, + "example": { + "outcome": [ + 42, + 87, + 13, + 65, + 29 + ], + "clientSeed": "my-app", + "serverHash": "9f86d081884c7d65...", + "nonce": 0, + "cursor": 5, + "count": 5, + "min": 1, + "max": 100, + "endpoint": "ints", + "created": 1716566400000, + "shortId": "k7Qm2A9bXz", + "permalink": "https://provable.io/o/k7Qm2A9bXz" + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { "$ref": "#/components/responses/InvalidApiKey" }, + "409": { + "$ref": "#/components/responses/IdempotencyConflict" + }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/ServerError" + } + } + } + }, + "/api/listOutcomes": { + "get": { + "tags": [ + "Verification" + ], + "summary": "List outcomes for a client seed", + "description": "List recorded outcomes for a given client seed, newest first, at most `limit` (default and max 1000) per call. To page, pass `before=:` from the last outcome of the previous page. Password-tool receipts retain verification metadata but never return the generated integers or derivation coordinates.", + "operationId": "listOutcomes", + "parameters": [ + { + "$ref": "#/components/parameters/ClientSeed" + }, + { + "name": "limit", + "in": "query", + "required": false, + "description": "Max outcomes to return (1-1000, default 1000).", + "schema": { "type": "integer", "minimum": 1, "maximum": 1000, "default": 1000 } + }, + { + "name": "before", + "in": "query", + "required": false, + "description": "Keyset cursor `cursor:nonce` from the last outcome of the previous page; returns strictly older outcomes.", + "schema": { "type": "string", "pattern": "^\\d+:\\d+$", "example": "0:120" } + } + ], + "responses": { + "200": { + "description": "List of outcomes for the given client seed.", + "headers": { + "Server-Timing": { + "$ref": "#/components/headers/ServerTiming" + } + }, + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PublicOutcome" + } + }, + "example": [ + { + "outcome": [ + 42, + 87, + 13, + 65, + 29 + ], + "clientSeed": "my-app", + "serverHash": "9f86d081884c7d65...", + "nonce": 0, + "cursor": 5, + "endpoint": "ints", + "created": 1716566400000, + "shortId": "k7Qm2A9bXz", + "permalink": "https://provable.io/o/k7Qm2A9bXz" + } + ] + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { "$ref": "#/components/responses/InvalidApiKey" }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/ServerError" + } + } + } + }, + "/api/merkle": { + "get": { + "tags": [ + "Transparency" + ], + "summary": "List recent daily Merkle roots", + "description": "Returns the most recent daily Merkle roots in reverse chronological order. Each root commits to every outcome generated during that UTC day.", + "operationId": "listMerkleRoots", + "security": [], + "parameters": [ + { + "name": "limit", + "in": "query", + "description": "Maximum number of roots to return (1-90).", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 90, + "default": 30 + } + } + ], + "responses": { + "200": { + "description": "List of recent daily roots.", + "headers": { + "Server-Timing": { + "$ref": "#/components/headers/ServerTiming" + } + }, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "roots": { + "type": "array", + "items": { + "$ref": "#/components/schemas/MerkleRoot" + } + } + } + }, + "example": { + "roots": [ + { + "date": "2026-05-28", + "root": "a3f1c2d4e5...e7", + "leafCount": 14238, + "treeHeight": 14, + "publishedAt": 1716681900000 + }, + { + "date": "2026-05-27", + "root": "b7e2f4a1c9...3d", + "leafCount": 13104, + "treeHeight": 14, + "publishedAt": 1716595500000 + } + ] + } + } + } + }, + "401": { "$ref": "#/components/responses/InvalidApiKey" } + } + } + }, + "/api/merkle/{date}": { + "get": { + "tags": [ + "Transparency" + ], + "summary": "Get a published daily Merkle root", + "description": "Returns the published Merkle root for the given UTC day, plus the leaf count, tree height, and publish timestamp.", + "operationId": "getMerkleRoot", + "security": [], + "parameters": [ + { + "name": "date", + "in": "path", + "required": true, + "description": "UTC date in `YYYY-MM-DD` form.", + "example": "2026-05-23", + "schema": { + "type": "string", + "pattern": "^\\d{4}-\\d{2}-\\d{2}$" + } + } + ], + "responses": { + "200": { + "description": "Published root for that date.", + "headers": { + "Server-Timing": { + "$ref": "#/components/headers/ServerTiming" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MerkleRoot" + }, + "example": { + "date": "2026-05-23", + "root": "a3f1c2...e7", + "leafCount": 14238, + "treeHeight": 14, + "publishedAt": 1716595500000 + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { "$ref": "#/components/responses/InvalidApiKey" }, + "404": { + "description": "No root published for this date yet.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/api/merkle/{date}/proof/{outcomeId}": { + "get": { + "tags": [ + "Transparency" + ], + "summary": "Get an inclusion proof for an outcome", + "description": "Returns the Merkle inclusion proof for `outcomeId` within the published tree for `date`. The proof contains the leaf, its index, the sibling hashes along the path to the root, and the published root itself. Anyone can verify the proof locally by recomputing the root from the leaf and siblings — see the leaf encoding documented at `/transparency` and `/api-docs#merkle`.", + "operationId": "getMerkleProof", + "security": [], + "parameters": [ + { + "name": "date", + "in": "path", + "required": true, + "description": "UTC date in `YYYY-MM-DD` form.", + "example": "2026-05-23", + "schema": { + "type": "string", + "pattern": "^\\d{4}-\\d{2}-\\d{2}$" + } + }, + { + "name": "outcomeId", + "in": "path", + "required": true, + "description": "The outcome's shortId (unique, preferred) or `clientSeed:cursor:nonce`. The triple can repeat across API-key chains; it then resolves to the first match.", + "example": "my-app:5:0", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Inclusion proof.", + "headers": { + "Server-Timing": { + "$ref": "#/components/headers/ServerTiming" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MerkleProof" + }, + "example": { + "date": "2026-05-23", + "outcomeId": "my-app:5:0", + "leaf": { + "outcomeId": "my-app:5:0", + "serverHash": "9f86d081884c7d65...", + "clientSeed": "my-app", + "timestamp": 1716566400000, + "canonical": "my-app:5:0|9f86d081884c7d65...|my-app|1716566400000", + "hash": "4d7e1b2c8a...f3" + }, + "index": 8123, + "leafCount": 14238, + "treeHeight": 14, + "root": "a3f1c2d4e5...e7", + "publishedAt": 1716595500000, + "siblings": [ + { + "position": "right", + "hash": "1a2b3c4d5e...90" + }, + { + "position": "left", + "hash": "6f7e8d9c0b...21" + } + ] + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { "$ref": "#/components/responses/InvalidApiKey" }, + "404": { + "description": "Root not published for that date, or outcome not in that day's tree.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/api/outcome": { + "get": { + "tags": [ + "Verification" + ], + "summary": "Look up a single recorded outcome", + "description": "Fetches a single recorded outcome by its `(clientSeed, cursor, nonce)` triple. Useful for re-fetching a known outcome's full record (including `serverHash`, `endpoint`-specific fields, and `shortId`) without scanning the whole seed via `/api/listOutcomes`. Password-tool receipts never return the generated integers or derivation coordinates. Returns `400` when the outcome is not found.", + "operationId": "getOutcome", + "parameters": [ + { + "$ref": "#/components/parameters/ClientSeed" + }, + { + "name": "cursor", + "in": "query", + "description": "Cursor of the outcome to look up.", + "required": true, + "example": 5, + "schema": { + "type": "integer", + "minimum": 0 + } + }, + { + "name": "nonce", + "in": "query", + "description": "Nonce of the outcome to look up.", + "required": true, + "example": 0, + "schema": { + "type": "integer", + "minimum": 0 + } + } + ], + "responses": { + "200": { + "description": "The recorded outcome.", + "headers": { + "Server-Timing": { + "$ref": "#/components/headers/ServerTiming" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PublicOutcome" + }, + "example": { + "outcome": [ + 42, + 7, + 88, + 13, + 61 + ], + "clientSeed": "my-app", + "serverHash": "9f86d081884c7d65...", + "nonce": 0, + "cursor": 5, + "count": 5, + "min": 1, + "max": 100, + "endpoint": "ints", + "created": 1716566400000, + "shortId": "k7Qm2A9bXz", + "mode": "live", + "permalink": "https://provable.io/o/k7Qm2A9bXz" + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { "$ref": "#/components/responses/InvalidApiKey" }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/ServerError" + } + } + } + }, + "/api/pick": { + "get": { + "tags": [ + "Random" + ], + "summary": "Weighted random pick", + "description": "Pick one item from a list, optionally with per-item weights. Returns the chosen item and its zero-based `index`.", + "operationId": "pickItem", + "parameters": [ + { + "$ref": "#/components/parameters/ClientSeed" + }, + { + "name": "items", + "in": "query", + "description": "Items to choose from. Same encoding as `/api/shuffle`. 1-1000 entries.", + "required": true, + "example": "common,rare,legendary", + "schema": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ] + } + }, + { + "name": "weights", + "in": "query", + "description": "Optional non-negative weights, one per item. Defaults to uniform. Must sum to a positive number.", + "required": false, + "example": "70,25,5", + "schema": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "array", + "items": { + "type": "number" + } + } + ] + } + }, + { + "$ref": "#/components/parameters/IdempotencyKey" + } + ], + "responses": { + "200": { + "description": "The picked item and its index.", + "headers": { + "Server-Timing": { + "$ref": "#/components/headers/ServerTiming" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PickOutcome" + }, + "example": { + "outcome": "legendary", + "index": 2, + "clientSeed": "loot-roll", + "serverHash": "9f86d081884c7d65...", + "nonce": 0, + "cursor": 0, + "count": 1, + "weights": [ + 70, + 25, + 5 + ], + "endpoint": "pick", + "created": 1716566400000 + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { "$ref": "#/components/responses/InvalidApiKey" }, + "409": { + "$ref": "#/components/responses/IdempotencyConflict" + }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/ServerError" + } + } + } + }, + "/api/reveal": { + "post": { + "tags": [ + "Random" + ], + "summary": "Reveal and use a committed server seed (commit-reveal step 2)", + "description": "Submit your `clientSeed` and the generation parameters against a previously committed `commitId`. The server marks the commit revealed (single-use), runs the requested generation against the committed `serverSeed`, persists the outcome, and returns the outcome plus the revealed `serverSeed` so you can independently re-derive the values. Returns `409 Conflict` if the commit has already been revealed, `410 Gone` if it expired, and `404` if it never existed.", + "operationId": "revealCommit", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RevealRequest" + }, + "example": { + "commitId": "8c3d7b9e-1f2a-4c5d-9e8f-7a6b5c4d3e2f", + "clientSeed": "my-app", + "endpoint": "ints", + "params": { + "count": 5, + "min": 1, + "max": 100 + } + } + } + } + }, + "responses": { + "200": { + "description": "The outcome computed from the committed server seed and your client seed, plus the revealed server seed.", + "headers": { + "Server-Timing": { + "$ref": "#/components/headers/ServerTiming" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RevealOutcome" + }, + "example": { + "outcome": [ + 42, + 87, + 13, + 65, + 29 + ], + "clientSeed": "my-app", + "serverHash": "9f86d081884c7d65...", + "serverSeed": "b1946ac92492d2347c6235b4d2611184...", + "nonce": 0, + "cursor": 0, + "count": 5, + "min": 1, + "max": 100, + "endpoint": "ints", + "commitId": "8c3d7b9e-1f2a-4c5d-9e8f-7a6b5c4d3e2f", + "created": 1716566400000 + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { "$ref": "#/components/responses/InvalidApiKey" }, + "404": { + "description": "Commit not found.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "error": "commit not found or expired" + } + } + } + }, + "403": { + "description": "The commit was created with a different API key (or anonymously). Reveal with the key that created it.", + "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" }, "example": { "error": "commit was created with a different API key" } } } + }, + "409": { + "description": "Commit has already been revealed (single-use).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "error": "commit already revealed" + } + } + } + }, + "410": { + "description": "Commit expired before being revealed.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "error": "commit expired" + } + } + } + }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/ServerError" + } + } + } + }, + "/api/rotate": { + "post": { + "tags": [ + "Verification" + ], + "summary": "Rotate the server seed for a client seed", + "description": "Reveals the *previous* `serverSeed` for the given `clientSeed`, then generates a fresh `serverSeed`. `cursor` and `nonce` carry over unchanged, so recorded outcomes keep unique coordinates. This is the **only** endpoint that exposes the one-shot `serverSeed` — `/api/floats`, `/api/ints`, the RNG primitives, and `/api/listOutcomes` only ever surface `serverHash`.\n\n**Per-key hash chains.** Each api key has its own independent hash chain per `clientSeed`. Rotating an authenticated call rotates *only* that key's chain — it does not touch any other key's chain or the anonymous chain.\n\n**Anonymous callers** rotate the shared anonymous chain for the given `clientSeed`. There is no ownership on that chain — any caller (authenticated or not) can rotate it.\n\n**Test keys.** `pk_test_*` keys are rejected with `403` (`code: \"test_mode_forbidden\"`): test mode has no live chain of its own, so rotation is undefined for it.\n\nThe addressed chain must already have at least one recorded outcome (i.e. that key — or an anonymous caller, for the anon chain — has called `/api/floats` or `/api/ints` with this `clientSeed`), otherwise the response is `404`.", + "operationId": "rotateServerSeed", + "security": [ + {}, + { + "ApiKeyAuth": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "clientSeed": { + "type": "string", + "description": "The client seed whose serverSeed should be revealed and rotated." + } + }, + "required": [ + "clientSeed" + ] + }, + "example": { + "clientSeed": "my-app" + } + } + } + }, + "responses": { + "200": { + "description": "Previous `serverSeed` revealed (verify by checking `sha256(revealed.serverSeed) === revealed.serverHash`) plus the new state. Future calls to `/api/floats`/`/api/ints` for this `clientSeed` will derive from `next.serverHash` at the `next.cursor` / `next.nonce` returned here.", + "headers": { + "Server-Timing": { + "$ref": "#/components/headers/ServerTiming" + } + }, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "clientSeed": { + "type": "string" + }, + "revealed": { + "type": "object", + "properties": { + "serverSeed": { + "type": "string", + "nullable": true, + "description": "The previous server seed, now revealed. `null` only on a freshly-created row that never carried one." + }, + "serverHash": { + "type": "string", + "nullable": true + }, + "cursor": { + "type": "integer", + "minimum": 0 + }, + "nonce": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "serverSeed", + "serverHash", + "cursor", + "nonce" + ] + }, + "next": { + "type": "object", + "properties": { + "serverHash": { + "type": "string", + "description": "Hash of the freshly generated server seed. The new seed itself stays secret until the next rotate." + }, + "cursor": { + "type": "integer", + "minimum": 0 + }, + "nonce": { + "type": "integer", + "minimum": 0 + }, + "rotatedAt": { + "type": "integer", + "format": "int64", + "description": "Unix ms at which the rotation was committed." + } + }, + "required": [ + "serverHash", + "cursor", + "nonce", + "rotatedAt" + ] + } + }, + "required": [ + "clientSeed", + "revealed", + "next" + ] + }, + "example": { + "clientSeed": "my-app", + "revealed": { + "serverSeed": "b1946ac92492d2347c6235b4d2611184a3a6f3c1e5c1c4d8e6b7f1a2c3d4e5f6", + "serverHash": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08", + "cursor": 7, + "nonce": 3 + }, + "next": { + "serverHash": "a3b1c5d7e9f1a3b5c7d9e1f3a5b7c9d1e3f5a7b9c1d3e5f7a9b1c3d5e7f9a1b3", + "cursor": 0, + "nonce": 0, + "rotatedAt": 1716566400000 + } + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { "$ref": "#/components/responses/InvalidApiKey" }, + "403": { + "description": "The calling key is a `pk_test_*` test key. Test mode has no live chain to rotate.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "error": "rotate requires a live (pk_live_*) api key or anonymous call; test keys have no live chain", + "code": "test_mode_forbidden" + } + } + } + }, + "404": { + "description": "No `seed_state` exists for the addressed chain yet (for authed calls: this api key's chain for this `clientSeed`; for anonymous calls: the anon chain for this `clientSeed`). Call `/api/floats` or `/api/ints` first.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "error": "no seed_state for this (api key, clientSeed) chain — generate an outcome first" + } + } + } + }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/ServerError" + } + } + } + }, + "/api/shuffle": { + "get": { + "tags": [ + "Random" + ], + "summary": "Shuffle an array", + "description": "Return a uniformly fair shuffle of a caller-supplied array. The same `clientSeed`/`cursor`/`nonce` triple always yields the same permutation, so the result is fully verifiable.", + "operationId": "shuffleItems", + "parameters": [ + { + "$ref": "#/components/parameters/ClientSeed" + }, + { + "name": "items", + "in": "query", + "description": "Items to shuffle. Pass a JSON array (`items=[\"a\",\"b\",\"c\"]`), a comma-separated list (`items=a,b,c`), or repeat the parameter (`items=a&items=b&items=c`). 1-1000 entries.", + "required": true, + "example": "a,b,c,d", + "schema": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ] + } + }, + { + "$ref": "#/components/parameters/ToolMeta" + }, + { + "$ref": "#/components/parameters/IdempotencyKey" + } + ], + "responses": { + "200": { + "description": "The shuffled array and the associated server hash.", + "headers": { + "Server-Timing": { + "$ref": "#/components/headers/ServerTiming" + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ShuffleOutcome" + }, + "example": { + "outcome": [ + "c", + "a", + "d", + "b" + ], + "clientSeed": "my-app", + "serverHash": "9f86d081884c7d65...", + "nonce": 0, + "cursor": 0, + "count": 4, + "endpoint": "shuffle", + "created": 1716566400000 + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { "$ref": "#/components/responses/InvalidApiKey" }, + "409": { + "$ref": "#/components/responses/IdempotencyConflict" + }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/ServerError" + } + } + } + }, + "/api/stream": { + "get": { + "tags": [ + "Random" + ], + "summary": "Stream outcomes as Server-Sent Events", + "description": "Open a long-lived Server-Sent Events (SSE) connection that emits one verifiable outcome per `intervalMs`, up to a server-enforced 10-minute cap.\n\n**The response shape differs from every other endpoint here.** Instead of returning a single JSON body, the server holds the connection open and writes a stream of `text/event-stream` frames. Each frame is a self-contained `event: outcome` message whose `data:` field is a full JSON outcome (identical shape to the matching non-streaming endpoint, plus an `outcomeId` of `clientSeed:cursor:nonce`). Every emitted outcome verifies independently via `/api/verifyServerHash`.\n\nHeartbeat comments (`: heartbeat …`) are sent every ~15 seconds. When the duration cap or quota is reached the server emits a terminal `event: done` frame and closes — reconnect to keep streaming. Closing the client (e.g. `EventSource.close()`) cleanly stops billing. Each emitted outcome counts as one billed call for live-key streams.\n\n**Resuming after a disconnect.** Every `event: outcome` frame includes an `id:` line of `clientSeed:cursor:nonce`. On a transient drop, browsers' built-in `EventSource` auto-reconnects and replays it as a `Last-Event-ID` request header; raw `fetch` clients can pass the same value as a `?lastEventId=` query parameter. Either way the server only emits outcomes strictly after that point on the same `clientSeed`, so reconnects don't double-count or skip — and skipped duplicates aren't billed.", + "operationId": "streamOutcomes", + "parameters": [ + { + "$ref": "#/components/parameters/ClientSeed" + }, + { + "name": "endpoint", + "in": "query", + "description": "Which generator to stream.", + "required": true, + "example": "floats", + "schema": { + "type": "string", + "enum": [ + "floats", + "ints", + "shuffle", + "pick", + "bytes", + "dice", + "gaussian" + ] + } + }, + { + "name": "intervalMs", + "in": "query", + "description": "Milliseconds between outcomes.", + "required": false, + "schema": { + "type": "integer", + "minimum": 100, + "maximum": 60000, + "default": 1000 + } + }, + { + "name": "lastEventId", + "in": "query", + "description": "Resume after a disconnect. Pass the most recent `outcomeId` you received (`clientSeed:cursor:nonce`); the server will only emit outcomes strictly after that point on the same `clientSeed`. Equivalent to the `Last-Event-ID` request header that `EventSource` sends automatically on auto-reconnect.", + "required": false, + "example": "my-app:42:0", + "schema": { + "type": "string" + } + }, + { + "name": "Last-Event-ID", + "in": "header", + "description": "Standard SSE resume header. Same semantics as the `lastEventId` query parameter — emit only outcomes strictly after this `clientSeed:cursor:nonce`. Sent automatically by `EventSource` on auto-reconnect.", + "required": false, + "example": "my-app:42:0", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "An event stream. The body is `text/event-stream`, not JSON. Two event types are emitted: `outcome` (one per interval, `data:` is a JSON outcome with an extra `outcomeId` field) and `done` (terminal, `data:` describes the close `reason` — `max_duration` or `quota_exceeded`).", + "content": { + "text/event-stream": { + "schema": { + "type": "string" + }, + "example": "id: my-app:0:0\nevent: outcome\ndata: {\"outcome\":[0.4823],\"clientSeed\":\"my-app\",\"serverHash\":\"9f86d0...\",\"nonce\":0,\"cursor\":0,\"count\":1,\"endpoint\":\"floats\",\"created\":1716566400000,\"outcomeId\":\"my-app:0:0\"}\n\n: heartbeat 1716566415000\n\nevent: done\ndata: {\"reason\":\"max_duration\",\"count\":600,\"durationMs\":600000}\n\n" + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { "$ref": "#/components/responses/InvalidApiKey" }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/ServerError" + } + } + } + }, + "/api/verifyServerHash": { + "get": { + "tags": [ + "Verification" + ], + "summary": "Verify a server hash", + "description": "Verify that a server hash matches our records for a given client seed. Returns `true` if the hash is authentic.", + "operationId": "verifyServerHash", + "parameters": [ + { + "$ref": "#/components/parameters/ClientSeed" + }, + { + "name": "serverHash", + "in": "query", + "description": "The server hash returned with the original outcome.", + "required": true, + "example": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Verification result. Returns the literal `true` when either the current `seed_state` for this client seed still carries the supplied `serverHash` (a one-line fast path) **or** any recorded outcome under this client seed (e.g. a revealed commit-reveal outcome) was generated against that `serverHash`. Otherwise returns a `VerifyResult` object whose `verified` flag and `outcomes` array describe whether — and where — the (clientSeed, serverHash) pair appears in recorded history.", + "headers": { + "Server-Timing": { + "$ref": "#/components/headers/ServerTiming" + } + }, + "content": { + "application/json": { + "schema": { + "oneOf": [ + { + "type": "boolean", + "enum": [ + true + ], + "description": "Fast-path match against live seed_state." + }, + { + "$ref": "#/components/schemas/VerifyResult" + } + ] + }, + "example": { + "verified": true, + "clientSeed": "my-app", + "serverHash": "9f86d081884c7d65...", + "outcomes": [ + { + "shortId": "k7Qm2A9bXz", + "permalink": "https://provable.io/o/k7Qm2A9bXz", + "endpoint": "ints", + "cursor": 5, + "nonce": 0, + "created": 1716566400000 + } + ] + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { "$ref": "#/components/responses/InvalidApiKey" }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/ServerError" + } + } + } + }, + "/api/verifyShortId": { + "get": { + "tags": [ + "Verification" + ], + "summary": "Verify an outcome by shortId", + "description": "Public, no-auth verifier used by the `/verify` landing page. Given a `shortId` returned by any random-generating endpoint (or visible in an `/o/:id` permalink), returns recorded metadata and a server-computed verification verdict. Password-tool receipts never return the generated integers or derivation coordinates. A response is `verified: true` when either (a) the live seed state still carries the same `serverHash` or (b) the `serverSeed` has been revealed and `sha256(serverSeed)` reproduces the recorded `serverHash`.", + "operationId": "verifyShortId", + "parameters": [ + { + "name": "shortId", + "in": "query", + "description": "The 4-32 character alphanumeric `shortId` for the outcome.", + "required": true, + "example": "k7Qm2A9bXz", + "schema": { + "type": "string", + "pattern": "^[A-Za-z0-9]{4,32}$" + } + } + ], + "responses": { + "200": { + "description": "Verification result for the outcome.", + "headers": { + "Server-Timing": { + "$ref": "#/components/headers/ServerTiming" + } + }, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "verified", + "reason", + "shortId" + ], + "properties": { + "verified": { + "type": "boolean" + }, + "reason": { + "type": "string" + }, + "shortId": { + "type": "string" + }, + "clientSeed": { + "type": "string", + "nullable": true + }, + "serverHash": { + "type": "string" + }, + "cursor": { + "type": "integer", + "minimum": 0, + "nullable": true + }, + "nonce": { + "type": "integer", + "minimum": 0, + "nullable": true + }, + "endpoint": { + "type": "string", + "nullable": true + }, + "outcome": { + "description": "The original generated result. Its shape depends on endpoint. Null for password-tool records so the password cannot be reconstructed through this public lookup.", + "nullable": true, + "oneOf": [ + { "type": "array", "items": {} }, + { "type": "object" } + ] + }, + "count": { + "type": "integer", + "minimum": 1, + "nullable": true + }, + "min": { + "type": "integer", + "nullable": true + }, + "max": { + "type": "integer", + "nullable": true + }, + "notation": { + "type": "string" + }, + "toolMeta": { + "type": "object", + "nullable": true, + "additionalProperties": true + }, + "created": { + "type": "integer", + "nullable": true + }, + "redacted": { + "type": "boolean", + "description": "True when password result material was removed from the public response." + }, + "permalink": { + "type": "string", + "format": "uri" + } + } + }, + "example": { + "verified": true, + "reason": "Server seed hash on file matches the current state for this client seed.", + "shortId": "k7Qm2A9bXz", + "clientSeed": "my-app", + "serverHash": "9f86d081884c7d65...", + "cursor": 5, + "nonce": 0, + "endpoint": "ints", + "created": 1716566400000, + "permalink": "https://provable.io/o/k7Qm2A9bXz" + } + } + } + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { "$ref": "#/components/responses/InvalidApiKey" }, + "404": { + "$ref": "#/components/responses/BadRequest" + }, + "429": { + "$ref": "#/components/responses/RateLimited" + }, + "500": { + "$ref": "#/components/responses/ServerError" + } + } + } + }, + "/o/{id}": { + "get": { + "tags": [ + "Verification" + ], + "summary": "Public outcome permalink page", + "description": "Public, no-auth HTML page for a recorded outcome. Anyone with the `shortId` can open it to see the endpoint, parameters, client seed, server hash, the generated values, and a server-side **Verified ✓** / **Mismatch ✗** badge. Includes `og:image` / `og:title` meta tags so links unfurl in Slack, Discord, and X. The `shortId` is returned by `/api/floats`, `/api/ints`, `/api/listOutcomes`, and `/api/verifyServerHash`.", + "operationId": "getOutcomePermalink", + "security": [], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The `shortId` returned with the outcome (~10 alphanumeric characters).", + "example": "k7Qm2A9bXz", + "schema": { + "type": "string", + "minLength": 4, + "maxLength": 32, + "pattern": "^[A-Za-z0-9]+$" + } + } + ], + "responses": { + "200": { + "description": "HTML permalink page rendering the outcome.", + "content": { + "text/html": { + "schema": { + "type": "string" + } + } + } + }, + "404": { + "description": "No outcome exists with that short ID.", + "content": { + "text/html": { + "schema": { + "type": "string" + } + } + } + } + } + } + }, + "/o/{id}/og.png": { + "get": { + "tags": [ + "Verification" + ], + "summary": "Dynamic social-preview image for an outcome permalink", + "description": "Returns a 1200×630 PNG rendered from the outcome (shortId, endpoint, **Verified ✓** / **Unverified** badge, count, and a sample of the generated values). Used as the `og:image` / `twitter:image` for `/o/{id}` so links unfurl with a per-outcome card in Slack, Discord, and X. Responses are cached (5 minutes). If the outcome doesn't exist or rendering fails, the generic site `og-image.jpg` is returned with a short cache so unfurls never break.", + "operationId": "getOutcomeOgImage", + "security": [], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "The `shortId` returned with the outcome (~10 alphanumeric characters).", + "example": "k7Qm2A9bXz", + "schema": { + "type": "string", + "minLength": 4, + "maxLength": 32, + "pattern": "^[A-Za-z0-9]+$" + } + } + ], + "responses": { + "200": { + "description": "1200×630 PNG preview card (or the fallback `og-image.jpg` if the shortId is unknown or rendering fails).", + "content": { + "image/png": { + "schema": { + "type": "string", + "format": "binary" + } + }, + "image/jpeg": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + } + } + } + } + }, + "components": { + "securitySchemes": { + "ApiKeyAuth": { + "type": "apiKey", + "in": "header", + "name": "x-api-key", + "description": "Send your API key in the `x-api-key` header. Two key kinds are supported:\n\n- `pk_live_…` — live key, real cryptographic randomness, counts toward your daily quota, fires webhooks.\n- `pk_test_…` — test key, deterministic per (account, clientSeed) so the same parameters always return the same outcome (any test key on your account with the same `clientSeed` yields identical results). Test calls are flagged `mode: \"test\"`, don't appear in usage stats, and don't fire webhooks. They're still subject to the anonymous per-minute rate limit.\n\nCreate or rotate keys on the dashboard at https://provable.io/dashboard.\n\n**Per-key restrictions.** Each key may carry an allowed-IP list (CIDR ranges) and/or an allowed-Referer-origin list. Empty lists mean no restriction. Requests that fail an active restriction are rejected with `403` and a JSON body of `{ \"error\": \"…\", \"code\": \"ip_not_allowed\" | \"referer_not_allowed\" }`, and the denial is logged to the key's activity in the dashboard." + }, + "BearerAuth": { + "type": "http", + "scheme": "bearer", + "description": "Send your API key as a bearer token in the `Authorization` header. Accepts either `pk_live_…` or `pk_test_…` keys; see the `ApiKeyAuth` description for behavior differences.\n\nSame per-key IP / Referer-origin restrictions apply as with `ApiKeyAuth`: a request that doesn't match an active allowlist is rejected with `403` and code `ip_not_allowed` or `referer_not_allowed`." + } + }, + "headers": { + "ServerTiming": { + "description": "Server processing duration for this finite successful live response, formatted as `total;dur=`. The duration is measured by the server and does not include network transfer, client work, or the browser's full round-trip time. The header is omitted for test-key responses, when a reliable measurement is unavailable, and is not guaranteed on error responses. It is intentionally not reported for SSE responses because an initial-response setup measurement would not represent the lifetime of the stream.", + "schema": { + "type": "string", + "pattern": "^total;dur=[0-9]+(?:\\.[0-9]+)?$" + }, + "example": "total;dur=12.4" + } + }, + "parameters": { + "ClientSeed": { + "name": "clientSeed", + "in": "query", + "description": "Your seed for this generation. Combined with the server seed to produce provably fair output. Defaults to the literal string `\"test\"` when omitted, so anonymous demos work out of the box — production callers should always pass a stable, caller-owned value (your account id, a session id, etc.) to keep their own deterministic seed history.", + "required": false, + "schema": { + "type": "string", + "minLength": 1, + "default": "test" + } + }, + "Count": { + "name": "count", + "in": "query", + "description": "Number of values to generate (1-100).", + "required": false, + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 100, + "default": 1 + } + }, + "ToolMeta": { + "name": "toolMeta", + "in": "query", + "description": "Reserved JSON object (up to 512 characters) used by supported Provable.io browser tools. API clients normally omit this.", + "required": false, + "schema": { + "type": "string", + "maxLength": 512 + } + }, + "IdempotencyKey": { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Optional opaque string (≤255 chars). When supplied on any random-generating endpoint (`/api/floats`, `/api/ints`, `/api/shuffle`, `/api/pick`, `/api/bytes`, `/api/dice`, `/api/gaussian`, `/api/batch`), the server stores the response for 24 hours and returns the **same** status, body, and `Content-Type` for any retry that uses the same key — replays are flagged with the `Idempotent-Replayed: true` response header and do **not** consume quota. Reusing the key with a different request body or query parameters returns `409 Conflict` with code `idempotency_key_conflict`. Keys are scoped per API key (or per IP for anonymous calls), so two callers can use the same opaque value without collision.", + "example": "8c3d7b9e-1f2a-4c5d-9e8f-7a6b5c4d3e2f", + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 255 + } + } + }, + "schemas": { + "BaseOutcome": { + "type": "object", + "description": "Fields shared by every recorded outcome. Each concrete `*Outcome` schema extends this with its own `endpoint` discriminator value, `outcome` shape, and any endpoint-specific parameters.", + "properties": { + "clientSeed": { + "type": "string" + }, + "serverHash": { + "type": "string", + "description": "SHA-256 hash of the server seed used for this generation." + }, + "nonce": { + "type": "integer", + "minimum": 0 + }, + "cursor": { + "type": "integer", + "minimum": 0 + }, + "count": { + "type": "integer", + "minimum": 1, + "description": "Number of underlying draws this outcome represents (e.g. requested float count, number of dice rolled, items shuffled)." + }, + "created": { + "type": "integer", + "format": "int64", + "description": "Unix timestamp in milliseconds." + }, + "shortId": { + "type": "string", + "description": "Stable ~10-character public ID for this outcome. Used to build a shareable permalink at /o/{shortId}." + }, + "mode": { + "type": "string", + "enum": [ + "live", + "test" + ], + "description": "`live` for real cryptographic randomness drawn from the (api key, clientSeed) hash chain. `test` is returned when the call was authenticated with a `pk_test_…` key; the outcome is deterministic per (account, clientSeed), bypasses the live chain entirely, is excluded from live usage stats, and does not trigger webhooks." + }, + "toolMeta": { + "type": "object", + "description": "Optional display settings saved by Provable.io's browser tools so a shared result can be reconstructed.", + "additionalProperties": true + }, + "redacted": { + "type": "boolean", + "description": "Present on public lookup responses. True when sensitive password result material was removed." + } + }, + "required": [ + "clientSeed", + "serverHash", + "nonce", + "cursor", + "count", + "created", + "shortId", + "mode" + ] + }, + "PasswordReceipt": { + "type": "object", + "description": "Public verification receipt for a password-tool call. The generated integer stream and its derivation coordinates are deliberately null.", + "required": [ + "serverHash", + "endpoint", + "outcome", + "shortId", + "toolMeta", + "redacted" + ], + "properties": { + "serverHash": { + "type": "string" + }, + "endpoint": { + "type": "string", + "enum": [ + "ints" + ] + }, + "outcome": { + "nullable": true + }, + "clientSeed": { + "type": "string", + "nullable": true + }, + "cursor": { + "type": "integer", + "nullable": true + }, + "nonce": { + "type": "integer", + "nullable": true + }, + "count": { + "type": "integer", + "nullable": true + }, + "min": { + "type": "integer", + "nullable": true + }, + "max": { + "type": "integer", + "nullable": true + }, + "created": { + "type": "integer", + "format": "int64", + "nullable": true + }, + "shortId": { + "type": "string" + }, + "mode": { + "type": "string" + }, + "toolMeta": { + "type": "object", + "additionalProperties": true + }, + "redacted": { + "type": "boolean", + "enum": [ + true + ] + }, + "permalink": { + "type": "string", + "format": "uri", + "nullable": true + } + } + }, + "PublicOutcome": { + "description": "A normal outcome or a redacted password verification receipt returned by public lookup endpoints.", + "oneOf": [ + { + "$ref": "#/components/schemas/Outcome" + }, + { + "$ref": "#/components/schemas/PasswordReceipt" + } + ], + "discriminator": { + "propertyName": "redacted", + "mapping": { + "false": "#/components/schemas/Outcome", + "true": "#/components/schemas/PasswordReceipt" + } + } + }, + "Outcome": { + "description": "Discriminated union of every concrete outcome shape returned by the random-generating endpoints. Use the `endpoint` field to pick the matching schema.", + "oneOf": [ + { + "$ref": "#/components/schemas/FloatOutcome" + }, + { + "$ref": "#/components/schemas/IntOutcome" + }, + { + "$ref": "#/components/schemas/ShuffleOutcome" + }, + { + "$ref": "#/components/schemas/PickOutcome" + }, + { + "$ref": "#/components/schemas/BytesOutcome" + }, + { + "$ref": "#/components/schemas/DiceOutcome" + }, + { + "$ref": "#/components/schemas/GaussianOutcome" + } + ], + "discriminator": { + "propertyName": "endpoint", + "mapping": { + "floats": "#/components/schemas/FloatOutcome", + "ints": "#/components/schemas/IntOutcome", + "shuffle": "#/components/schemas/ShuffleOutcome", + "pick": "#/components/schemas/PickOutcome", + "bytes": "#/components/schemas/BytesOutcome", + "dice": "#/components/schemas/DiceOutcome", + "gaussian": "#/components/schemas/GaussianOutcome" + } + } + }, + "VerifyResult": { + "type": "object", + "description": "Result of /api/verifyServerHash, including any recorded outcomes matching the (clientSeed, serverHash) pair.", + "properties": { + "verified": { + "type": "boolean", + "description": "True when the server hash matches what we have on file for this client seed." + }, + "clientSeed": { + "type": "string" + }, + "serverHash": { + "type": "string" + }, + "outcomes": { + "type": "array", + "description": "Permalinks for every recorded outcome under this (clientSeed, serverHash). May be empty if none were recorded.", + "items": { + "type": "object", + "properties": { + "shortId": { + "type": "string" + }, + "permalink": { + "type": "string", + "format": "uri" + }, + "endpoint": { + "type": "string", + "nullable": true + }, + "cursor": { + "type": "integer" + }, + "nonce": { + "type": "integer" + }, + "created": { + "type": "integer", + "format": "int64", + "nullable": true + } + }, + "required": [ + "shortId", + "permalink" + ] + } + } + }, + "required": [ + "verified", + "clientSeed", + "serverHash", + "outcomes" + ] + }, + "FloatOutcome": { + "allOf": [ + { + "$ref": "#/components/schemas/BaseOutcome" + }, + { + "type": "object", + "properties": { + "outcome": { + "type": "array", + "items": { + "type": "number", + "format": "double", + "minimum": 0, + "maximum": 1 + } + }, + "endpoint": { + "type": "string", + "enum": [ + "floats" + ] + }, + "mode": { + "type": "string", + "enum": [ + "live", + "test" + ], + "description": "`live` for real cryptographic randomness. `test` is returned when the call was authenticated with a `pk_test_…` key; the outcome is deterministic per (account, clientSeed), is excluded from live usage stats, and does not trigger webhooks." + }, + "permalink": { + "type": "string", + "format": "uri", + "description": "Absolute public URL anyone can open to view and re-verify this outcome." + } + }, + "required": [ + "outcome", + "endpoint", + "mode", + "permalink" + ] + } + ] + }, + "IntOutcome": { + "allOf": [ + { + "$ref": "#/components/schemas/BaseOutcome" + }, + { + "type": "object", + "properties": { + "outcome": { + "type": "array", + "items": { + "type": "integer" + } + }, + "endpoint": { + "type": "string", + "enum": [ + "ints" + ] + }, + "min": { + "type": "integer", + "description": "Inclusive lower bound used for this draw." + }, + "max": { + "type": "integer", + "description": "Inclusive upper bound used for this draw." + }, + "mode": { + "type": "string", + "enum": [ + "live", + "test" + ], + "description": "`live` for real cryptographic randomness. `test` is returned when the call was authenticated with a `pk_test_…` key; the outcome is deterministic per (account, clientSeed), is excluded from live usage stats, and does not trigger webhooks." + }, + "permalink": { + "type": "string", + "format": "uri", + "description": "Absolute public URL anyone can open to view and re-verify this outcome." + } + }, + "required": [ + "outcome", + "endpoint", + "min", + "max", + "mode", + "permalink" + ] + } + ] + }, + "MerkleRoot": { + "type": "object", + "description": "A published daily Merkle root over every outcome produced in a single UTC day.", + "properties": { + "date": { + "type": "string", + "description": "UTC date in YYYY-MM-DD form.", + "pattern": "^\\d{4}-\\d{2}-\\d{2}$" + }, + "root": { + "type": "string", + "description": "Hex-encoded SHA-256 root. Empty string when the day had zero outcomes." + }, + "leafCount": { + "type": "integer", + "minimum": 0 + }, + "treeHeight": { + "type": "integer", + "minimum": 0 + }, + "publishedAt": { + "type": "integer", + "format": "int64", + "description": "Unix timestamp in milliseconds when the root was published." + } + }, + "required": [ + "date", + "root", + "leafCount", + "treeHeight", + "publishedAt" + ] + }, + "MerkleProof": { + "type": "object", + "description": "Inclusion proof for a single outcome within a published daily Merkle tree.", + "properties": { + "date": { + "type": "string", + "pattern": "^\\d{4}-\\d{2}-\\d{2}$" + }, + "outcomeId": { + "type": "string", + "description": "`clientSeed:cursor:nonce`." + }, + "leaf": { + "type": "object", + "properties": { + "outcomeId": { + "type": "string" + }, + "serverHash": { + "type": "string" + }, + "clientSeed": { + "type": "string" + }, + "timestamp": { + "type": "integer", + "format": "int64" + }, + "canonical": { + "type": "string", + "description": "`outcomeId|serverHash|clientSeed|timestamp` — the exact bytes that get hashed into the leaf." + }, + "hash": { + "type": "string", + "description": "Hex of `SHA256(0x00 || utf8(canonical))`." + } + }, + "required": [ + "canonical", + "hash" + ] + }, + "index": { + "type": "integer", + "minimum": 0, + "description": "Zero-based position of the leaf in the sorted day." + }, + "leafCount": { + "type": "integer", + "minimum": 1 + }, + "treeHeight": { + "type": "integer", + "minimum": 0 + }, + "root": { + "type": "string", + "description": "Published root the proof terminates at." + }, + "publishedAt": { + "type": "integer", + "format": "int64" + }, + "siblings": { + "type": "array", + "description": "Sibling hashes from leaf level up to the root.", + "items": { + "type": "object", + "properties": { + "position": { + "type": "string", + "enum": [ + "left", + "right" + ], + "description": "Side of the sibling relative to the accumulator: 'left' means `SHA256(0x01 || sibling || acc)`, 'right' means `SHA256(0x01 || acc || sibling)`." + }, + "hash": { + "type": "string" + } + }, + "required": [ + "position", + "hash" + ] + } + } + }, + "required": [ + "date", + "outcomeId", + "leaf", + "index", + "leafCount", + "root", + "siblings" + ] + }, + "ShuffleOutcome": { + "allOf": [ + { + "$ref": "#/components/schemas/BaseOutcome" + }, + { + "type": "object", + "properties": { + "outcome": { + "type": "array", + "description": "The input array shuffled into its verifiable permutation. Same length and contents as the request.", + "items": {} + }, + "endpoint": { + "type": "string", + "enum": [ + "shuffle" + ] + }, + "permalink": { + "type": "string", + "format": "uri", + "description": "Absolute public URL anyone can open to view and re-verify this outcome." + } + }, + "required": [ + "outcome", + "endpoint", + "permalink" + ] + } + ] + }, + "Commit": { + "type": "object", + "description": "A pre-committed server seed published by the server. Hold onto `commitId` and `serverHash`; reveal before `expiresAt` (Unix ms) by calling `/api/reveal`.", + "properties": { + "commitId": { + "type": "string", + "format": "uuid" + }, + "serverHash": { + "type": "string", + "description": "SHA-256 hash of the secret server seed." + }, + "expiresAt": { + "type": "integer", + "format": "int64", + "description": "Unix timestamp in ms after which the commit is no longer revealable." + } + }, + "required": [ + "commitId", + "serverHash", + "expiresAt" + ] + }, + "RevealRequest": { + "type": "object", + "properties": { + "commitId": { + "type": "string", + "format": "uuid", + "description": "The `commitId` returned by `/api/commit`." + }, + "clientSeed": { + "type": "string", + "minLength": 1 + }, + "endpoint": { + "type": "string", + "enum": [ + "floats", + "ints" + ], + "description": "Which generator to run against the committed server seed." + }, + "params": { + "type": "object", + "description": "Generator parameters. For `floats`: `{ count }`. For `ints`: `{ count, min, max }`.", + "properties": { + "count": { + "type": "integer", + "minimum": 1, + "maximum": 100, + "default": 1 + }, + "min": { + "type": "integer", + "minimum": 0, + "default": 1 + }, + "max": { + "type": "integer", + "minimum": 1, + "default": 100 + } + } + } + }, + "required": [ + "commitId", + "clientSeed", + "endpoint" + ] + }, + "RevealOutcome": { + "allOf": [ + { + "$ref": "#/components/schemas/BaseOutcome" + }, + { + "type": "object", + "description": "Outcome returned from `/api/reveal`. Always uses the committed server seed; `endpoint` is restricted to the two generators the commit-reveal flow supports.", + "properties": { + "outcome": { + "type": "array", + "description": "Generated values. `number` items for `endpoint: \"floats\"` (each in [0, 1)); `integer` items for `endpoint: \"ints\"`.", + "items": { + "type": "number" + } + }, + "endpoint": { + "type": "string", + "enum": [ + "floats", + "ints" + ] + }, + "min": { + "type": "integer", + "description": "Inclusive lower bound (only present when `endpoint: \"ints\"`)." + }, + "max": { + "type": "integer", + "description": "Inclusive upper bound (only present when `endpoint: \"ints\"`)." + }, + "serverSeed": { + "type": "string", + "description": "The now-revealed server seed. Verify by checking SHA-256(serverSeed) === serverHash." + }, + "commitId": { + "type": "string", + "format": "uuid" + } + }, + "required": [ + "outcome", + "endpoint", + "serverSeed", + "commitId" + ] + } + ] + }, + "PickOutcome": { + "allOf": [ + { + "$ref": "#/components/schemas/BaseOutcome" + }, + { + "type": "object", + "properties": { + "outcome": { + "description": "The picked item (any JSON value drawn from the input `items` array)." + }, + "index": { + "type": "integer", + "minimum": 0, + "description": "Zero-based index of the picked item." + }, + "weights": { + "type": "array", + "nullable": true, + "description": "The per-item weights supplied with the request, or `null` when the caller used the default uniform distribution.", + "items": { + "type": "number", + "minimum": 0 + } + }, + "endpoint": { + "type": "string", + "enum": [ + "pick" + ] + }, + "permalink": { + "type": "string", + "format": "uri", + "description": "Absolute public URL anyone can open to view and re-verify this outcome." + } + }, + "required": [ + "outcome", + "endpoint", + "index", + "weights", + "permalink" + ] + } + ] + }, + "BytesOutcome": { + "allOf": [ + { + "$ref": "#/components/schemas/BaseOutcome" + }, + { + "type": "object", + "properties": { + "outcome": { + "type": "string", + "description": "Random bytes encoded as `hex` or `base64`, matching the `encoding` field." + }, + "encoding": { + "type": "string", + "enum": [ + "hex", + "base64" + ] + }, + "endpoint": { + "type": "string", + "enum": [ + "bytes" + ] + }, + "permalink": { + "type": "string", + "format": "uri", + "description": "Absolute public URL anyone can open to view and re-verify this outcome." + } + }, + "required": [ + "outcome", + "endpoint", + "encoding", + "permalink" + ] + } + ] + }, + "DiceOutcome": { + "allOf": [ + { + "$ref": "#/components/schemas/BaseOutcome" + }, + { + "type": "object", + "properties": { + "outcome": { + "type": "object", + "properties": { + "notation": { + "type": "string", + "description": "Canonical `NdM`, `NdM+K`, or `NdM-K` form of the roll." + }, + "rolls": { + "type": "array", + "items": { + "type": "integer", + "minimum": 1 + } + }, + "modifier": { + "type": "integer" + }, + "total": { + "type": "integer", + "description": "Sum of `rolls` plus `modifier`." + } + }, + "required": [ + "notation", + "rolls", + "modifier", + "total" + ] + }, + "sides": { + "type": "integer", + "minimum": 2, + "description": "Number of sides on each die (parsed from the request notation)." + }, + "modifier": { + "type": "integer", + "description": "Flat modifier (parsed from the request notation)." + }, + "endpoint": { + "type": "string", + "enum": [ + "dice" + ] + }, + "permalink": { + "type": "string", + "format": "uri", + "description": "Absolute public URL anyone can open to view and re-verify this outcome." + } + }, + "required": [ + "outcome", + "endpoint", + "sides", + "modifier", + "permalink" + ] + } + ] + }, + "GaussianOutcome": { + "allOf": [ + { + "$ref": "#/components/schemas/BaseOutcome" + }, + { + "type": "object", + "description": "Samples from a `normal`, `exponential`, or `poisson` distribution. Only the parameters relevant to the chosen `distribution` are present (`mean`/`stddev` for `normal`, `lambda` for `exponential` and `poisson`).", + "properties": { + "outcome": { + "type": "array", + "items": { + "type": "number" + } + }, + "distribution": { + "type": "string", + "enum": [ + "normal", + "exponential", + "poisson" + ] + }, + "mean": { + "type": "number", + "description": "Mean (μ). Present only when `distribution: \"normal\"`." + }, + "stddev": { + "type": "number", + "exclusiveMinimum": 0, + "description": "Standard deviation (σ). Present only when `distribution: \"normal\"`." + }, + "lambda": { + "type": "number", + "exclusiveMinimum": 0, + "description": "Rate parameter (λ). Present only when `distribution: \"exponential\"` or `\"poisson\"`." + }, + "endpoint": { + "type": "string", + "enum": [ + "gaussian" + ] + }, + "permalink": { + "type": "string", + "format": "uri", + "description": "Absolute public URL anyone can open to view and re-verify this outcome." + } + }, + "required": [ + "outcome", + "endpoint", + "distribution", + "permalink" + ] + } + ] + }, + "BatchRequest": { + "type": "object", + "required": [ + "draws" + ], + "properties": { + "draws": { + "type": "array", + "minItems": 1, + "maxItems": 50, + "items": { + "type": "object", + "required": [ + "endpoint" + ], + "properties": { + "endpoint": { + "type": "string", + "enum": [ + "floats", + "ints", + "shuffle", + "pick", + "bytes", + "dice", + "gaussian" + ], + "description": "Which random-generating endpoint to invoke for this draw." + }, + "params": { + "type": "object", + "description": "The same parameters you would pass as query string to the single-draw endpoint. Each draw must supply its own `clientSeed`.", + "additionalProperties": true + } + } + } + } + } + }, + "BatchResponse": { + "type": "object", + "required": [ + "results" + ], + "properties": { + "results": { + "type": "array", + "description": "One result per requested draw, in the same order as `draws`.", + "items": { + "oneOf": [ + { + "type": "object", + "required": [ + "ok", + "outcome" + ], + "properties": { + "ok": { + "type": "boolean", + "enum": [ + true + ] + }, + "outcome": { + "$ref": "#/components/schemas/Outcome" + } + } + }, + { + "type": "object", + "required": [ + "ok", + "error" + ], + "properties": { + "ok": { + "type": "boolean", + "enum": [ + false + ] + }, + "error": { + "type": "string" + }, + "code": { + "type": "string", + "description": "Machine-readable failure code, e.g. `quota_exceeded`." + } + } + } + ] + } + } + } + }, + "PublicMetrics": { + "type": "object", + "additionalProperties": false, + "required": [ + "registeredUsers", + "callsServed", + "responseTime", + "apiStatus" + ], + "properties": { + "registeredUsers": { + "type": "object", + "additionalProperties": false, + "required": [ + "value", + "scope" + ], + "properties": { + "value": { + "type": "integer", + "minimum": 0, + "nullable": true + }, + "scope": { + "type": "string", + "enum": [ + "current" + ] + } + } + }, + "callsServed": { + "type": "object", + "additionalProperties": false, + "required": [ + "value", + "scope" + ], + "properties": { + "value": { + "type": "integer", + "minimum": 0, + "nullable": true + }, + "scope": { + "type": "string", + "enum": [ + "lifetime_live_non_test" + ] + } + } + }, + "responseTime": { + "type": "object", + "additionalProperties": false, + "required": [ + "avgMs", + "sampleSize", + "scope" + ], + "properties": { + "avgMs": { + "type": "number", + "minimum": 0, + "nullable": true + }, + "sampleSize": { + "type": "integer", + "minimum": 0 + }, + "scope": { + "type": "string", + "enum": [ + "recent_instance_window" + ] + } + } + }, + "apiStatus": { + "type": "string", + "enum": [ + "operational", + "degraded" + ] + } + } + }, + "Health": { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "ok", + "degraded", + "shutting_down" + ] + }, + "db": { + "type": "string", + "enum": [ + "ok", + "down" + ] + }, + "version": { + "type": "string" + }, + "uptime": { + "type": "integer", + "description": "Seconds since process start." + }, + "timestamp": { + "type": "string", + "format": "date-time" + }, + "responseTimes": { + "type": "object", + "description": "Rolling in-memory response-time aggregate for /api/* traffic on this server instance. Resets on restart.", + "properties": { + "windowSize": { + "type": "integer", + "description": "Number of samples retained per endpoint bucket." + }, + "overall": { + "$ref": "#/components/schemas/ResponseTimeStats", + "nullable": true + }, + "endpoints": { + "type": "object", + "description": "Per-endpoint stats, keyed by the grouped path (e.g. /api/floats).", + "additionalProperties": { + "$ref": "#/components/schemas/ResponseTimeStats" + } + } + } + }, + "usagePersistence": { + "type": "object", + "description": "Process-local health signal for failed atomic usage-accounting writes. Resets on restart.", + "properties": { + "failures": { + "type": "integer", + "minimum": 0 + }, + "lastFailureAt": { + "type": "string", + "format": "date-time", + "nullable": true + }, + "pendingReservations": { + "type": "integer", + "minimum": 0, + "nullable": true, + "description": "Durable usage reservations awaiting reconciliation; null only if the health query itself failed." + } + }, + "required": [ + "failures", + "lastFailureAt", + "pendingReservations" + ] + } + }, + "required": [ + "status", + "version", + "uptime", + "timestamp" + ] + }, + "ResponseTimeStats": { + "type": "object", + "properties": { + "count": { "type": "integer" }, + "avgMs": { "type": "number" }, + "p50Ms": { "type": "number" }, + "p95Ms": { "type": "number" }, + "maxMs": { "type": "number" } + }, + "required": ["count", "avgMs", "p50Ms", "p95Ms", "maxMs"] + }, + "Error": { + "type": "object", + "properties": { + "error": { + "type": "string" + }, + "requestId": { + "type": "string", + "description": "Correlation id present on 5xx responses." + }, + "retryAfter": { + "type": "integer", + "nullable": true, + "description": "Seconds to wait before retrying (on 429 responses)." + } + }, + "required": [ + "error" + ] + } + }, + "responses": { + "IdempotencyConflict": { + "description": "The supplied `Idempotency-Key` was previously used with a different request body or query parameters. The response body's `code` is `idempotency_key_conflict`. Either retry the original request unchanged (in which case the cached response is replayed within the 24h TTL with `Idempotent-Replayed: true`) or pick a fresh key for the new request.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "error": "Idempotency-Key was reused with different request parameters. Use a new key for a new request.", + "code": "idempotency_key_conflict" + } + } + } + }, + "BadRequest": { + "description": "Invalid request (e.g. missing or out-of-range parameters).", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "error": "clientSeed is required" + } + } + } + }, + "InvalidApiKey": { + "description": "An API key was supplied but is unknown or revoked. The response body's `code` is `invalid_api_key`. Omit the key to call anonymously.", + "content": { + "application/json": { + "schema": { "$ref": "#/components/schemas/Error" }, + "example": { "error": "Invalid or revoked API key. Omit the key to call anonymously.", "code": "invalid_api_key" } + } + } + }, + "RateLimited": { + "description": "Too many requests. Anonymous calls are limited per IP; authenticated calls have per-account daily quotas.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "error": "Too many requests. Please slow down and try again shortly.", + "retryAfter": 30 + } + } + } + }, + "ServerError": { + "description": "Unexpected server error.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + }, + "example": { + "error": "Internal server error", + "requestId": "a1b2c3d4e5f60718" + } + } + } + } + } + } +} diff --git a/sdk/python/LICENSE b/sdk/python/LICENSE new file mode 100644 index 0000000..1633427 --- /dev/null +++ b/sdk/python/LICENSE @@ -0,0 +1,178 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any form, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2026 Provable.io diff --git a/sdk/python/README.md b/sdk/python/README.md new file mode 100644 index 0000000..174e1e8 --- /dev/null +++ b/sdk/python/README.md @@ -0,0 +1,78 @@ +# provableio + +Official typed **Python SDK** for the [Provable.io](https://provable.io) provably-fair random number API. Models are generated from the canonical OpenAPI specification, and the client covers every published operation. + +## Install + +```bash +pip install provableio +``` + +Python 3.9+ is supported. + +## Quickstart + +```python +import os +from provableio import ProvableClient + +with ProvableClient(api_key=os.environ.get("PROVABLE_KEY")) as client: + result = client.get_ints({ + "clientSeed": "order-42", + "count": 5, + "min": 1, + "max": 100, + }) + if result.error: + raise RuntimeError(result.error.error) + print(result.data["outcome"]) +``` + +Use `bearer_token="..."` instead of `api_key="..."` for `Authorization: Bearer` authentication. Omit both for anonymous, IP-rate-limited calls. + +## Idempotency, batch, and commit/reveal + +```python +result = client.get_floats( + {"clientSeed": "order-42", "count": 1}, + idempotency_key="order-42-draw", +) + +batch = client.batch({"draws": [ + {"endpoint": "ints", "params": {"clientSeed": "a", "min": 1, "max": 6}}, +]}, idempotency_key="round-1") + +commit = client.create_commit().data +reveal = client.reveal_commit({ + "commitId": commit["commitId"], + "clientSeed": "round-1", + "endpoint": "ints", + "params": {"count": 1, "min": 1, "max": 100}, +}).data +``` + +## Streaming (SSE) + +```python +for event in client.stream_outcomes( + {"clientSeed": "live", "endpoint": "floats"}, + last_event_id=last_seen, +): + print(event) +``` + +`Last-Event-ID` is sent when `last_event_id` is provided. Transport failures and non-2xx stream responses raise `httpx.HTTPError`; ordinary API methods return `ApiResult` without throwing for non-2xx responses. + +## Regenerating models + +From `sdk/python`: + +```bash +python generate_models.py +``` + +This reads `sdk/openapi.json` (a copy of https://provable.io/openapi.json) and rewrites `src/provableio/models.py` and `operations.py`. + +## License + +Apache-2.0 © Provable.io diff --git a/sdk/python/generate_models.py b/sdk/python/generate_models.py new file mode 100644 index 0000000..5f2580d --- /dev/null +++ b/sdk/python/generate_models.py @@ -0,0 +1,264 @@ +#!/usr/bin/env python3 +"""Generate TypedDict response models from the canonical OpenAPI document.""" + +from __future__ import annotations + +import json +import keyword +import re +from pathlib import Path +from typing import Any + +SPEC = Path(__file__).resolve().parent.parent / "openapi.json" +OUTPUT = Path(__file__).parent / "src" / "provableio" / "models.py" +OPERATIONS_OUTPUT = Path(__file__).parent / "src" / "provableio" / "operations.py" +METHOD_OVERRIDES = { + "batchDraw": "batch", + "pickItem": "pick", + "shuffleItems": "shuffle", +} +INLINE_TYPES: dict[str, dict[str, Any]] = {} + + +def safe_name(name: str) -> str: + name = re.sub(r"\W", "_", name) + return name + "_" if keyword.iskeyword(name) else name + + +def class_name(name: str) -> str: + return name[:1].upper() + name[1:] + + +def snake_name(name: str) -> str: + return re.sub(r"(? str: + if "$ref" in schema: + return schema["$ref"].rsplit("/", 1)[-1] + if "enum" in schema: + return "Literal[" + ", ".join(repr(v) for v in schema["enum"]) + "]" + variants = schema.get("oneOf") or schema.get("anyOf") + if variants: + return "Union[" + ", ".join( + py_type(variant, f"{hint}Variant{index}") + for index, variant in enumerate(variants, 1) + ) + "]" + kind = schema.get("type") + if kind == "array": + return f"List[{py_type(schema.get('items', {}), hint + 'Item')}]" + if kind == "object": + if schema.get("properties") or schema.get("allOf"): + INLINE_TYPES.setdefault(hint, schema) + return hint + additional = schema.get("additionalProperties") + return f"Dict[str, {py_type(additional, hint + 'Value')}]" if isinstance(additional, dict) else "Dict[str, Any]" + return {"string": "str", "integer": "int", "number": "float", "boolean": "bool"}.get(kind, "Any") + +def object_shape(schema: dict[str, Any]) -> tuple[list[str], dict[str, Any], set[str]]: + bases: list[str] = [] + properties: dict[str, Any] = {} + required: set[str] = set() + parts = schema.get("allOf", [schema]) + for part in parts: + if "$ref" in part: + bases.append(part["$ref"].rsplit("/", 1)[-1]) + else: + properties.update(part.get("properties", {})) + required.update(part.get("required", [])) + return bases, properties, required + + +def referenced_types(schema: Any) -> set[str]: + if isinstance(schema, list): + return set().union(*(referenced_types(item) for item in schema), set()) + if not isinstance(schema, dict): + return set() + refs = { + value.rsplit("/", 1)[-1] + for key, value in schema.items() + if key == "$ref" and isinstance(value, str) + } + return refs | set().union(*(referenced_types(value) for value in schema.values()), set()) + + +def main() -> None: + INLINE_TYPES.clear() + spec = json.loads(SPEC.read_text()) + lines = [ + '"""Generated from public/openapi.json. Do not edit by hand."""', + "from __future__ import annotations", + "from typing import Any, Dict, List, Literal, TypedDict, Union", + "", + ] + aliases = [] + for name, schema in spec["components"]["schemas"].items(): + bases, properties, required = object_shape(schema) + if not properties and not bases: + aliases.append((name, schema)) + continue + parent = bases[0] if bases else "TypedDict" + lines += [f"class {name}({parent}, total=False):"] + if not properties: + lines.append(" pass") + for prop, prop_schema in properties.items(): + annotation = py_type(prop_schema, f"{name}{class_name(safe_name(prop))}") + if prop in required: + annotation = f"Required[{annotation}]" + lines.append(f" {safe_name(prop)}: {annotation}") + lines.append("") + inline_insert_at = len(lines) + pending_aliases = dict(aliases) + while pending_aliases: + ready = [ + name + for name, schema in pending_aliases.items() + if not (referenced_types(schema) & pending_aliases.keys()) + ] + if not ready: + names = ", ".join(pending_aliases) + raise ValueError(f"Cyclic generated type aliases: {names}") + for name in ready: + schema = pending_aliases.pop(name) + lines += [f"{name} = {py_type(schema, name)}", ""] + + operation_methods = {} + operation_descriptors = {} + for path, path_item in spec["paths"].items(): + for method in ("get", "post", "put", "patch", "delete"): + operation = path_item.get(method) + if not operation: + continue + operation_id = operation["operationId"] + operation_methods[operation_id] = METHOD_OVERRIDES.get(operation_id, snake_name(operation_id)) + parameters = [] + query_names = [] + path_names = [] + for parameter in operation.get("parameters", []): + if "$ref" in parameter: + target = spec + for part in parameter["$ref"][2:].split("/"): + target = target[part] + parameter = target + if parameter["in"] in ("query", "path"): + parameters.append(parameter) + if parameter["in"] == "query": + query_names.append(parameter["name"]) + elif parameter["in"] == "path": + path_names.append(parameter["name"]) + operation_descriptors[operation_id] = { + "method": method.upper(), + "path": path, + "query": tuple(query_names), + "query_aliases": { + safe_name(name): name + for name in query_names + if safe_name(name) != name + }, + "path_params": tuple(path_names), + "has_body": bool(operation.get("requestBody")), + } + if parameters: + lines += [f"class {class_name(operation_id)}Params(TypedDict, total=False):"] + for parameter in parameters: + annotation = py_type( + parameter.get("schema", {}), + f"{class_name(operation_id)}Params{class_name(safe_name(parameter['name']))}", + ) + if parameter.get("required"): + annotation = f"Required[{annotation}]" + lines.append(f" {safe_name(parameter['name'])}: {annotation}") + lines.append("") + + raw_body = operation.get("requestBody") + if raw_body: + if "$ref" in raw_body: + target = spec + for part in raw_body["$ref"][2:].split("/"): + target = target[part] + raw_body = target + body_schema = raw_body.get("content", {}).get("application/json", {}).get("schema") + if body_schema and "$ref" not in body_schema: + body_name = f"{class_name(operation_id)}Body" + bases, properties, required = object_shape(body_schema) + parent = bases[0] if bases else "TypedDict" + lines += [f"class {body_name}({parent}, total=False):"] + if not properties: + lines.append(" pass") + for prop, prop_schema in properties.items(): + annotation = py_type(prop_schema, f"{body_name}{class_name(safe_name(prop))}") + if prop in required: + annotation = f"Required[{annotation}]" + lines.append(f" {safe_name(prop)}: {annotation}") + lines.append("") + + response_schema = None + response_content_type = None + for status, raw_response in operation["responses"].items(): + if not str(status).startswith("2"): + continue + if "$ref" in raw_response: + target = spec + for part in raw_response["$ref"][2:].split("/"): + target = target[part] + raw_response = target + for content_type, content in raw_response.get("content", {}).items(): + response_schema = content.get("schema", {}) + response_content_type = content_type + break + if response_schema is not None: + break + response_name = f"{class_name(operation_id)}Response" + if response_content_type in ("image/png", "image/jpeg"): + lines += [f"{response_name} = bytes", ""] + elif response_schema is not None and "$ref" in response_schema: + lines += [f"{response_name} = {py_type(response_schema, response_name)}", ""] + elif response_schema is not None: + bases, properties, required = object_shape(response_schema) + if properties or bases: + parent = bases[0] if bases else "TypedDict" + lines += [f"class {response_name}({parent}, total=False):"] + for prop, prop_schema in properties.items(): + annotation = py_type(prop_schema, f"{response_name}{class_name(safe_name(prop))}") + if prop in required: + annotation = f"Required[{annotation}]" + lines.append(f" {safe_name(prop)}: {annotation}") + lines.append("") + else: + lines += [f"{response_name} = {py_type(response_schema, response_name)}", ""] + inline_lines = [] + emitted = set() + while True: + pending = [(name, schema) for name, schema in INLINE_TYPES.items() if name not in emitted] + if not pending: + break + for name, schema in pending: + emitted.add(name) + bases, properties, required = object_shape(schema) + parent = bases[0] if bases else "TypedDict" + inline_lines += [f"class {name}({parent}, total=False):"] + if not properties: + inline_lines.append(" pass") + for prop, prop_schema in properties.items(): + annotation = py_type(prop_schema, f"{name}{class_name(safe_name(prop))}") + if prop in required: + annotation = f"Required[{annotation}]" + inline_lines.append(f" {safe_name(prop)}: {annotation}") + inline_lines.append("") + lines[inline_insert_at:inline_insert_at] = inline_lines + text = "\n".join(lines) + text = text.replace( + "from typing import Any, Dict, List, Literal, TypedDict, Union", + "from typing import Any, Dict, List, Literal, TypedDict, Union\n" + "try:\n from typing import Required\nexcept ImportError:\n from typing_extensions import Required", + ) + OUTPUT.write_text(text + "\n") + OPERATIONS_OUTPUT.write_text( + '"""Generated operation-to-method map. Do not edit by hand."""\n\n' + f"OPERATION_METHODS = {operation_methods!r}\n\n" + f"OPERATIONS = {operation_descriptors!r}\n" + ) + + +if __name__ == "__main__": + main() diff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.toml new file mode 100644 index 0000000..78cbf7a --- /dev/null +++ b/sdk/python/pyproject.toml @@ -0,0 +1,40 @@ +[build-system] +requires = ["hatchling>=1.21"] +build-backend = "hatchling.build" + +[project] +name = "provableio" +version = "0.1.0" +description = "Official Python SDK for the Provable.io provably-fair random number API" +readme = "README.md" +requires-python = ">=3.9" +license = { file = "LICENSE" } +authors = [{ name = "Provable.io", email = "support@provable.io" }] +keywords = ["provable", "random", "rng", "commit-reveal", "openapi", "sdk"] +classifiers = [ + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Typing :: Typed", +] +dependencies = [ + "httpx>=0.25,<1", + "typing-extensions>=4.5; python_version < '3.11'", +] + +[project.urls] +Homepage = "https://provable.io/api-docs" +Documentation = "https://provable.io/api-docs" +Repository = "https://github.com/provableio/provable-core" +Issues = "https://github.com/provableio/provable-core/issues" + +[tool.hatch.build.targets.wheel] +packages = ["src/provableio"] + +[tool.pytest.ini_options] +testpaths = ["tests"] diff --git a/sdk/python/src/provableio/__init__.py b/sdk/python/src/provableio/__init__.py new file mode 100644 index 0000000..d64d891 --- /dev/null +++ b/sdk/python/src/provableio/__init__.py @@ -0,0 +1,7 @@ +"""Official Python SDK for the Provable.io API.""" + +from .client import ApiError, ApiResult, ProvableClient +from .models import * # noqa: F403 - generated models are part of the public API + +__all__ = ["ApiError", "ApiResult", "ProvableClient"] +__version__ = "0.1.0" diff --git a/sdk/python/src/provableio/client.py b/sdk/python/src/provableio/client.py new file mode 100644 index 0000000..135bdc6 --- /dev/null +++ b/sdk/python/src/provableio/client.py @@ -0,0 +1,254 @@ +"""Typed synchronous client for every operation in the public OpenAPI spec.""" + +from __future__ import annotations + +import json +from dataclasses import dataclass +from typing import Any, Dict, Generic, Iterator, Mapping, Optional, TypedDict, TypeVar, Union +try: + from typing import Unpack +except ImportError: + from typing_extensions import Unpack +from urllib.parse import quote + +import httpx + +from . import models +from .operations import OPERATIONS + +T = TypeVar("T") +DEFAULT_BASE_URL = "https://api.provable.io" + + +@dataclass(frozen=True) +class ApiError: + error: str + code: Optional[str] = None + + +@dataclass(frozen=True) +class ApiResult(Generic[T]): + data: Optional[T] + error: Optional[ApiError] + response: httpx.Response + + @property + def is_success(self) -> bool: + return self.error is None + + +class RequestOptions(TypedDict, total=False): + idempotency_key: str + headers: Mapping[str, str] + + +class ProvableClient: + """Provable.io API client. + + API errors are returned in :class:`ApiResult`; transport errors raise + ``httpx.HTTPError``. The client owns its HTTP connection unless a custom + ``httpx.Client`` is supplied. + """ + + def __init__( + self, + *, + api_key: Optional[str] = None, + bearer_token: Optional[str] = None, + base_url: str = DEFAULT_BASE_URL, + headers: Optional[Mapping[str, str]] = None, + timeout: Union[float, httpx.Timeout] = 30.0, + http_client: Optional[httpx.Client] = None, + ) -> None: + auth_headers = dict(headers or {}) + auth_headers.setdefault("Accept", "application/json") + if api_key: + auth_headers["x-api-key"] = api_key + elif bearer_token: + auth_headers["Authorization"] = f"Bearer {bearer_token}" + self.base_url = base_url.rstrip("/") + self._owns_client = http_client is None + self._client = http_client or httpx.Client(headers=auth_headers, timeout=timeout) + self._headers = auth_headers + + def close(self) -> None: + if self._owns_client: + self._client.close() + + def __enter__(self) -> "ProvableClient": + return self + + def __exit__(self, *_: object) -> None: + self.close() + + def request( + self, + method: str, + path: str, + *, + query: Optional[Mapping[str, Any]] = None, + body: Any = None, + idempotency_key: Optional[str] = None, + headers: Optional[Mapping[str, str]] = None, + ) -> ApiResult[Any]: + request_headers = {**self._headers, **dict(headers or {})} + if idempotency_key: + request_headers["Idempotency-Key"] = idempotency_key + params = [(key, item) for key, value in (query or {}).items() if value is not None + for item in (value if isinstance(value, (list, tuple)) else [value])] + request_args: Dict[str, Any] = { + "params": params, + "headers": request_headers, + } + if body is not None: + request_args["json"] = body + response = self._client.request(method, self.base_url + path, **request_args) + content_type = response.headers.get("content-type", "") + if content_type.startswith("image/"): + payload = response.content + else: + payload = response.json() if "json" in content_type else response.text + if response.is_success: + return ApiResult(data=payload, error=None, response=response) + if isinstance(payload, dict): + error = ApiError(str(payload.get("error", f"HTTP {response.status_code}")), payload.get("code")) + else: + error = ApiError(str(payload) or f"HTTP {response.status_code}") + return ApiResult(data=None, error=error, response=response) + + def _operation( + self, + operation_id: str, + *, + query: Optional[Mapping[str, Any]] = None, + path_params: Optional[Mapping[str, Any]] = None, + body: Any = None, + options: Optional[Mapping[str, Any]] = None, + ) -> ApiResult[Any]: + operation = OPERATIONS[operation_id] + path = operation["path"] + for name in operation["path_params"]: + if path_params is None or name not in path_params: + raise ValueError(f"Missing path parameter: {name}") + path = path.replace("{" + name + "}", quote(str(path_params[name]), safe="")) + aliases = operation["query_aliases"] + wire_query = ( + {aliases.get(name, name): value for name, value in query.items()} + if query is not None + else None + ) + return self.request( + operation["method"], + path, + query=wire_query, + body=body, + **dict(options or {}), + ) + + def get_floats(self, query: models.GetFloatsParams, **options: Unpack[RequestOptions]) -> ApiResult[models.GetFloatsResponse]: + return self._operation("getFloats", query=query, options=options) + + def get_ints(self, query: models.GetIntsParams, **options: Unpack[RequestOptions]) -> ApiResult[models.GetIntsResponse]: + return self._operation("getInts", query=query, options=options) + + def shuffle(self, query: models.ShuffleItemsParams, **options: Unpack[RequestOptions]) -> ApiResult[models.ShuffleItemsResponse]: + return self._operation("shuffleItems", query=query, options=options) + + def pick(self, query: models.PickItemParams, **options: Unpack[RequestOptions]) -> ApiResult[models.PickItemResponse]: + return self._operation("pickItem", query=query, options=options) + + def get_bytes(self, query: models.GetBytesParams, **options: Unpack[RequestOptions]) -> ApiResult[models.GetBytesResponse]: + return self._operation("getBytes", query=query, options=options) + + def roll_dice(self, query: models.RollDiceParams, **options: Unpack[RequestOptions]) -> ApiResult[models.RollDiceResponse]: + return self._operation("rollDice", query=query, options=options) + + def gaussian(self, query: models.GaussianParams, **options: Unpack[RequestOptions]) -> ApiResult[models.GaussianResponse]: + return self._operation("gaussian", query=query, options=options) + + def batch(self, body: models.BatchRequest, **options: Unpack[RequestOptions]) -> ApiResult[models.BatchDrawResponse]: + return self._operation("batchDraw", body=body, options=options) + + def create_commit(self, **options: Unpack[RequestOptions]) -> ApiResult[models.CreateCommitResponse]: + return self._operation("createCommit", options=options) + + def reveal_commit(self, body: models.RevealRequest, **options: Unpack[RequestOptions]) -> ApiResult[models.RevealCommitResponse]: + return self._operation("revealCommit", body=body, options=options) + + def rotate_server_seed(self, body: models.RotateServerSeedBody, **options: Unpack[RequestOptions]) -> ApiResult[models.RotateServerSeedResponse]: + return self._operation("rotateServerSeed", body=body, options=options) + + def verify_server_hash(self, query: models.VerifyServerHashParams, **options: Unpack[RequestOptions]) -> ApiResult[models.VerifyServerHashResponse]: + return self._operation("verifyServerHash", query=query, options=options) + + def verify_short_id(self, query: models.VerifyShortIdParams, **options: Unpack[RequestOptions]) -> ApiResult[models.VerifyShortIdResponse]: + return self._operation("verifyShortId", query=query, options=options) + + def get_outcome(self, query: models.GetOutcomeParams, **options: Unpack[RequestOptions]) -> ApiResult[models.GetOutcomeResponse]: + return self._operation("getOutcome", query=query, options=options) + + def increment_cursor(self, query: models.IncrementCursorParams, **options: Unpack[RequestOptions]) -> ApiResult[models.IncrementCursorResponse]: + return self._operation("incrementCursor", query=query, options=options) + + def list_outcomes(self, query: Optional[models.ListOutcomesParams] = None, **options: Unpack[RequestOptions]) -> ApiResult[models.ListOutcomesResponse]: + return self._operation("listOutcomes", query=query, options=options) + + def list_merkle_roots(self, query: Optional[models.ListMerkleRootsParams] = None, **options: Unpack[RequestOptions]) -> ApiResult[models.ListMerkleRootsResponse]: + return self._operation("listMerkleRoots", query=query, options=options) + + def get_merkle_root(self, date: str, **options: Unpack[RequestOptions]) -> ApiResult[models.GetMerkleRootResponse]: + return self._operation("getMerkleRoot", path_params={"date": date}, options=options) + + def get_merkle_proof(self, date: str, outcome_id: str, **options: Unpack[RequestOptions]) -> ApiResult[models.GetMerkleProofResponse]: + return self._operation( + "getMerkleProof", + path_params={"date": date, "outcomeId": outcome_id}, + options=options, + ) + + def get_health(self, **options: Unpack[RequestOptions]) -> ApiResult[models.GetHealthResponse]: + return self._operation("getHealth", options=options) + + def get_public_metrics(self, **options: Unpack[RequestOptions]) -> ApiResult[models.GetPublicMetricsResponse]: + return self._operation("getPublicMetrics", options=options) + + def get_outcome_permalink(self, outcome_id: str, **options: Unpack[RequestOptions]) -> ApiResult[models.GetOutcomePermalinkResponse]: + return self._operation( + "getOutcomePermalink", path_params={"id": outcome_id}, options=options, + ) + + def get_outcome_og_image(self, outcome_id: str, **options: Unpack[RequestOptions]) -> ApiResult[models.GetOutcomeOgImageResponse]: + return self._operation( + "getOutcomeOgImage", path_params={"id": outcome_id}, options=options, + ) + + def stream_outcomes( + self, + query: models.StreamOutcomesParams, + *, + last_event_id: Optional[str] = None, + headers: Optional[Mapping[str, str]] = None, + ) -> Iterator[models.Outcome]: + stream_headers = {**self._headers, **dict(headers or {}), "Accept": "text/event-stream"} + if last_event_id: + stream_headers["Last-Event-ID"] = last_event_id + operation = OPERATIONS["streamOutcomes"] + with self._client.stream( + operation["method"], self.base_url + operation["path"], params=query, headers=stream_headers, + ) as response: + response.raise_for_status() + data_lines = [] + event_name = "message" + for line in response.iter_lines(): + if line.startswith("event:"): + event_name = line[6:].strip() + elif line.startswith("data:"): + data_lines.append(line[5:].lstrip()) + elif not line and data_lines: + data = "\n".join(data_lines) + data_lines = [] + if event_name == "done": + return + if event_name in ("message", "outcome"): + yield json.loads(data) + event_name = "message" diff --git a/sdk/python/src/provableio/models.py b/sdk/python/src/provableio/models.py new file mode 100644 index 0000000..4fbf9cb --- /dev/null +++ b/sdk/python/src/provableio/models.py @@ -0,0 +1,401 @@ +"""Generated from public/openapi.json. Do not edit by hand.""" +from __future__ import annotations +from typing import Any, Dict, List, Literal, TypedDict, Union +try: + from typing import Required +except ImportError: + from typing_extensions import Required + +class BaseOutcome(TypedDict, total=False): + clientSeed: Required[str] + serverHash: Required[str] + nonce: Required[int] + cursor: Required[int] + count: Required[int] + created: Required[int] + shortId: Required[str] + mode: Required[Literal['live', 'test']] + toolMeta: Dict[str, Any] + redacted: bool + +class PasswordReceipt(TypedDict, total=False): + serverHash: Required[str] + endpoint: Required[Literal['ints']] + outcome: Required[Any] + clientSeed: str + cursor: int + nonce: int + count: int + min: int + max: int + created: int + shortId: Required[str] + mode: str + toolMeta: Required[Dict[str, Any]] + redacted: Required[Literal[True]] + permalink: str + +class VerifyResult(TypedDict, total=False): + verified: Required[bool] + clientSeed: Required[str] + serverHash: Required[str] + outcomes: Required[List[VerifyResultOutcomesItem]] + +class FloatOutcome(BaseOutcome, total=False): + outcome: Required[List[float]] + endpoint: Required[Literal['floats']] + mode: Required[Literal['live', 'test']] + permalink: Required[str] + +class IntOutcome(BaseOutcome, total=False): + outcome: Required[List[int]] + endpoint: Required[Literal['ints']] + min: Required[int] + max: Required[int] + mode: Required[Literal['live', 'test']] + permalink: Required[str] + +class MerkleRoot(TypedDict, total=False): + date: Required[str] + root: Required[str] + leafCount: Required[int] + treeHeight: Required[int] + publishedAt: Required[int] + +class MerkleProof(TypedDict, total=False): + date: Required[str] + outcomeId: Required[str] + leaf: Required[MerkleProofLeaf] + index: Required[int] + leafCount: Required[int] + treeHeight: int + root: Required[str] + publishedAt: int + siblings: Required[List[MerkleProofSiblingsItem]] + +class ShuffleOutcome(BaseOutcome, total=False): + outcome: Required[List[Any]] + endpoint: Required[Literal['shuffle']] + permalink: Required[str] + +class Commit(TypedDict, total=False): + commitId: Required[str] + serverHash: Required[str] + expiresAt: Required[int] + +class RevealRequest(TypedDict, total=False): + commitId: Required[str] + clientSeed: Required[str] + endpoint: Required[Literal['floats', 'ints']] + params: RevealRequestParams + +class RevealOutcome(BaseOutcome, total=False): + outcome: Required[List[float]] + endpoint: Required[Literal['floats', 'ints']] + min: int + max: int + serverSeed: Required[str] + commitId: Required[str] + +class PickOutcome(BaseOutcome, total=False): + outcome: Required[Any] + index: Required[int] + weights: Required[List[float]] + endpoint: Required[Literal['pick']] + permalink: Required[str] + +class BytesOutcome(BaseOutcome, total=False): + outcome: Required[str] + encoding: Required[Literal['hex', 'base64']] + endpoint: Required[Literal['bytes']] + permalink: Required[str] + +class DiceOutcome(BaseOutcome, total=False): + outcome: Required[DiceOutcomeOutcome] + sides: Required[int] + modifier: Required[int] + endpoint: Required[Literal['dice']] + permalink: Required[str] + +class GaussianOutcome(BaseOutcome, total=False): + outcome: Required[List[float]] + distribution: Required[Literal['normal', 'exponential', 'poisson']] + mean: float + stddev: float + lambda_: float + endpoint: Required[Literal['gaussian']] + permalink: Required[str] + +class BatchRequest(TypedDict, total=False): + draws: Required[List[BatchRequestDrawsItem]] + +class BatchResponse(TypedDict, total=False): + results: Required[List[Union[BatchResponseResultsItemVariant1, BatchResponseResultsItemVariant2]]] + +class PublicMetrics(TypedDict, total=False): + registeredUsers: Required[PublicMetricsRegisteredUsers] + callsServed: Required[PublicMetricsCallsServed] + responseTime: Required[PublicMetricsResponseTime] + apiStatus: Required[Literal['operational', 'degraded']] + +class Health(TypedDict, total=False): + status: Required[Literal['ok', 'degraded', 'shutting_down']] + db: Literal['ok', 'down'] + version: Required[str] + uptime: Required[int] + timestamp: Required[str] + responseTimes: HealthResponseTimes + usagePersistence: HealthUsagePersistence + +class ResponseTimeStats(TypedDict, total=False): + count: Required[int] + avgMs: Required[float] + p50Ms: Required[float] + p95Ms: Required[float] + maxMs: Required[float] + +class Error(TypedDict, total=False): + error: Required[str] + requestId: str + retryAfter: int + +class VerifyResultOutcomesItem(TypedDict, total=False): + shortId: Required[str] + permalink: Required[str] + endpoint: str + cursor: int + nonce: int + created: int + +class MerkleProofLeaf(TypedDict, total=False): + outcomeId: str + serverHash: str + clientSeed: str + timestamp: int + canonical: Required[str] + hash: Required[str] + +class MerkleProofSiblingsItem(TypedDict, total=False): + position: Required[Literal['left', 'right']] + hash: Required[str] + +class RevealRequestParams(TypedDict, total=False): + count: int + min: int + max: int + +class DiceOutcomeOutcome(TypedDict, total=False): + notation: Required[str] + rolls: Required[List[int]] + modifier: Required[int] + total: Required[int] + +class BatchRequestDrawsItem(TypedDict, total=False): + endpoint: Required[Literal['floats', 'ints', 'shuffle', 'pick', 'bytes', 'dice', 'gaussian']] + params: Dict[str, Any] + +class BatchResponseResultsItemVariant1(TypedDict, total=False): + ok: Required[Literal[True]] + outcome: Required[Outcome] + +class BatchResponseResultsItemVariant2(TypedDict, total=False): + ok: Required[Literal[False]] + error: Required[str] + code: str + +class PublicMetricsRegisteredUsers(TypedDict, total=False): + value: Required[int] + scope: Required[Literal['current']] + +class PublicMetricsCallsServed(TypedDict, total=False): + value: Required[int] + scope: Required[Literal['lifetime_live_non_test']] + +class PublicMetricsResponseTime(TypedDict, total=False): + avgMs: Required[float] + sampleSize: Required[int] + scope: Required[Literal['recent_instance_window']] + +class HealthResponseTimes(TypedDict, total=False): + windowSize: int + overall: ResponseTimeStats + endpoints: Dict[str, ResponseTimeStats] + +class HealthUsagePersistence(TypedDict, total=False): + failures: Required[int] + lastFailureAt: Required[str] + pendingReservations: Required[int] + +class RotateServerSeedResponseRevealed(TypedDict, total=False): + serverSeed: Required[str] + serverHash: Required[str] + cursor: Required[int] + nonce: Required[int] + +class RotateServerSeedResponseNext(TypedDict, total=False): + serverHash: Required[str] + cursor: Required[int] + nonce: Required[int] + rotatedAt: Required[int] + +Outcome = Union[FloatOutcome, IntOutcome, ShuffleOutcome, PickOutcome, BytesOutcome, DiceOutcome, GaussianOutcome] + +PublicOutcome = Union[Outcome, PasswordReceipt] + +BatchDrawResponse = BatchResponse + +class GetBytesParams(TypedDict, total=False): + clientSeed: str + count: int + encoding: Literal['hex', 'base64'] + +GetBytesResponse = BytesOutcome + +CreateCommitResponse = Commit + +class RollDiceParams(TypedDict, total=False): + clientSeed: str + notation: Required[str] + +RollDiceResponse = DiceOutcome + +class GetFloatsParams(TypedDict, total=False): + clientSeed: str + count: int + +GetFloatsResponse = FloatOutcome + +class GaussianParams(TypedDict, total=False): + clientSeed: str + count: int + distribution: Literal['normal', 'exponential', 'poisson'] + mean: float + stddev: float + lambda_: float + +GaussianResponse = GaussianOutcome + +GetHealthResponse = Health + +GetPublicMetricsResponse = PublicMetrics + +class IncrementCursorParams(TypedDict, total=False): + clientSeed: str + +class IncrementCursorResponse(TypedDict, total=False): + clientSeed: Required[str] + cursor: Required[int] + nonce: Required[int] + serverHash: Required[str] + created: Required[int] + +class GetIntsParams(TypedDict, total=False): + clientSeed: str + count: int + min: int + max: int + toolMeta: str + +GetIntsResponse = IntOutcome + +class ListOutcomesParams(TypedDict, total=False): + clientSeed: str + limit: int + before: str + +ListOutcomesResponse = List[PublicOutcome] + +class ListMerkleRootsParams(TypedDict, total=False): + limit: int + +class ListMerkleRootsResponse(TypedDict, total=False): + roots: List[MerkleRoot] + +class GetMerkleRootParams(TypedDict, total=False): + date: Required[str] + +GetMerkleRootResponse = MerkleRoot + +class GetMerkleProofParams(TypedDict, total=False): + date: Required[str] + outcomeId: Required[str] + +GetMerkleProofResponse = MerkleProof + +class GetOutcomeParams(TypedDict, total=False): + clientSeed: str + cursor: Required[int] + nonce: Required[int] + +GetOutcomeResponse = PublicOutcome + +class PickItemParams(TypedDict, total=False): + clientSeed: str + items: Required[Union[str, List[str]]] + weights: Union[str, List[float]] + +PickItemResponse = PickOutcome + +RevealCommitResponse = RevealOutcome + +class RotateServerSeedBody(TypedDict, total=False): + clientSeed: Required[str] + +class RotateServerSeedResponse(TypedDict, total=False): + clientSeed: Required[str] + revealed: Required[RotateServerSeedResponseRevealed] + next: Required[RotateServerSeedResponseNext] + +class ShuffleItemsParams(TypedDict, total=False): + clientSeed: str + items: Required[Union[str, List[str]]] + toolMeta: str + +ShuffleItemsResponse = ShuffleOutcome + +class StreamOutcomesParams(TypedDict, total=False): + clientSeed: str + endpoint: Required[Literal['floats', 'ints', 'shuffle', 'pick', 'bytes', 'dice', 'gaussian']] + intervalMs: int + lastEventId: str + +StreamOutcomesResponse = str + +class VerifyServerHashParams(TypedDict, total=False): + clientSeed: str + serverHash: Required[str] + +VerifyServerHashResponse = Union[Literal[True], VerifyResult] + +class VerifyShortIdParams(TypedDict, total=False): + shortId: Required[str] + +class VerifyShortIdResponse(TypedDict, total=False): + verified: Required[bool] + reason: Required[str] + shortId: Required[str] + clientSeed: str + serverHash: str + cursor: int + nonce: int + endpoint: str + outcome: Union[List[Any], Dict[str, Any]] + count: int + min: int + max: int + notation: str + toolMeta: Dict[str, Any] + created: int + redacted: bool + permalink: str + +class GetOutcomePermalinkParams(TypedDict, total=False): + id: Required[str] + +GetOutcomePermalinkResponse = str + +class GetOutcomeOgImageParams(TypedDict, total=False): + id: Required[str] + +GetOutcomeOgImageResponse = bytes + diff --git a/sdk/python/src/provableio/operations.py b/sdk/python/src/provableio/operations.py new file mode 100644 index 0000000..1fd2ebf --- /dev/null +++ b/sdk/python/src/provableio/operations.py @@ -0,0 +1,5 @@ +"""Generated operation-to-method map. Do not edit by hand.""" + +OPERATION_METHODS = {'batchDraw': 'batch', 'getBytes': 'get_bytes', 'createCommit': 'create_commit', 'rollDice': 'roll_dice', 'getFloats': 'get_floats', 'gaussian': 'gaussian', 'getHealth': 'get_health', 'getPublicMetrics': 'get_public_metrics', 'incrementCursor': 'increment_cursor', 'getInts': 'get_ints', 'listOutcomes': 'list_outcomes', 'listMerkleRoots': 'list_merkle_roots', 'getMerkleRoot': 'get_merkle_root', 'getMerkleProof': 'get_merkle_proof', 'getOutcome': 'get_outcome', 'pickItem': 'pick', 'revealCommit': 'reveal_commit', 'rotateServerSeed': 'rotate_server_seed', 'shuffleItems': 'shuffle', 'streamOutcomes': 'stream_outcomes', 'verifyServerHash': 'verify_server_hash', 'verifyShortId': 'verify_short_id', 'getOutcomePermalink': 'get_outcome_permalink', 'getOutcomeOgImage': 'get_outcome_og_image'} + +OPERATIONS = {'batchDraw': {'method': 'POST', 'path': '/api/batch', 'query': (), 'query_aliases': {}, 'path_params': (), 'has_body': True}, 'getBytes': {'method': 'GET', 'path': '/api/bytes', 'query': ('clientSeed', 'count', 'encoding'), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'createCommit': {'method': 'POST', 'path': '/api/commit', 'query': (), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'rollDice': {'method': 'GET', 'path': '/api/dice', 'query': ('clientSeed', 'notation'), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'getFloats': {'method': 'GET', 'path': '/api/floats', 'query': ('clientSeed', 'count'), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'gaussian': {'method': 'GET', 'path': '/api/gaussian', 'query': ('clientSeed', 'count', 'distribution', 'mean', 'stddev', 'lambda'), 'query_aliases': {'lambda_': 'lambda'}, 'path_params': (), 'has_body': False}, 'getHealth': {'method': 'GET', 'path': '/api/health', 'query': (), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'getPublicMetrics': {'method': 'GET', 'path': '/api/public-metrics', 'query': (), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'incrementCursor': {'method': 'GET', 'path': '/api/incrementCursor', 'query': ('clientSeed',), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'getInts': {'method': 'GET', 'path': '/api/ints', 'query': ('clientSeed', 'count', 'min', 'max', 'toolMeta'), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'listOutcomes': {'method': 'GET', 'path': '/api/listOutcomes', 'query': ('clientSeed', 'limit', 'before'), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'listMerkleRoots': {'method': 'GET', 'path': '/api/merkle', 'query': ('limit',), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'getMerkleRoot': {'method': 'GET', 'path': '/api/merkle/{date}', 'query': (), 'query_aliases': {}, 'path_params': ('date',), 'has_body': False}, 'getMerkleProof': {'method': 'GET', 'path': '/api/merkle/{date}/proof/{outcomeId}', 'query': (), 'query_aliases': {}, 'path_params': ('date', 'outcomeId'), 'has_body': False}, 'getOutcome': {'method': 'GET', 'path': '/api/outcome', 'query': ('clientSeed', 'cursor', 'nonce'), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'pickItem': {'method': 'GET', 'path': '/api/pick', 'query': ('clientSeed', 'items', 'weights'), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'revealCommit': {'method': 'POST', 'path': '/api/reveal', 'query': (), 'query_aliases': {}, 'path_params': (), 'has_body': True}, 'rotateServerSeed': {'method': 'POST', 'path': '/api/rotate', 'query': (), 'query_aliases': {}, 'path_params': (), 'has_body': True}, 'shuffleItems': {'method': 'GET', 'path': '/api/shuffle', 'query': ('clientSeed', 'items', 'toolMeta'), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'streamOutcomes': {'method': 'GET', 'path': '/api/stream', 'query': ('clientSeed', 'endpoint', 'intervalMs', 'lastEventId'), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'verifyServerHash': {'method': 'GET', 'path': '/api/verifyServerHash', 'query': ('clientSeed', 'serverHash'), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'verifyShortId': {'method': 'GET', 'path': '/api/verifyShortId', 'query': ('shortId',), 'query_aliases': {}, 'path_params': (), 'has_body': False}, 'getOutcomePermalink': {'method': 'GET', 'path': '/o/{id}', 'query': (), 'query_aliases': {}, 'path_params': ('id',), 'has_body': False}, 'getOutcomeOgImage': {'method': 'GET', 'path': '/o/{id}/og.png', 'query': (), 'query_aliases': {}, 'path_params': ('id',), 'has_body': False}} diff --git a/sdk/python/src/provableio/py.typed b/sdk/python/src/provableio/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/sdk/python/tests/test_client.py b/sdk/python/tests/test_client.py new file mode 100644 index 0000000..477c0c4 --- /dev/null +++ b/sdk/python/tests/test_client.py @@ -0,0 +1,87 @@ +import httpx + +from provableio import ProvableClient + + +def stub(handler): + return httpx.Client(transport=httpx.MockTransport(handler)) + + +def test_query_api_key_and_idempotency(): + captured = {} + + def handler(request): + captured["request"] = request + return httpx.Response(200, json={"outcome": [3], "serverHash": "abc"}) + + client = ProvableClient(api_key="pk_test_abc", base_url="https://example.test", http_client=stub(handler)) + result = client.get_ints( + {"clientSeed": "seed", "count": 1, "min": 1, "max": 6}, + idempotency_key="idem-1", + ) + assert result.is_success and result.data["outcome"] == [3] + request = captured["request"] + assert str(request.url) == "https://example.test/api/ints?clientSeed=seed&count=1&min=1&max=6" + assert request.headers["x-api-key"] == "pk_test_abc" + assert request.headers["Idempotency-Key"] == "idem-1" + + +def test_bearer_error_and_path_encoding(): + requests = [] + + def handler(request): + requests.append(request) + if request.url.path.startswith("/api/merkle"): + return httpx.Response(429, json={"error": "slow down", "code": "rate_limited"}) + return httpx.Response(200, text="", headers={"content-type": "text/html"}) + + client = ProvableClient(bearer_token="token", base_url="https://example.test", http_client=stub(handler)) + error = client.get_merkle_proof("2026-01-01", "seed:0/1") + assert error.error.code == "rate_limited" + assert requests[0].headers["Authorization"] == "Bearer token" + assert requests[0].url.raw_path.endswith(b"/seed%3A0%2F1") + assert client.get_outcome_permalink("a b").data == "" + + +def test_batch_json_and_sse_resume(): + requests = [] + + def handler(request): + requests.append(request) + if request.url.path == "/api/stream": + return httpx.Response( + 200, + text=( + 'event: outcome\nid: s:1:0\ndata: {"outcome":[0.5]}\n\n' + 'event: done\ndata: {"reason":"limit","count":1}\n\n' + 'event: outcome\ndata: {"outcome":[0.9]}\n\n' + ), + headers={"content-type": "text/event-stream"}, + ) + return httpx.Response(200, json={"results": []}) + + client = ProvableClient(base_url="https://example.test", http_client=stub(handler)) + result = client.batch({"draws": []}, idempotency_key="batch-1") + assert result.data == {"results": []} + assert requests[0].read() == b'{"draws":[]}' + events = list(client.stream_outcomes({"clientSeed": "s", "endpoint": "floats"}, last_event_id="s:1:0")) + assert events == [{"outcome": [0.5]}] + assert requests[1].headers["Last-Event-ID"] == "s:1:0" + + +def test_python_keyword_parameter_uses_openapi_wire_name(): + captured = {} + + def handler(request): + captured["request"] = request + return httpx.Response(200, json={"outcome": [1.25]}) + + client = ProvableClient(base_url="https://example.test", http_client=stub(handler)) + client.gaussian({ + "clientSeed": "distribution", + "distribution": "exponential", + "lambda_": 2, + }) + params = captured["request"].url.params + assert params["lambda"] == "2" + assert "lambda_" not in params diff --git a/sdk/python/tests/test_openapi_coverage.py b/sdk/python/tests/test_openapi_coverage.py new file mode 100644 index 0000000..b9f5a5d --- /dev/null +++ b/sdk/python/tests/test_openapi_coverage.py @@ -0,0 +1,89 @@ +import json +from pathlib import Path +from typing import get_args, get_origin, get_type_hints + +try: + from typing import Required +except ImportError: + from typing_extensions import Required + +from provableio import ProvableClient +from provableio.models import ( + BatchResponse, + GetOutcomeParams, + PasswordReceipt, + PublicOutcome, + RevealRequest, + StreamOutcomesParams, +) +from provableio.operations import OPERATIONS, OPERATION_METHODS + + +SPEC = Path(__file__).resolve().parents[2] / "openapi.json" + + +def required_fields(model): + hints = get_type_hints(model, include_extras=True) + return {name for name, hint in hints.items() if get_origin(hint) is Required} + + +def test_every_openapi_operation_has_a_public_client_method(): + document = json.loads(SPEC.read_text()) + operation_ids = { + operation["operationId"] + for path_item in document["paths"].values() + for operation in path_item.values() + if isinstance(operation, dict) and "operationId" in operation + } + assert set(OPERATION_METHODS) == operation_ids + assert all(hasattr(ProvableClient, method) for method in OPERATION_METHODS.values()) + + +def test_generated_dispatch_contract_matches_openapi(): + document = json.loads(SPEC.read_text()) + expected = {} + for path, path_item in document["paths"].items(): + for method, operation in path_item.items(): + if not isinstance(operation, dict) or "operationId" not in operation: + continue + parameters = [] + for parameter in operation.get("parameters", []): + if "$ref" in parameter: + parameter = document["components"]["parameters"][parameter["$ref"].rsplit("/", 1)[-1]] + parameters.append(parameter) + expected[operation["operationId"]] = { + "method": method.upper(), + "path": path, + "query": tuple(p["name"] for p in parameters if p["in"] == "query"), + "query_aliases": { + p["name"] + "_": p["name"] + for p in parameters + if p["in"] == "query" and p["name"] in {"False", "None", "True", "and", "as", "assert", "async", "await", "break", "class", "continue", "def", "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "nonlocal", "not", "or", "pass", "raise", "return", "try", "while", "with", "yield"} + }, + "path_params": tuple(p["name"] for p in parameters if p["in"] == "path"), + "has_body": "requestBody" in operation, + } + assert OPERATIONS == expected + + +def test_required_inputs_are_preserved_in_generated_types(): + assert required_fields(GetOutcomeParams) == {"cursor", "nonce"} + assert {"commitId", "clientSeed", "endpoint"} <= required_fields(RevealRequest) + assert required_fields(StreamOutcomesParams) == {"endpoint"} + + +def test_inline_batch_variants_are_discriminated_typed_dicts(): + results_hint = get_type_hints(BatchResponse, include_extras=True)["results"] + results_list = get_args(results_hint)[0] + result_union = get_args(results_list)[0] + success, failure = get_args(result_union) + assert required_fields(success) == {"ok", "outcome"} + assert required_fields(failure) == {"ok", "error"} + success_literal = get_args(get_type_hints(success, include_extras=True)["ok"])[0] + failure_literal = get_args(get_type_hints(failure, include_extras=True)["ok"])[0] + assert get_args(success_literal) == (True,) + assert get_args(failure_literal) == (False,) + + +def test_alias_dependencies_are_emitted_in_runtime_safe_order(): + assert PasswordReceipt in get_args(PublicOutcome) \ No newline at end of file diff --git a/sdk/typescript/LICENSE b/sdk/typescript/LICENSE new file mode 100644 index 0000000..1633427 --- /dev/null +++ b/sdk/typescript/LICENSE @@ -0,0 +1,178 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any form, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2026 Provable.io diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md new file mode 100644 index 0000000..a8ca2f1 --- /dev/null +++ b/sdk/typescript/README.md @@ -0,0 +1,133 @@ +# @provableio/sdk + +Official **TypeScript SDK** for the [Provable.io](https://provable.io) provably-fair random number API. + +- 🔒 Fully typed — request params, query strings, and response bodies are generated from the canonical [OpenAPI 3.0 spec](https://provable.io/openapi.json). +- 🪶 Zero runtime dependencies. Uses the built-in `fetch` (Node 18+, browsers, Deno, Bun, Cloudflare Workers). +- 🔁 First-class support for `Idempotency-Key`, commit-reveal, batch draws, Merkle inclusion proofs, and the SSE outcome stream. +- 🧪 Works with `pk_test_*` keys (test-mode outcomes don't touch live seed state and don't count toward your quota). + +## Install + +```bash +npm install @provableio/sdk +# or: pnpm add @provableio/sdk / yarn add @provableio/sdk +``` + +## Quickstart + +```ts +import { ProvableClient } from "@provableio/sdk"; + +const client = new ProvableClient({ + apiKey: process.env.PROVABLE_KEY, // or omit for anonymous (rate-limited) calls +}); + +const { data, error } = await client.getInts({ + clientSeed: "order-42", + count: 5, + min: 1, + max: 100, +}); + +if (error) { + throw new Error(`API ${error.code ?? ""}: ${error.error}`); +} + +console.log(data.outcome); // the integers +console.log(data.serverHash); // commit you can later verify +``` + +Every method returns a discriminated `ApiResult = { data, error: null } | { data: null, error }`. +No exceptions are thrown for non-2xx responses — only network/abort errors throw. + +## Authentication + +Pass **one** of: + +```ts +new ProvableClient({ apiKey: "pk_live_..." }); // x-api-key header +new ProvableClient({ bearerToken: "pk_live_..." }); // Authorization: Bearer ... +``` + +Both anonymous and authenticated calls work. Anonymous calls are rate-limited by IP and aren't attributed to an account. + +## Idempotency + +Send a per-request idempotency key on any RNG endpoint. Retries within 24 hours return the original outcome byte-for-byte and **don't** count toward your daily quota. + +```ts +await client.getFloats( + { clientSeed: "order-42", count: 1 }, + { idempotencyKey: crypto.randomUUID() }, +); +``` + +## Commit / reveal + +```ts +const { data: commit } = await client.createCommit({ clientSeed: "round-1" }); +// ...later, after the player has locked in their bet: +const { data: reveal } = await client.revealCommit({ commitId: commit!.commitId }); +``` + +## Streaming outcomes (SSE) + +```ts +for await (const event of client.streamOutcomes( + { clientSeed: "live-feed" }, + { lastEventId: lastSeen }, +)) { + console.log(event); +} +``` + +Pass `AbortSignal` via the request options to stop the stream. + +## Batching + +```ts +const { data } = await client.batch({ + draws: [ + { kind: "ints", clientSeed: "s1", count: 3, min: 1, max: 6 }, + { kind: "floats", clientSeed: "s2", count: 2 }, + ], +}); +``` + +## Verification + +```ts +const { data } = await client.verifyServerHash({ + serverSeed: "...", + clientSeed: "order-42", + nonce: 0, +}); +``` + +## Escape hatch + +If you need to call an endpoint that's newer than this SDK, use the typed low-level helper: + +```ts +const res = await client.request("GET", "/api/some-new-endpoint", { + query: { foo: 1 }, + headers: { "X-Custom": "1" }, +}); +``` + +You can also import the raw generated OpenAPI types: + +```ts +import type { paths, components } from "@provableio/sdk"; +``` + +## Versioning + +Types are generated from [`sdk/openapi.json`](https://github.com/provableio/provable-core/blob/master/sdk/openapi.json), a copy of the spec served at https://provable.io/openapi.json. + +SDK versions follow semver. Breaking changes to the API surface bump the SDK's major version. + +## License + +Apache-2.0 © Provable.io diff --git a/sdk/typescript/package-lock.json b/sdk/typescript/package-lock.json new file mode 100644 index 0000000..e283d2a --- /dev/null +++ b/sdk/typescript/package-lock.json @@ -0,0 +1,398 @@ +{ + "name": "@provableio/sdk", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@provableio/sdk", + "version": "0.1.0", + "license": "Apache-2.0", + "devDependencies": { + "openapi-typescript": "^7.0.0", + "typescript": "^5.4.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz", + "integrity": "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.28.5", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", + "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@redocly/ajv": { + "version": "8.11.2", + "resolved": "https://registry.npmjs.org/@redocly/ajv/-/ajv-8.11.2.tgz", + "integrity": "sha512-io1JpnwtIcvojV7QKDUSIuMN/ikdOUd1ReEnUnMKGfDVridQZ31J0MmIuqwuRjWDZfmvr+Q0MqCcfHM2gTivOg==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2", + "uri-js-replace": "^1.0.1" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/@redocly/config": { + "version": "0.22.0", + "resolved": "https://registry.npmjs.org/@redocly/config/-/config-0.22.0.tgz", + "integrity": "sha512-gAy93Ddo01Z3bHuVdPWfCwzgfaYgMdaZPcfL7JZ7hWJoK9V0lXDbigTWkhiPFAaLWzbOJ+kbUQG1+XwIm0KRGQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@redocly/openapi-core": { + "version": "1.34.14", + "resolved": "https://registry.npmjs.org/@redocly/openapi-core/-/openapi-core-1.34.14.tgz", + "integrity": "sha512-y+xFx+Zz54Xhr8jUdnLENYnt7Y7GEDL6Q03ga7rTtX8DVwefX9H+hQEPgJp1nda7vdH+wJ9/HBVvyfBuW9x6rA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@redocly/ajv": "8.11.2", + "@redocly/config": "0.22.0", + "colorette": "1.4.0", + "https-proxy-agent": "7.0.6", + "js-levenshtein": "1.1.6", + "js-yaml": "4.1.1", + "minimatch": "5.1.9", + "pluralize": "8.0.0", + "yaml-ast-parser": "0.0.43" + }, + "engines": { + "node": ">=18.17.0", + "npm": ">=9.5.0" + } + }, + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/ansi-colors": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.3.tgz", + "integrity": "sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true, + "license": "Python-2.0" + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/brace-expansion": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz", + "integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/change-case": { + "version": "5.4.4", + "resolved": "https://registry.npmjs.org/change-case/-/change-case-5.4.4.tgz", + "integrity": "sha512-HRQyTk2/YPEkt9TnUPbOpr64Uw3KOicFWPVBb+xiHvd6eBx/qPr9xqfBFDT8P2vWsvvz4jbEkfDe71W3VyNu2w==", + "dev": true, + "license": "MIT" + }, + "node_modules/colorette": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/colorette/-/colorette-1.4.0.tgz", + "integrity": "sha512-Y2oEozpomLn7Q3HFP7dpww7AtMJplbM9lGZP6RDfHqmbeRjiwRg4n6VM6j4KLmRke85uWEI7JqF17f3pqdRA0g==", + "dev": true, + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/index-to-position": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/index-to-position/-/index-to-position-1.2.0.tgz", + "integrity": "sha512-Yg7+ztRkqslMAS2iFaU+Oa4KTSidr63OsFGlOrJoW981kIYO3CGCS3wA95P1mUi/IVSJkn0D479KTJpVpvFNuw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/js-levenshtein": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/js-levenshtein/-/js-levenshtein-1.1.6.tgz", + "integrity": "sha512-X2BB11YZtrRqY4EnQcLX5Rh373zbK4alC1FW7D7MBhL2gtcC17cTnr6DmfHZeS0s2rTHjUTMMHfG7gO8SSdw+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/js-yaml": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.1.tgz", + "integrity": "sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true, + "license": "MIT" + }, + "node_modules/minimatch": { + "version": "5.1.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.9.tgz", + "integrity": "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/openapi-typescript": { + "version": "7.13.0", + "resolved": "https://registry.npmjs.org/openapi-typescript/-/openapi-typescript-7.13.0.tgz", + "integrity": "sha512-EFP392gcqXS7ntPvbhBzbF8TyBA+baIYEm791Hy5YkjDYKTnk/Tn5OQeKm5BIZvJihpp8Zzr4hzx0Irde1LNGQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@redocly/openapi-core": "^1.34.6", + "ansi-colors": "^4.1.3", + "change-case": "^5.4.4", + "parse-json": "^8.3.0", + "supports-color": "^10.2.2", + "yargs-parser": "^21.1.1" + }, + "bin": { + "openapi-typescript": "bin/cli.js" + }, + "peerDependencies": { + "typescript": "^5.x" + } + }, + "node_modules/parse-json": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-8.3.0.tgz", + "integrity": "sha512-ybiGyvspI+fAoRQbIPRddCcSTV9/LsJbf0e/S85VLowVGzRmokfneg2kwVW/KU5rOXrPSbF1qAKPMgNTqqROQQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.26.2", + "index-to-position": "^1.1.0", + "type-fest": "^4.39.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/pluralize": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/pluralize/-/pluralize-8.0.0.tgz", + "integrity": "sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/supports-color": { + "version": "10.2.2", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-10.2.2.tgz", + "integrity": "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/type-fest": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-4.41.0.tgz", + "integrity": "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==", + "dev": true, + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/uri-js-replace": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/uri-js-replace/-/uri-js-replace-1.0.1.tgz", + "integrity": "sha512-W+C9NWNLFOoBI2QWDp4UT9pv65r2w5Cx+3sTYFvtMdDBxkKt1syCqsUdSFAChbEe1uK5TfS04wt/nGwmaeIQ0g==", + "dev": true, + "license": "MIT" + }, + "node_modules/yaml-ast-parser": { + "version": "0.0.43", + "resolved": "https://registry.npmjs.org/yaml-ast-parser/-/yaml-ast-parser-0.0.43.tgz", + "integrity": "sha512-2PTINUwsRqSd+s8XxKaJWQlUuEMHJQyEuh2edBbW8KNJz0SJPwUSD2zRWqezFEdN7IzAgeuYHFUCF7o8zRdZ0A==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=12" + } + } + } +} diff --git a/sdk/typescript/package.json b/sdk/typescript/package.json new file mode 100644 index 0000000..07bdd64 --- /dev/null +++ b/sdk/typescript/package.json @@ -0,0 +1,65 @@ +{ + "name": "@provableio/sdk", + "version": "0.1.0", + "description": "Official TypeScript SDK for the Provable.io provably-fair random number API. Generated from the public OpenAPI spec.", + "keywords": [ + "provable", + "provable.io", + "random", + "rng", + "commit-reveal", + "merkle", + "openapi", + "sdk" + ], + "homepage": "https://provable.io/api-docs", + "repository": { + "type": "git", + "url": "https://github.com/provableio/provable-core.git", + "directory": "sdk/typescript" + }, + "bugs": { + "url": "https://github.com/provableio/provable-core/issues" + }, + "license": "Apache-2.0", + "author": "Provable.io ", + "type": "module", + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + }, + "./types": { + "types": "./dist/openapi-types.d.ts" + } + }, + "files": [ + "dist", + "src", + "README.md", + "LICENSE" + ], + "engines": { + "node": ">=18" + }, + "scripts": { + "generate": "openapi-typescript ../openapi.json -o ./src/openapi-types.ts", + "build": "npm run generate && tsc -p tsconfig.json", + "prepublishOnly": "npm run build", + "test": "node --test test/*.test.mjs" + }, + "devDependencies": { + "openapi-typescript": "^7.0.0", + "typescript": "^5.4.0" + }, + "overrides": { + "brace-expansion": "2.1.4", + "js-yaml": "4.3.1" + }, + "publishConfig": { + "access": "public" + } +} diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.ts new file mode 100644 index 0000000..abef55a --- /dev/null +++ b/sdk/typescript/src/index.ts @@ -0,0 +1,428 @@ +/** + * Provable.io TypeScript SDK + * + * Thin, dependency-free, fully-typed client for the Provable.io + * provably-fair random number API. Types are generated from the public + * OpenAPI spec (`public/openapi.json`) and re-exported from `./types`. + * + * @example + * ```ts + * import { ProvableClient } from "@provableio/sdk"; + * + * const client = new ProvableClient({ apiKey: process.env.PROVABLE_KEY }); + * const { data, error } = await client.getFloats({ clientSeed: "order-42", count: 5 }); + * if (error) throw new Error(error.error); + * console.log(data.outcome); + * ``` + */ + +import type { paths, components } from "./openapi-types.js"; + +export type { paths, components } from "./openapi-types.js"; + +/** Operation-by-operation request/response helpers. */ +type PathItem

= paths[P]; +type OpGet

= PathItem

extends { get: infer O } ? O : never; +type OpPost

= PathItem

extends { post: infer O } ? O : never; + +type Query = O extends { parameters: { query?: infer Q } } ? Q : undefined; +type PathParams = O extends { parameters: { path: infer P } } ? P : undefined; +type JsonBody = O extends { + requestBody: { content: { "application/json": infer B } }; +} + ? B + : O extends { + requestBody?: { content: { "application/json": infer B } }; + } + ? B | undefined + : undefined; + +type OkResponse = O extends { + responses: { 200: { content: { "application/json": infer R } } }; +} + ? R + : O extends { + responses: { 201: { content: { "application/json": infer R } } }; + } + ? R + : unknown; + +type ErrResponse = components["schemas"]["Error"]; + +/** Discriminated result type returned by every client method. */ +export type ApiResult = + | { data: T; error: null; response: Response } + | { data: null; error: ErrResponse; response: Response }; + +export interface ProvableClientOptions { + /** + * Base URL of the API server. + * @default "https://api.provable.io" + */ + baseUrl?: string; + /** API key (sent as `x-api-key`). Use a `pk_test_*` key in test mode. */ + apiKey?: string; + /** Alternative to `apiKey`: send as `Authorization: Bearer `. */ + bearerToken?: string; + /** Optional custom fetch implementation (defaults to global `fetch`). */ + fetch?: typeof fetch; + /** Extra headers merged into every request. */ + defaultHeaders?: Record; +} + +export interface RequestOptions { + /** Per-request `Idempotency-Key` header (only meaningful on RNG endpoints). */ + idempotencyKey?: string; + /** Extra per-request headers (merged on top of client defaults). */ + headers?: Record; + /** AbortSignal forwarded to fetch. */ + signal?: AbortSignal; +} + +const DEFAULT_BASE_URL = "https://api.provable.io"; + +function buildQueryString(query: Record | undefined): string { + if (!query) return ""; + const params = new URLSearchParams(); + for (const [k, v] of Object.entries(query)) { + if (v === undefined || v === null) continue; + if (Array.isArray(v)) { + for (const item of v) params.append(k, String(item)); + } else { + params.append(k, String(v)); + } + } + const s = params.toString(); + return s ? `?${s}` : ""; +} + +function substitutePath(path: string, params: Record | undefined): string { + if (!params) return path; + return path.replace(/\{([^}]+)\}/g, (_m, key) => { + const value = params[key]; + if (value === undefined || value === null) { + throw new Error(`Missing path parameter: ${key}`); + } + return encodeURIComponent(String(value)); + }); +} + +/** + * Lightweight typed client for the Provable.io HTTP API. + * + * Every method returns an `ApiResult` discriminated union with `{ data, error, response }`. + * No exceptions are thrown for non-2xx responses; only network / abort errors throw. + */ +export class ProvableClient { + readonly baseUrl: string; + private readonly apiKey?: string; + private readonly bearerToken?: string; + private readonly fetchImpl: typeof fetch; + private readonly defaultHeaders: Record; + + constructor(opts: ProvableClientOptions = {}) { + this.baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, ""); + this.apiKey = opts.apiKey; + this.bearerToken = opts.bearerToken; + const f = opts.fetch ?? (typeof fetch !== "undefined" ? fetch : undefined); + if (!f) { + throw new Error( + "No global fetch available. Pass a fetch implementation via options.fetch (Node < 18).", + ); + } + this.fetchImpl = f.bind(globalThis); + this.defaultHeaders = { Accept: "application/json", ...(opts.defaultHeaders ?? {}) }; + } + + private buildHeaders(extra?: Record, hasBody = false): Headers { + const h = new Headers(this.defaultHeaders); + if (hasBody) h.set("Content-Type", "application/json"); + if (this.apiKey) h.set("x-api-key", this.apiKey); + else if (this.bearerToken) h.set("Authorization", `Bearer ${this.bearerToken}`); + if (extra) { + for (const [k, v] of Object.entries(extra)) h.set(k, v); + } + return h; + } + + /** Low-level request helper. Exposed for advanced use (e.g. new endpoints). */ + async request( + method: string, + path: string, + init: { + query?: Record; + pathParams?: Record; + body?: unknown; + } & RequestOptions = {}, + ): Promise> { + const finalPath = substitutePath(path, init.pathParams); + const url = this.baseUrl + finalPath + buildQueryString(init.query); + const hasBody = init.body !== undefined; + const headers = this.buildHeaders(init.headers, hasBody); + if (init.idempotencyKey) headers.set("Idempotency-Key", init.idempotencyKey); + + const response = await this.fetchImpl(url, { + method, + headers, + body: hasBody ? JSON.stringify(init.body) : undefined, + signal: init.signal, + }); + + const ct = response.headers.get("content-type") ?? ""; + const isJson = ct.includes("application/json"); + const payload = isJson ? await response.json() : await response.text(); + + if (response.ok) { + return { data: payload as T, error: null, response }; + } + const errorBody: ErrResponse = + isJson && payload && typeof payload === "object" + ? (payload as ErrResponse) + : { error: typeof payload === "string" ? payload : `HTTP ${response.status}` }; + return { data: null, error: errorBody, response }; + } + + // ----- Random ----- + + getFloats( + query: Query>, + opts?: RequestOptions, + ): Promise>>> { + return this.request("GET", "/api/floats", { query: query as Record, ...opts }); + } + + getInts( + query: Query>, + opts?: RequestOptions, + ): Promise>>> { + return this.request("GET", "/api/ints", { query: query as Record, ...opts }); + } + + shuffle( + query: Query>, + opts?: RequestOptions, + ): Promise>>> { + return this.request("GET", "/api/shuffle", { query: query as Record, ...opts }); + } + + pick( + query: Query>, + opts?: RequestOptions, + ): Promise>>> { + return this.request("GET", "/api/pick", { query: query as Record, ...opts }); + } + + getBytes( + query: Query>, + opts?: RequestOptions, + ): Promise>>> { + return this.request("GET", "/api/bytes", { query: query as Record, ...opts }); + } + + rollDice( + query: Query>, + opts?: RequestOptions, + ): Promise>>> { + return this.request("GET", "/api/dice", { query: query as Record, ...opts }); + } + + gaussian( + query: Query>, + opts?: RequestOptions, + ): Promise>>> { + return this.request("GET", "/api/gaussian", { query: query as Record, ...opts }); + } + + batch( + body: JsonBody>, + opts?: RequestOptions, + ): Promise>>> { + return this.request("POST", "/api/batch", { body, ...opts }); + } + + // ----- Verification / lookup ----- + + verifyServerHash( + query: Query>, + opts?: RequestOptions, + ): Promise>>> { + return this.request("GET", "/api/verifyServerHash", { + query: query as Record, + ...opts, + }); + } + + verifyShortId( + query: Query>, + opts?: RequestOptions, + ): Promise>>> { + return this.request("GET", "/api/verifyShortId", { + query: query as Record, + ...opts, + }); + } + + getOutcome( + query: Query>, + opts?: RequestOptions, + ): Promise>>> { + return this.request("GET", "/api/outcome", { query: query as Record, ...opts }); + } + + incrementCursor( + query: Query>, + opts?: RequestOptions, + ): Promise>>> { + return this.request("GET", "/api/incrementCursor", { + query: query as Record, + ...opts, + }); + } + + listOutcomes( + query: Query>, + opts?: RequestOptions, + ): Promise>>> { + return this.request("GET", "/api/listOutcomes", { + query: query as Record, + ...opts, + }); + } + + getOutcomePermalink( + pathParams: PathParams>, + opts?: RequestOptions, + ): Promise>>> { + return this.request("GET", "/o/{id}", { + pathParams: pathParams as Record, + ...opts, + }); + } + + // ----- Transparency / Merkle ----- + + listMerkleRoots( + query?: Query>, + opts?: RequestOptions, + ): Promise>>> { + return this.request("GET", "/api/merkle", { query: query as Record, ...opts }); + } + + getMerkleRoot( + pathParams: PathParams>, + opts?: RequestOptions, + ): Promise>>> { + return this.request("GET", "/api/merkle/{date}", { + pathParams: pathParams as Record, + ...opts, + }); + } + + getMerkleProof( + pathParams: PathParams>, + opts?: RequestOptions, + ): Promise>>> { + return this.request("GET", "/api/merkle/{date}/proof/{outcomeId}", { + pathParams: pathParams as Record, + ...opts, + }); + } + + // ----- Commit / reveal ----- + + createCommit( + body: JsonBody>, + opts?: RequestOptions, + ): Promise>>> { + return this.request("POST", "/api/commit", { body, ...opts }); + } + + revealCommit( + body: JsonBody>, + opts?: RequestOptions, + ): Promise>>> { + return this.request("POST", "/api/reveal", { body, ...opts }); + } + + rotateServerSeed( + body: JsonBody>, + opts?: RequestOptions, + ): Promise>>> { + return this.request("POST", "/api/rotate", { body, ...opts }); + } + + // ----- Health ----- + + getHealth(opts?: RequestOptions): Promise>>> { + return this.request("GET", "/api/health", { ...opts }); + } + + getPublicMetrics(opts?: RequestOptions): Promise>>> { + return this.request("GET", "/api/public-metrics", { ...opts }); + } + + /** + * Server-Sent Events stream of outcomes. Returns an async iterator of + * parsed event payloads. Pass `lastEventId` to resume from a known event. + * + * @example + * ```ts + * for await (const ev of client.streamOutcomes({ clientSeed: "live" })) { + * console.log(ev); + * } + * ``` + */ + async *streamOutcomes( + query: Query>, + opts: RequestOptions & { lastEventId?: string } = {}, + ): AsyncGenerator { + const url = this.baseUrl + "/api/stream" + buildQueryString(query as Record); + const headers = this.buildHeaders(opts.headers); + headers.set("Accept", "text/event-stream"); + if (opts.lastEventId) headers.set("Last-Event-ID", opts.lastEventId); + + const response = await this.fetchImpl(url, { + method: "GET", + headers, + signal: opts.signal, + }); + if (!response.ok || !response.body) { + throw new Error(`Stream failed: HTTP ${response.status}`); + } + + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + let buf = ""; + try { + while (true) { + const { value, done } = await reader.read(); + if (done) break; + buf += decoder.decode(value, { stream: true }); + let idx: number; + while ((idx = buf.indexOf("\n\n")) !== -1) { + const raw = buf.slice(0, idx); + buf = buf.slice(idx + 2); + const dataLines = raw + .split("\n") + .filter((l) => l.startsWith("data:")) + .map((l) => l.slice(5).trimStart()); + if (dataLines.length === 0) continue; + const dataStr = dataLines.join("\n"); + try { + yield JSON.parse(dataStr); + } catch { + yield dataStr; + } + } + } + } finally { + try { + reader.releaseLock(); + } catch { + /* noop */ + } + } + } +} + +export default ProvableClient; diff --git a/sdk/typescript/src/openapi-types.ts b/sdk/typescript/src/openapi-types.ts new file mode 100644 index 0000000..9ea68e3 --- /dev/null +++ b/sdk/typescript/src/openapi-types.ts @@ -0,0 +1,2474 @@ +/** + * This file was auto-generated by openapi-typescript. + * Do not make direct changes to the file. + */ + +export interface paths { + "/api/batch": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Run many draws in one round trip + * @description Accepts up to 50 independent draws across any of the random-generating endpoints (`floats`, `ints`, `shuffle`, `pick`, `bytes`, `dice`, `gaussian`) and returns one result per draw in the same order. + * + * - Each draw uses its own `clientSeed`/`cursor`/`nonce`, so any single outcome is independently verifiable via `/api/verifyServerHash` and gets its own `shortId`/`permalink`. + * - A failing draw is reported as `{ ok: false, error }` and does **not** abort the batch — successful draws still persist their outcomes. + * - Authenticated calls bump usage counters once per **successful** draw. If the daily quota is reached mid-batch, the remaining draws short-circuit with `{ ok: false, error: "…", code: "quota_exceeded" }` instead of running. + * - One `Idempotency-Key` covers the whole batch: a retry with the same key replays the identical `results` array and does not re-run any draw. + */ + post: operations["batchDraw"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/bytes": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Generate random bytes + * @description Return `count` random bytes encoded as `hex` (default) or `base64`. Useful for tokens, salts, and key material. + */ + get: operations["getBytes"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/commit": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Commit a server seed (commit-reveal step 1) + * @description Stronger fairness guarantee than `/api/floats` and `/api/ints`. The server generates a fresh `serverSeed`, publishes its `serverHash`, and holds the seed secret until you reveal. Because the hash is published *before* you submit your `clientSeed`, the server cannot pick its seed in response to yours. Follow with `POST /api/reveal` within the commit's TTL (default 10 minutes). + */ + post: operations["createCommit"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/dice": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Roll dice + * @description Roll dice using standard tabletop notation. Returns the individual rolls, the modifier, and the total. + */ + get: operations["rollDice"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/floats": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Generate random floats + * @description Generate cryptographically verifiable random floating-point numbers in the range [0, 1). + */ + get: operations["getFloats"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/gaussian": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Sample a statistical distribution + * @description Draw samples from a `normal`, `exponential`, or `poisson` distribution with caller-supplied parameters. + */ + get: operations["gaussian"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/health": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Service health + * @description Service health, version, and uptime. Returns 503 when the database is unreachable or the server is shutting down. + */ + get: operations["getHealth"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/public-metrics": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Public service metrics + * @description Privacy-safe aggregate adoption and operational metrics for the homepage. The account value is the current account total. The outcome value is a persisted lifetime total that includes anonymous traffic and excludes test mode. Counts contain no account or outcome details. Response time covers only successful, completed, non-test, non-stream requests to public product API endpoints in the recent in-memory window on the current server instance. + */ + get: operations["getPublicMetrics"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/incrementCursor": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Advance the cursor for a client seed + * @description Bumps the cursor for the given `clientSeed`; `nonce` keeps counting up so no earlier draw is ever repeated. The next call to `/api/floats` or `/api/ints` for this seed will derive from a fresh row in the underlying HMAC stream. Use this to rotate to a new "round" of draws without changing the seed pair. Returns `400` if the client seed has no recorded state yet. + */ + get: operations["incrementCursor"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/ints": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Generate random integers + * @description Generate cryptographically verifiable random integers within a custom inclusive range. + */ + get: operations["getInts"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/listOutcomes": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * List outcomes for a client seed + * @description List recorded outcomes for a given client seed, newest first, at most `limit` (default and max 1000) per call. To page, pass `before=:` from the last outcome of the previous page. Password-tool receipts retain verification metadata but never return the generated integers or derivation coordinates. + */ + get: operations["listOutcomes"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/merkle": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * List recent daily Merkle roots + * @description Returns the most recent daily Merkle roots in reverse chronological order. Each root commits to every outcome generated during that UTC day. + */ + get: operations["listMerkleRoots"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/merkle/{date}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Get a published daily Merkle root + * @description Returns the published Merkle root for the given UTC day, plus the leaf count, tree height, and publish timestamp. + */ + get: operations["getMerkleRoot"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/merkle/{date}/proof/{outcomeId}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Get an inclusion proof for an outcome + * @description Returns the Merkle inclusion proof for `outcomeId` within the published tree for `date`. The proof contains the leaf, its index, the sibling hashes along the path to the root, and the published root itself. Anyone can verify the proof locally by recomputing the root from the leaf and siblings — see the leaf encoding documented at `/transparency` and `/api-docs#merkle`. + */ + get: operations["getMerkleProof"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/outcome": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Look up a single recorded outcome + * @description Fetches a single recorded outcome by its `(clientSeed, cursor, nonce)` triple. Useful for re-fetching a known outcome's full record (including `serverHash`, `endpoint`-specific fields, and `shortId`) without scanning the whole seed via `/api/listOutcomes`. Password-tool receipts never return the generated integers or derivation coordinates. Returns `400` when the outcome is not found. + */ + get: operations["getOutcome"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/pick": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Weighted random pick + * @description Pick one item from a list, optionally with per-item weights. Returns the chosen item and its zero-based `index`. + */ + get: operations["pickItem"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/reveal": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Reveal and use a committed server seed (commit-reveal step 2) + * @description Submit your `clientSeed` and the generation parameters against a previously committed `commitId`. The server marks the commit revealed (single-use), runs the requested generation against the committed `serverSeed`, persists the outcome, and returns the outcome plus the revealed `serverSeed` so you can independently re-derive the values. Returns `409 Conflict` if the commit has already been revealed, `410 Gone` if it expired, and `404` if it never existed. + */ + post: operations["revealCommit"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/rotate": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Rotate the server seed for a client seed + * @description Reveals the *previous* `serverSeed` for the given `clientSeed`, then generates a fresh `serverSeed`. `cursor` and `nonce` carry over unchanged, so recorded outcomes keep unique coordinates. This is the **only** endpoint that exposes the one-shot `serverSeed` — `/api/floats`, `/api/ints`, the RNG primitives, and `/api/listOutcomes` only ever surface `serverHash`. + * + * **Per-key hash chains.** Each api key has its own independent hash chain per `clientSeed`. Rotating an authenticated call rotates *only* that key's chain — it does not touch any other key's chain or the anonymous chain. + * + * **Anonymous callers** rotate the shared anonymous chain for the given `clientSeed`. There is no ownership on that chain — any caller (authenticated or not) can rotate it. + * + * **Test keys.** `pk_test_*` keys are rejected with `403` (`code: "test_mode_forbidden"`): test mode has no live chain of its own, so rotation is undefined for it. + * + * The addressed chain must already have at least one recorded outcome (i.e. that key — or an anonymous caller, for the anon chain — has called `/api/floats` or `/api/ints` with this `clientSeed`), otherwise the response is `404`. + */ + post: operations["rotateServerSeed"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/shuffle": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Shuffle an array + * @description Return a uniformly fair shuffle of a caller-supplied array. The same `clientSeed`/`cursor`/`nonce` triple always yields the same permutation, so the result is fully verifiable. + */ + get: operations["shuffleItems"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/stream": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Stream outcomes as Server-Sent Events + * @description Open a long-lived Server-Sent Events (SSE) connection that emits one verifiable outcome per `intervalMs`, up to a server-enforced 10-minute cap. + * + * **The response shape differs from every other endpoint here.** Instead of returning a single JSON body, the server holds the connection open and writes a stream of `text/event-stream` frames. Each frame is a self-contained `event: outcome` message whose `data:` field is a full JSON outcome (identical shape to the matching non-streaming endpoint, plus an `outcomeId` of `clientSeed:cursor:nonce`). Every emitted outcome verifies independently via `/api/verifyServerHash`. + * + * Heartbeat comments (`: heartbeat …`) are sent every ~15 seconds. When the duration cap or quota is reached the server emits a terminal `event: done` frame and closes — reconnect to keep streaming. Closing the client (e.g. `EventSource.close()`) cleanly stops billing. Each emitted outcome counts as one billed call for live-key streams. + * + * **Resuming after a disconnect.** Every `event: outcome` frame includes an `id:` line of `clientSeed:cursor:nonce`. On a transient drop, browsers' built-in `EventSource` auto-reconnects and replays it as a `Last-Event-ID` request header; raw `fetch` clients can pass the same value as a `?lastEventId=` query parameter. Either way the server only emits outcomes strictly after that point on the same `clientSeed`, so reconnects don't double-count or skip — and skipped duplicates aren't billed. + */ + get: operations["streamOutcomes"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/verifyServerHash": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Verify a server hash + * @description Verify that a server hash matches our records for a given client seed. Returns `true` if the hash is authentic. + */ + get: operations["verifyServerHash"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/verifyShortId": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Verify an outcome by shortId + * @description Public, no-auth verifier used by the `/verify` landing page. Given a `shortId` returned by any random-generating endpoint (or visible in an `/o/:id` permalink), returns recorded metadata and a server-computed verification verdict. Password-tool receipts never return the generated integers or derivation coordinates. A response is `verified: true` when either (a) the live seed state still carries the same `serverHash` or (b) the `serverSeed` has been revealed and `sha256(serverSeed)` reproduces the recorded `serverHash`. + */ + get: operations["verifyShortId"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/o/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Public outcome permalink page + * @description Public, no-auth HTML page for a recorded outcome. Anyone with the `shortId` can open it to see the endpoint, parameters, client seed, server hash, the generated values, and a server-side **Verified ✓** / **Mismatch ✗** badge. Includes `og:image` / `og:title` meta tags so links unfurl in Slack, Discord, and X. The `shortId` is returned by `/api/floats`, `/api/ints`, `/api/listOutcomes`, and `/api/verifyServerHash`. + */ + get: operations["getOutcomePermalink"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/o/{id}/og.png": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Dynamic social-preview image for an outcome permalink + * @description Returns a 1200×630 PNG rendered from the outcome (shortId, endpoint, **Verified ✓** / **Unverified** badge, count, and a sample of the generated values). Used as the `og:image` / `twitter:image` for `/o/{id}` so links unfurl with a per-outcome card in Slack, Discord, and X. Responses are cached (5 minutes). If the outcome doesn't exist or rendering fails, the generic site `og-image.jpg` is returned with a short cache so unfurls never break. + */ + get: operations["getOutcomeOgImage"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; +} +export type webhooks = Record; +export interface components { + schemas: { + /** @description Fields shared by every recorded outcome. Each concrete `*Outcome` schema extends this with its own `endpoint` discriminator value, `outcome` shape, and any endpoint-specific parameters. */ + BaseOutcome: { + clientSeed: string; + /** @description SHA-256 hash of the server seed used for this generation. */ + serverHash: string; + nonce: number; + cursor: number; + /** @description Number of underlying draws this outcome represents (e.g. requested float count, number of dice rolled, items shuffled). */ + count: number; + /** + * Format: int64 + * @description Unix timestamp in milliseconds. + */ + created: number; + /** @description Stable ~10-character public ID for this outcome. Used to build a shareable permalink at /o/{shortId}. */ + shortId: string; + /** + * @description `live` for real cryptographic randomness drawn from the (api key, clientSeed) hash chain. `test` is returned when the call was authenticated with a `pk_test_…` key; the outcome is deterministic per (account, clientSeed), bypasses the live chain entirely, is excluded from live usage stats, and does not trigger webhooks. + * @enum {string} + */ + mode: "live" | "test"; + /** @description Optional display settings saved by Provable.io's browser tools so a shared result can be reconstructed. */ + toolMeta?: { + [key: string]: unknown; + }; + /** @description Present on public lookup responses. True when sensitive password result material was removed. */ + redacted?: boolean; + }; + /** @description Public verification receipt for a password-tool call. The generated integer stream and its derivation coordinates are deliberately null. */ + PasswordReceipt: { + serverHash: string; + /** @enum {string} */ + endpoint: "ints"; + outcome: unknown; + clientSeed?: string | null; + cursor?: number | null; + nonce?: number | null; + count?: number | null; + min?: number | null; + max?: number | null; + /** Format: int64 */ + created?: number | null; + shortId: string; + mode?: string; + toolMeta: { + [key: string]: unknown; + }; + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + redacted: "true"; + /** Format: uri */ + permalink?: string | null; + }; + /** @description A normal outcome or a redacted password verification receipt returned by public lookup endpoints. */ + PublicOutcome: components["schemas"]["Outcome"] | components["schemas"]["PasswordReceipt"]; + /** @description Discriminated union of every concrete outcome shape returned by the random-generating endpoints. Use the `endpoint` field to pick the matching schema. */ + Outcome: components["schemas"]["FloatOutcome"] | components["schemas"]["IntOutcome"] | components["schemas"]["ShuffleOutcome"] | components["schemas"]["PickOutcome"] | components["schemas"]["BytesOutcome"] | components["schemas"]["DiceOutcome"] | components["schemas"]["GaussianOutcome"]; + /** @description Result of /api/verifyServerHash, including any recorded outcomes matching the (clientSeed, serverHash) pair. */ + VerifyResult: { + /** @description True when the server hash matches what we have on file for this client seed. */ + verified: boolean; + clientSeed: string; + serverHash: string; + /** @description Permalinks for every recorded outcome under this (clientSeed, serverHash). May be empty if none were recorded. */ + outcomes: { + shortId: string; + /** Format: uri */ + permalink: string; + endpoint?: string | null; + cursor?: number; + nonce?: number; + /** Format: int64 */ + created?: number | null; + }[]; + }; + FloatOutcome: components["schemas"]["BaseOutcome"] & { + outcome: number[]; + /** @enum {string} */ + endpoint: "floats"; + /** + * @description `live` for real cryptographic randomness. `test` is returned when the call was authenticated with a `pk_test_…` key; the outcome is deterministic per (account, clientSeed), is excluded from live usage stats, and does not trigger webhooks. + * @enum {string} + */ + mode: "live" | "test"; + /** + * Format: uri + * @description Absolute public URL anyone can open to view and re-verify this outcome. + */ + permalink: string; + } & { + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + endpoint: "floats"; + }; + IntOutcome: components["schemas"]["BaseOutcome"] & { + outcome: number[]; + /** @enum {string} */ + endpoint: "ints"; + /** @description Inclusive lower bound used for this draw. */ + min: number; + /** @description Inclusive upper bound used for this draw. */ + max: number; + /** + * @description `live` for real cryptographic randomness. `test` is returned when the call was authenticated with a `pk_test_…` key; the outcome is deterministic per (account, clientSeed), is excluded from live usage stats, and does not trigger webhooks. + * @enum {string} + */ + mode: "live" | "test"; + /** + * Format: uri + * @description Absolute public URL anyone can open to view and re-verify this outcome. + */ + permalink: string; + } & { + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + endpoint: "ints"; + }; + /** @description A published daily Merkle root over every outcome produced in a single UTC day. */ + MerkleRoot: { + /** @description UTC date in YYYY-MM-DD form. */ + date: string; + /** @description Hex-encoded SHA-256 root. Empty string when the day had zero outcomes. */ + root: string; + leafCount: number; + treeHeight: number; + /** + * Format: int64 + * @description Unix timestamp in milliseconds when the root was published. + */ + publishedAt: number; + }; + /** @description Inclusion proof for a single outcome within a published daily Merkle tree. */ + MerkleProof: { + date: string; + /** @description `clientSeed:cursor:nonce`. */ + outcomeId: string; + leaf: { + outcomeId?: string; + serverHash?: string; + clientSeed?: string; + /** Format: int64 */ + timestamp?: number; + /** @description `outcomeId|serverHash|clientSeed|timestamp` — the exact bytes that get hashed into the leaf. */ + canonical: string; + /** @description Hex of `SHA256(0x00 || utf8(canonical))`. */ + hash: string; + }; + /** @description Zero-based position of the leaf in the sorted day. */ + index: number; + leafCount: number; + treeHeight?: number; + /** @description Published root the proof terminates at. */ + root: string; + /** Format: int64 */ + publishedAt?: number; + /** @description Sibling hashes from leaf level up to the root. */ + siblings: { + /** + * @description Side of the sibling relative to the accumulator: 'left' means `SHA256(0x01 || sibling || acc)`, 'right' means `SHA256(0x01 || acc || sibling)`. + * @enum {string} + */ + position: "left" | "right"; + hash: string; + }[]; + }; + ShuffleOutcome: components["schemas"]["BaseOutcome"] & { + /** @description The input array shuffled into its verifiable permutation. Same length and contents as the request. */ + outcome: unknown[]; + /** @enum {string} */ + endpoint: "shuffle"; + /** + * Format: uri + * @description Absolute public URL anyone can open to view and re-verify this outcome. + */ + permalink: string; + } & { + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + endpoint: "shuffle"; + }; + /** @description A pre-committed server seed published by the server. Hold onto `commitId` and `serverHash`; reveal before `expiresAt` (Unix ms) by calling `/api/reveal`. */ + Commit: { + /** Format: uuid */ + commitId: string; + /** @description SHA-256 hash of the secret server seed. */ + serverHash: string; + /** + * Format: int64 + * @description Unix timestamp in ms after which the commit is no longer revealable. + */ + expiresAt: number; + }; + RevealRequest: { + /** + * Format: uuid + * @description The `commitId` returned by `/api/commit`. + */ + commitId: string; + clientSeed: string; + /** + * @description Which generator to run against the committed server seed. + * @enum {string} + */ + endpoint: "floats" | "ints"; + /** @description Generator parameters. For `floats`: `{ count }`. For `ints`: `{ count, min, max }`. */ + params?: { + /** @default 1 */ + count: number; + /** @default 1 */ + min: number; + /** @default 100 */ + max: number; + }; + }; + RevealOutcome: components["schemas"]["BaseOutcome"] & { + /** @description Generated values. `number` items for `endpoint: "floats"` (each in [0, 1)); `integer` items for `endpoint: "ints"`. */ + outcome: number[]; + /** @enum {string} */ + endpoint: "floats" | "ints"; + /** @description Inclusive lower bound (only present when `endpoint: "ints"`). */ + min?: number; + /** @description Inclusive upper bound (only present when `endpoint: "ints"`). */ + max?: number; + /** @description The now-revealed server seed. Verify by checking SHA-256(serverSeed) === serverHash. */ + serverSeed: string; + /** Format: uuid */ + commitId: string; + }; + PickOutcome: components["schemas"]["BaseOutcome"] & { + /** @description The picked item (any JSON value drawn from the input `items` array). */ + outcome: unknown; + /** @description Zero-based index of the picked item. */ + index: number; + /** @description The per-item weights supplied with the request, or `null` when the caller used the default uniform distribution. */ + weights: number[] | null; + /** @enum {string} */ + endpoint: "pick"; + /** + * Format: uri + * @description Absolute public URL anyone can open to view and re-verify this outcome. + */ + permalink: string; + } & { + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + endpoint: "pick"; + }; + BytesOutcome: components["schemas"]["BaseOutcome"] & { + /** @description Random bytes encoded as `hex` or `base64`, matching the `encoding` field. */ + outcome: string; + /** @enum {string} */ + encoding: "hex" | "base64"; + /** @enum {string} */ + endpoint: "bytes"; + /** + * Format: uri + * @description Absolute public URL anyone can open to view and re-verify this outcome. + */ + permalink: string; + } & { + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + endpoint: "bytes"; + }; + DiceOutcome: components["schemas"]["BaseOutcome"] & { + outcome: { + /** @description Canonical `NdM`, `NdM+K`, or `NdM-K` form of the roll. */ + notation: string; + rolls: number[]; + modifier: number; + /** @description Sum of `rolls` plus `modifier`. */ + total: number; + }; + /** @description Number of sides on each die (parsed from the request notation). */ + sides: number; + /** @description Flat modifier (parsed from the request notation). */ + modifier: number; + /** @enum {string} */ + endpoint: "dice"; + /** + * Format: uri + * @description Absolute public URL anyone can open to view and re-verify this outcome. + */ + permalink: string; + } & { + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + endpoint: "dice"; + }; + GaussianOutcome: components["schemas"]["BaseOutcome"] & { + outcome: number[]; + /** @enum {string} */ + distribution: "normal" | "exponential" | "poisson"; + /** @description Mean (μ). Present only when `distribution: "normal"`. */ + mean?: number; + /** @description Standard deviation (σ). Present only when `distribution: "normal"`. */ + stddev?: number; + /** @description Rate parameter (λ). Present only when `distribution: "exponential"` or `"poisson"`. */ + lambda?: number; + /** @enum {string} */ + endpoint: "gaussian"; + /** + * Format: uri + * @description Absolute public URL anyone can open to view and re-verify this outcome. + */ + permalink: string; + } & { + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + endpoint: "gaussian"; + }; + BatchRequest: { + draws: { + /** + * @description Which random-generating endpoint to invoke for this draw. + * @enum {string} + */ + endpoint: "floats" | "ints" | "shuffle" | "pick" | "bytes" | "dice" | "gaussian"; + /** @description The same parameters you would pass as query string to the single-draw endpoint. Each draw must supply its own `clientSeed`. */ + params?: { + [key: string]: unknown; + }; + }[]; + }; + BatchResponse: { + /** @description One result per requested draw, in the same order as `draws`. */ + results: ({ + /** @enum {boolean} */ + ok: true; + outcome: components["schemas"]["Outcome"]; + } | { + /** @enum {boolean} */ + ok: false; + error: string; + /** @description Machine-readable failure code, e.g. `quota_exceeded`. */ + code?: string; + })[]; + }; + PublicMetrics: { + registeredUsers: { + value: number | null; + /** @enum {string} */ + scope: "current"; + }; + callsServed: { + value: number | null; + /** @enum {string} */ + scope: "lifetime_live_non_test"; + }; + responseTime: { + avgMs: number | null; + sampleSize: number; + /** @enum {string} */ + scope: "recent_instance_window"; + }; + /** @enum {string} */ + apiStatus: "operational" | "degraded"; + }; + Health: { + /** @enum {string} */ + status: "ok" | "degraded" | "shutting_down"; + /** @enum {string} */ + db?: "ok" | "down"; + version: string; + /** @description Seconds since process start. */ + uptime: number; + /** Format: date-time */ + timestamp: string; + /** @description Rolling in-memory response-time aggregate for /api/* traffic on this server instance. Resets on restart. */ + responseTimes?: { + /** @description Number of samples retained per endpoint bucket. */ + windowSize?: number; + overall?: components["schemas"]["ResponseTimeStats"]; + /** @description Per-endpoint stats, keyed by the grouped path (e.g. /api/floats). */ + endpoints?: { + [key: string]: components["schemas"]["ResponseTimeStats"]; + }; + }; + /** @description Process-local health signal for failed atomic usage-accounting writes. Resets on restart. */ + usagePersistence?: { + failures: number; + /** Format: date-time */ + lastFailureAt: string | null; + /** @description Durable usage reservations awaiting reconciliation; null only if the health query itself failed. */ + pendingReservations: number | null; + }; + }; + ResponseTimeStats: { + count: number; + avgMs: number; + p50Ms: number; + p95Ms: number; + maxMs: number; + }; + Error: { + error: string; + /** @description Correlation id present on 5xx responses. */ + requestId?: string; + /** @description Seconds to wait before retrying (on 429 responses). */ + retryAfter?: number | null; + }; + }; + responses: { + /** @description The supplied `Idempotency-Key` was previously used with a different request body or query parameters. The response body's `code` is `idempotency_key_conflict`. Either retry the original request unchanged (in which case the cached response is replayed within the 24h TTL with `Idempotent-Replayed: true`) or pick a fresh key for the new request. */ + IdempotencyConflict: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "Idempotency-Key was reused with different request parameters. Use a new key for a new request.", + * "code": "idempotency_key_conflict" + * } + */ + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Invalid request (e.g. missing or out-of-range parameters). */ + BadRequest: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "clientSeed is required" + * } + */ + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description An API key was supplied but is unknown or revoked. The response body's `code` is `invalid_api_key`. Omit the key to call anonymously. */ + InvalidApiKey: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "Invalid or revoked API key. Omit the key to call anonymously.", + * "code": "invalid_api_key" + * } + */ + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Too many requests. Anonymous calls are limited per IP; authenticated calls have per-account daily quotas. */ + RateLimited: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "Too many requests. Please slow down and try again shortly.", + * "retryAfter": 30 + * } + */ + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Unexpected server error. */ + ServerError: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "Internal server error", + * "requestId": "a1b2c3d4e5f60718" + * } + */ + "application/json": components["schemas"]["Error"]; + }; + }; + }; + parameters: { + /** @description Your seed for this generation. Combined with the server seed to produce provably fair output. Defaults to the literal string `"test"` when omitted, so anonymous demos work out of the box — production callers should always pass a stable, caller-owned value (your account id, a session id, etc.) to keep their own deterministic seed history. */ + ClientSeed: string; + /** @description Number of values to generate (1-100). */ + Count: number; + /** @description Reserved JSON object (up to 512 characters) used by supported Provable.io browser tools. API clients normally omit this. */ + ToolMeta: string; + /** + * @description Optional opaque string (≤255 chars). When supplied on any random-generating endpoint (`/api/floats`, `/api/ints`, `/api/shuffle`, `/api/pick`, `/api/bytes`, `/api/dice`, `/api/gaussian`, `/api/batch`), the server stores the response for 24 hours and returns the **same** status, body, and `Content-Type` for any retry that uses the same key — replays are flagged with the `Idempotent-Replayed: true` response header and do **not** consume quota. Reusing the key with a different request body or query parameters returns `409 Conflict` with code `idempotency_key_conflict`. Keys are scoped per API key (or per IP for anonymous calls), so two callers can use the same opaque value without collision. + * @example 8c3d7b9e-1f2a-4c5d-9e8f-7a6b5c4d3e2f + */ + IdempotencyKey: string; + }; + requestBodies: never; + headers: { + /** + * @description Server processing duration for this finite successful live response, formatted as `total;dur=`. The duration is measured by the server and does not include network transfer, client work, or the browser's full round-trip time. The header is omitted for test-key responses, when a reliable measurement is unavailable, and is not guaranteed on error responses. It is intentionally not reported for SSE responses because an initial-response setup measurement would not represent the lifetime of the stream. + * @example total;dur=12.4 + */ + ServerTiming: string; + }; + pathItems: never; +} +export type $defs = Record; +export interface operations { + batchDraw: { + parameters: { + query?: never; + header?: { + /** + * @description Optional opaque string (≤255 chars). When supplied on any random-generating endpoint (`/api/floats`, `/api/ints`, `/api/shuffle`, `/api/pick`, `/api/bytes`, `/api/dice`, `/api/gaussian`, `/api/batch`), the server stores the response for 24 hours and returns the **same** status, body, and `Content-Type` for any retry that uses the same key — replays are flagged with the `Idempotent-Replayed: true` response header and do **not** consume quota. Reusing the key with a different request body or query parameters returns `409 Conflict` with code `idempotency_key_conflict`. Keys are scoped per API key (or per IP for anonymous calls), so two callers can use the same opaque value without collision. + * @example 8c3d7b9e-1f2a-4c5d-9e8f-7a6b5c4d3e2f + */ + "Idempotency-Key"?: components["parameters"]["IdempotencyKey"]; + }; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + /** + * @example { + * "draws": [ + * { + * "endpoint": "ints", + * "params": { + * "clientSeed": "chest-1", + * "count": 1, + * "min": 1, + * "max": 100 + * } + * }, + * { + * "endpoint": "ints", + * "params": { + * "clientSeed": "chest-2", + * "count": 1, + * "min": 1, + * "max": 100 + * } + * }, + * { + * "endpoint": "pick", + * "params": { + * "clientSeed": "loot-3", + * "items": [ + * "common", + * "rare", + * "legendary" + * ], + * "weights": [ + * 70, + * 25, + * 5 + * ] + * } + * } + * ] + * } + */ + "application/json": components["schemas"]["BatchRequest"]; + }; + }; + responses: { + /** @description One result per draw, in request order. */ + 200: { + headers: { + "Server-Timing": components["headers"]["ServerTiming"]; + [name: string]: unknown; + }; + content: { + /** + * @example { + * "results": [ + * { + * "ok": true, + * "outcome": { + * "outcome": [ + * 42 + * ], + * "clientSeed": "chest-1", + * "serverHash": "9f86d081884c7d65...", + * "nonce": 0, + * "cursor": 0, + * "count": 1, + * "min": 1, + * "max": 100, + * "endpoint": "ints", + * "created": 1716566400000, + * "shortId": "k7Qm2A9bXz", + * "permalink": "https://provable.io/o/k7Qm2A9bXz" + * } + * }, + * { + * "ok": true, + * "outcome": { + * "outcome": [ + * 73 + * ], + * "clientSeed": "chest-2", + * "serverHash": "5e3b...", + * "nonce": 0, + * "cursor": 0, + * "count": 1, + * "min": 1, + * "max": 100, + * "endpoint": "ints", + * "created": 1716566400000, + * "shortId": "9aB2c3D4eF", + * "permalink": "https://provable.io/o/9aB2c3D4eF" + * } + * }, + * { + * "ok": true, + * "outcome": { + * "outcome": "legendary", + * "index": 2, + * "clientSeed": "loot-3", + * "serverHash": "0a1b...", + * "nonce": 0, + * "cursor": 0, + * "count": 1, + * "weights": [ + * 70, + * 25, + * 5 + * ], + * "endpoint": "pick", + * "created": 1716566400000, + * "shortId": "P9q8R7s6T5", + * "permalink": "https://provable.io/o/P9q8R7s6T5" + * } + * } + * ] + * } + */ + "application/json": components["schemas"]["BatchResponse"]; + }; + }; + 400: components["responses"]["BadRequest"]; + 401: components["responses"]["InvalidApiKey"]; + 409: components["responses"]["IdempotencyConflict"]; + 429: components["responses"]["RateLimited"]; + 500: components["responses"]["ServerError"]; + }; + }; + getBytes: { + parameters: { + query?: { + /** @description Your seed for this generation. Combined with the server seed to produce provably fair output. Defaults to the literal string `"test"` when omitted, so anonymous demos work out of the box — production callers should always pass a stable, caller-owned value (your account id, a session id, etc.) to keep their own deterministic seed history. */ + clientSeed?: components["parameters"]["ClientSeed"]; + /** @description Number of bytes to generate (1-1024). */ + count?: number; + /** @description Output encoding. */ + encoding?: "hex" | "base64"; + }; + header?: { + /** + * @description Optional opaque string (≤255 chars). When supplied on any random-generating endpoint (`/api/floats`, `/api/ints`, `/api/shuffle`, `/api/pick`, `/api/bytes`, `/api/dice`, `/api/gaussian`, `/api/batch`), the server stores the response for 24 hours and returns the **same** status, body, and `Content-Type` for any retry that uses the same key — replays are flagged with the `Idempotent-Replayed: true` response header and do **not** consume quota. Reusing the key with a different request body or query parameters returns `409 Conflict` with code `idempotency_key_conflict`. Keys are scoped per API key (or per IP for anonymous calls), so two callers can use the same opaque value without collision. + * @example 8c3d7b9e-1f2a-4c5d-9e8f-7a6b5c4d3e2f + */ + "Idempotency-Key"?: components["parameters"]["IdempotencyKey"]; + }; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description An encoded byte string and the associated server hash. */ + 200: { + headers: { + "Server-Timing": components["headers"]["ServerTiming"]; + [name: string]: unknown; + }; + content: { + /** + * @example { + * "outcome": "3f0a8b7d1c4e6f209a8c5b4d2e1f0a8b", + * "clientSeed": "my-app", + * "serverHash": "9f86d081884c7d65...", + * "nonce": 0, + * "cursor": 0, + * "count": 16, + * "encoding": "hex", + * "endpoint": "bytes", + * "created": 1716566400000 + * } + */ + "application/json": components["schemas"]["BytesOutcome"]; + }; + }; + 400: components["responses"]["BadRequest"]; + 401: components["responses"]["InvalidApiKey"]; + 409: components["responses"]["IdempotencyConflict"]; + 429: components["responses"]["RateLimited"]; + 500: components["responses"]["ServerError"]; + }; + }; + createCommit: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description A new commit. Save `commitId` and `serverHash` for verification, then call `/api/reveal`. */ + 200: { + headers: { + "Server-Timing": components["headers"]["ServerTiming"]; + [name: string]: unknown; + }; + content: { + /** + * @example { + * "commitId": "8c3d7b9e-1f2a-4c5d-9e8f-7a6b5c4d3e2f", + * "serverHash": "9f86d081884c7d65...", + * "expiresAt": 1716567000000 + * } + */ + "application/json": components["schemas"]["Commit"]; + }; + }; + 401: components["responses"]["InvalidApiKey"]; + 429: components["responses"]["RateLimited"]; + 500: components["responses"]["ServerError"]; + }; + }; + rollDice: { + parameters: { + query: { + /** @description Your seed for this generation. Combined with the server seed to produce provably fair output. Defaults to the literal string `"test"` when omitted, so anonymous demos work out of the box — production callers should always pass a stable, caller-owned value (your account id, a session id, etc.) to keep their own deterministic seed history. */ + clientSeed?: components["parameters"]["ClientSeed"]; + /** + * @description Dice notation `NdM`, `NdM+K`, or `NdM-K`. N: 1-100 dice. M: 2-1,000,000 sides. K: integer modifier added to the total. Examples: `3d6`, `2d20+5`, `1d100-10`. + * @example 3d6+2 + */ + notation: string; + }; + header?: { + /** + * @description Optional opaque string (≤255 chars). When supplied on any random-generating endpoint (`/api/floats`, `/api/ints`, `/api/shuffle`, `/api/pick`, `/api/bytes`, `/api/dice`, `/api/gaussian`, `/api/batch`), the server stores the response for 24 hours and returns the **same** status, body, and `Content-Type` for any retry that uses the same key — replays are flagged with the `Idempotent-Replayed: true` response header and do **not** consume quota. Reusing the key with a different request body or query parameters returns `409 Conflict` with code `idempotency_key_conflict`. Keys are scoped per API key (or per IP for anonymous calls), so two callers can use the same opaque value without collision. + * @example 8c3d7b9e-1f2a-4c5d-9e8f-7a6b5c4d3e2f + */ + "Idempotency-Key"?: components["parameters"]["IdempotencyKey"]; + }; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Per-die rolls, modifier, and total. */ + 200: { + headers: { + "Server-Timing": components["headers"]["ServerTiming"]; + [name: string]: unknown; + }; + content: { + /** + * @example { + * "outcome": { + * "notation": "3d6+2", + * "rolls": [ + * 4, + * 6, + * 3 + * ], + * "modifier": 2, + * "total": 15 + * }, + * "clientSeed": "tabletop", + * "serverHash": "9f86d081884c7d65...", + * "nonce": 0, + * "cursor": 0, + * "count": 3, + * "sides": 6, + * "modifier": 2, + * "endpoint": "dice", + * "created": 1716566400000 + * } + */ + "application/json": components["schemas"]["DiceOutcome"]; + }; + }; + 400: components["responses"]["BadRequest"]; + 401: components["responses"]["InvalidApiKey"]; + 409: components["responses"]["IdempotencyConflict"]; + 429: components["responses"]["RateLimited"]; + 500: components["responses"]["ServerError"]; + }; + }; + getFloats: { + parameters: { + query?: { + /** @description Your seed for this generation. Combined with the server seed to produce provably fair output. Defaults to the literal string `"test"` when omitted, so anonymous demos work out of the box — production callers should always pass a stable, caller-owned value (your account id, a session id, etc.) to keep their own deterministic seed history. */ + clientSeed?: components["parameters"]["ClientSeed"]; + /** @description Number of values to generate (1-100). */ + count?: components["parameters"]["Count"]; + }; + header?: { + /** + * @description Optional opaque string (≤255 chars). When supplied on any random-generating endpoint (`/api/floats`, `/api/ints`, `/api/shuffle`, `/api/pick`, `/api/bytes`, `/api/dice`, `/api/gaussian`, `/api/batch`), the server stores the response for 24 hours and returns the **same** status, body, and `Content-Type` for any retry that uses the same key — replays are flagged with the `Idempotent-Replayed: true` response header and do **not** consume quota. Reusing the key with a different request body or query parameters returns `409 Conflict` with code `idempotency_key_conflict`. Keys are scoped per API key (or per IP for anonymous calls), so two callers can use the same opaque value without collision. + * @example 8c3d7b9e-1f2a-4c5d-9e8f-7a6b5c4d3e2f + */ + "Idempotency-Key"?: components["parameters"]["IdempotencyKey"]; + }; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description A batch of random floats and the associated server hash. */ + 200: { + headers: { + "Server-Timing": components["headers"]["ServerTiming"]; + [name: string]: unknown; + }; + content: { + /** + * @example { + * "outcome": [ + * 0.4823, + * 0.1175, + * 0.9034, + * 0.5567, + * 0.2218 + * ], + * "clientSeed": "my-app", + * "serverHash": "9f86d081884c7d65...", + * "nonce": 0, + * "cursor": 5, + * "count": 5, + * "endpoint": "floats", + * "created": 1716566400000, + * "shortId": "k7Qm2A9bXz", + * "permalink": "https://provable.io/o/k7Qm2A9bXz" + * } + */ + "application/json": components["schemas"]["FloatOutcome"]; + }; + }; + 400: components["responses"]["BadRequest"]; + 401: components["responses"]["InvalidApiKey"]; + 409: components["responses"]["IdempotencyConflict"]; + 429: components["responses"]["RateLimited"]; + 500: components["responses"]["ServerError"]; + }; + }; + gaussian: { + parameters: { + query?: { + /** @description Your seed for this generation. Combined with the server seed to produce provably fair output. Defaults to the literal string `"test"` when omitted, so anonymous demos work out of the box — production callers should always pass a stable, caller-owned value (your account id, a session id, etc.) to keep their own deterministic seed history. */ + clientSeed?: components["parameters"]["ClientSeed"]; + /** @description Number of values to generate (1-100). */ + count?: components["parameters"]["Count"]; + /** @description Which distribution to sample. */ + distribution?: "normal" | "exponential" | "poisson"; + /** @description Mean (μ) for `normal`. Defaults to 0. */ + mean?: number; + /** @description Standard deviation (σ) for `normal`. Must be > 0. Defaults to 1. */ + stddev?: number; + /** @description Rate parameter (λ) for `exponential` (> 0) or `poisson` (> 0, ≤ 100). Defaults to 1. */ + lambda?: number; + }; + header?: { + /** + * @description Optional opaque string (≤255 chars). When supplied on any random-generating endpoint (`/api/floats`, `/api/ints`, `/api/shuffle`, `/api/pick`, `/api/bytes`, `/api/dice`, `/api/gaussian`, `/api/batch`), the server stores the response for 24 hours and returns the **same** status, body, and `Content-Type` for any retry that uses the same key — replays are flagged with the `Idempotent-Replayed: true` response header and do **not** consume quota. Reusing the key with a different request body or query parameters returns `409 Conflict` with code `idempotency_key_conflict`. Keys are scoped per API key (or per IP for anonymous calls), so two callers can use the same opaque value without collision. + * @example 8c3d7b9e-1f2a-4c5d-9e8f-7a6b5c4d3e2f + */ + "Idempotency-Key"?: components["parameters"]["IdempotencyKey"]; + }; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description An array of samples from the requested distribution. */ + 200: { + headers: { + "Server-Timing": components["headers"]["ServerTiming"]; + [name: string]: unknown; + }; + content: { + /** + * @example { + * "outcome": [ + * -0.42, + * 1.05, + * 0.18, + * -1.21, + * 0.66 + * ], + * "clientSeed": "stats", + * "serverHash": "9f86d081884c7d65...", + * "nonce": 0, + * "cursor": 0, + * "count": 5, + * "distribution": "normal", + * "mean": 0, + * "stddev": 1, + * "endpoint": "gaussian", + * "created": 1716566400000 + * } + */ + "application/json": components["schemas"]["GaussianOutcome"]; + }; + }; + 400: components["responses"]["BadRequest"]; + 401: components["responses"]["InvalidApiKey"]; + 409: components["responses"]["IdempotencyConflict"]; + 429: components["responses"]["RateLimited"]; + 500: components["responses"]["ServerError"]; + }; + }; + getHealth: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Service is healthy. */ + 200: { + headers: { + "Server-Timing": components["headers"]["ServerTiming"]; + [name: string]: unknown; + }; + content: { + /** + * @example { + * "status": "ok", + * "db": "ok", + * "version": "1.0.0", + * "uptime": 12345, + * "timestamp": "2026-05-24T12:00:00.000Z" + * } + */ + "application/json": components["schemas"]["Health"]; + }; + }; + 401: components["responses"]["InvalidApiKey"]; + /** @description Service is degraded or shutting down. */ + 503: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Health"]; + }; + }; + }; + }; + getPublicMetrics: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Current metrics, with unavailable aggregate values represented as null when the database cannot be reached. */ + 200: { + headers: { + "Server-Timing": components["headers"]["ServerTiming"]; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["PublicMetrics"]; + }; + }; + 401: components["responses"]["InvalidApiKey"]; + 429: components["responses"]["RateLimited"]; + }; + }; + incrementCursor: { + parameters: { + query?: { + /** @description Your seed for this generation. Combined with the server seed to produce provably fair output. Defaults to the literal string `"test"` when omitted, so anonymous demos work out of the box — production callers should always pass a stable, caller-owned value (your account id, a session id, etc.) to keep their own deterministic seed history. */ + clientSeed?: components["parameters"]["ClientSeed"]; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description The new cursor/nonce pair for this seed, with the current `serverHash` echoed back. */ + 200: { + headers: { + "Server-Timing": components["headers"]["ServerTiming"]; + [name: string]: unknown; + }; + content: { + /** + * @example { + * "clientSeed": "my-app", + * "cursor": 6, + * "nonce": 0, + * "serverHash": "9f86d081884c7d65...", + * "created": 1716566400000 + * } + */ + "application/json": { + clientSeed: string; + cursor: number; + nonce: number; + serverHash: string; + /** + * Format: int64 + * @description Unix ms when the cursor was bumped. + */ + created: number; + }; + }; + }; + 400: components["responses"]["BadRequest"]; + 401: components["responses"]["InvalidApiKey"]; + 429: components["responses"]["RateLimited"]; + 500: components["responses"]["ServerError"]; + }; + }; + getInts: { + parameters: { + query?: { + /** @description Your seed for this generation. Combined with the server seed to produce provably fair output. Defaults to the literal string `"test"` when omitted, so anonymous demos work out of the box — production callers should always pass a stable, caller-owned value (your account id, a session id, etc.) to keep their own deterministic seed history. */ + clientSeed?: components["parameters"]["ClientSeed"]; + /** @description Number of values to generate (1-100). */ + count?: components["parameters"]["Count"]; + /** @description Minimum value (inclusive). */ + min?: number; + /** @description Maximum value (inclusive). The range max - min + 1 may be at most 2^32 (4294967296). */ + max?: number; + /** @description Reserved JSON object (up to 512 characters) used by supported Provable.io browser tools. API clients normally omit this. */ + toolMeta?: components["parameters"]["ToolMeta"]; + }; + header?: { + /** + * @description Optional opaque string (≤255 chars). When supplied on any random-generating endpoint (`/api/floats`, `/api/ints`, `/api/shuffle`, `/api/pick`, `/api/bytes`, `/api/dice`, `/api/gaussian`, `/api/batch`), the server stores the response for 24 hours and returns the **same** status, body, and `Content-Type` for any retry that uses the same key — replays are flagged with the `Idempotent-Replayed: true` response header and do **not** consume quota. Reusing the key with a different request body or query parameters returns `409 Conflict` with code `idempotency_key_conflict`. Keys are scoped per API key (or per IP for anonymous calls), so two callers can use the same opaque value without collision. + * @example 8c3d7b9e-1f2a-4c5d-9e8f-7a6b5c4d3e2f + */ + "Idempotency-Key"?: components["parameters"]["IdempotencyKey"]; + }; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description A batch of random integers and the associated server hash. */ + 200: { + headers: { + "Server-Timing": components["headers"]["ServerTiming"]; + [name: string]: unknown; + }; + content: { + /** + * @example { + * "outcome": [ + * 42, + * 87, + * 13, + * 65, + * 29 + * ], + * "clientSeed": "my-app", + * "serverHash": "9f86d081884c7d65...", + * "nonce": 0, + * "cursor": 5, + * "count": 5, + * "min": 1, + * "max": 100, + * "endpoint": "ints", + * "created": 1716566400000, + * "shortId": "k7Qm2A9bXz", + * "permalink": "https://provable.io/o/k7Qm2A9bXz" + * } + */ + "application/json": components["schemas"]["IntOutcome"]; + }; + }; + 400: components["responses"]["BadRequest"]; + 401: components["responses"]["InvalidApiKey"]; + 409: components["responses"]["IdempotencyConflict"]; + 429: components["responses"]["RateLimited"]; + 500: components["responses"]["ServerError"]; + }; + }; + listOutcomes: { + parameters: { + query?: { + /** @description Your seed for this generation. Combined with the server seed to produce provably fair output. Defaults to the literal string `"test"` when omitted, so anonymous demos work out of the box — production callers should always pass a stable, caller-owned value (your account id, a session id, etc.) to keep their own deterministic seed history. */ + clientSeed?: components["parameters"]["ClientSeed"]; + /** @description Max outcomes to return (1-1000, default 1000). */ + limit?: number; + /** @description Keyset cursor `cursor:nonce` from the last outcome of the previous page; returns strictly older outcomes. */ + before?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description List of outcomes for the given client seed. */ + 200: { + headers: { + "Server-Timing": components["headers"]["ServerTiming"]; + [name: string]: unknown; + }; + content: { + /** + * @example [ + * { + * "outcome": [ + * 42, + * 87, + * 13, + * 65, + * 29 + * ], + * "clientSeed": "my-app", + * "serverHash": "9f86d081884c7d65...", + * "nonce": 0, + * "cursor": 5, + * "endpoint": "ints", + * "created": 1716566400000, + * "shortId": "k7Qm2A9bXz", + * "permalink": "https://provable.io/o/k7Qm2A9bXz" + * } + * ] + */ + "application/json": components["schemas"]["PublicOutcome"][]; + }; + }; + 400: components["responses"]["BadRequest"]; + 401: components["responses"]["InvalidApiKey"]; + 429: components["responses"]["RateLimited"]; + 500: components["responses"]["ServerError"]; + }; + }; + listMerkleRoots: { + parameters: { + query?: { + /** @description Maximum number of roots to return (1-90). */ + limit?: number; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description List of recent daily roots. */ + 200: { + headers: { + "Server-Timing": components["headers"]["ServerTiming"]; + [name: string]: unknown; + }; + content: { + /** + * @example { + * "roots": [ + * { + * "date": "2026-05-28", + * "root": "a3f1c2d4e5...e7", + * "leafCount": 14238, + * "treeHeight": 14, + * "publishedAt": 1716681900000 + * }, + * { + * "date": "2026-05-27", + * "root": "b7e2f4a1c9...3d", + * "leafCount": 13104, + * "treeHeight": 14, + * "publishedAt": 1716595500000 + * } + * ] + * } + */ + "application/json": { + roots?: components["schemas"]["MerkleRoot"][]; + }; + }; + }; + 401: components["responses"]["InvalidApiKey"]; + }; + }; + getMerkleRoot: { + parameters: { + query?: never; + header?: never; + path: { + /** + * @description UTC date in `YYYY-MM-DD` form. + * @example 2026-05-23 + */ + date: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Published root for that date. */ + 200: { + headers: { + "Server-Timing": components["headers"]["ServerTiming"]; + [name: string]: unknown; + }; + content: { + /** + * @example { + * "date": "2026-05-23", + * "root": "a3f1c2...e7", + * "leafCount": 14238, + * "treeHeight": 14, + * "publishedAt": 1716595500000 + * } + */ + "application/json": components["schemas"]["MerkleRoot"]; + }; + }; + 400: components["responses"]["BadRequest"]; + 401: components["responses"]["InvalidApiKey"]; + /** @description No root published for this date yet. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; + getMerkleProof: { + parameters: { + query?: never; + header?: never; + path: { + /** + * @description UTC date in `YYYY-MM-DD` form. + * @example 2026-05-23 + */ + date: string; + /** + * @description The outcome's shortId (unique, preferred) or `clientSeed:cursor:nonce`. The triple can repeat across API-key chains; it then resolves to the first match. + * @example my-app:5:0 + */ + outcomeId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Inclusion proof. */ + 200: { + headers: { + "Server-Timing": components["headers"]["ServerTiming"]; + [name: string]: unknown; + }; + content: { + /** + * @example { + * "date": "2026-05-23", + * "outcomeId": "my-app:5:0", + * "leaf": { + * "outcomeId": "my-app:5:0", + * "serverHash": "9f86d081884c7d65...", + * "clientSeed": "my-app", + * "timestamp": 1716566400000, + * "canonical": "my-app:5:0|9f86d081884c7d65...|my-app|1716566400000", + * "hash": "4d7e1b2c8a...f3" + * }, + * "index": 8123, + * "leafCount": 14238, + * "treeHeight": 14, + * "root": "a3f1c2d4e5...e7", + * "publishedAt": 1716595500000, + * "siblings": [ + * { + * "position": "right", + * "hash": "1a2b3c4d5e...90" + * }, + * { + * "position": "left", + * "hash": "6f7e8d9c0b...21" + * } + * ] + * } + */ + "application/json": components["schemas"]["MerkleProof"]; + }; + }; + 400: components["responses"]["BadRequest"]; + 401: components["responses"]["InvalidApiKey"]; + /** @description Root not published for that date, or outcome not in that day's tree. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; + getOutcome: { + parameters: { + query: { + /** @description Your seed for this generation. Combined with the server seed to produce provably fair output. Defaults to the literal string `"test"` when omitted, so anonymous demos work out of the box — production callers should always pass a stable, caller-owned value (your account id, a session id, etc.) to keep their own deterministic seed history. */ + clientSeed?: components["parameters"]["ClientSeed"]; + /** + * @description Cursor of the outcome to look up. + * @example 5 + */ + cursor: number; + /** + * @description Nonce of the outcome to look up. + * @example 0 + */ + nonce: number; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description The recorded outcome. */ + 200: { + headers: { + "Server-Timing": components["headers"]["ServerTiming"]; + [name: string]: unknown; + }; + content: { + /** + * @example { + * "outcome": [ + * 42, + * 7, + * 88, + * 13, + * 61 + * ], + * "clientSeed": "my-app", + * "serverHash": "9f86d081884c7d65...", + * "nonce": 0, + * "cursor": 5, + * "count": 5, + * "min": 1, + * "max": 100, + * "endpoint": "ints", + * "created": 1716566400000, + * "shortId": "k7Qm2A9bXz", + * "mode": "live", + * "permalink": "https://provable.io/o/k7Qm2A9bXz" + * } + */ + "application/json": components["schemas"]["PublicOutcome"]; + }; + }; + 400: components["responses"]["BadRequest"]; + 401: components["responses"]["InvalidApiKey"]; + 429: components["responses"]["RateLimited"]; + 500: components["responses"]["ServerError"]; + }; + }; + pickItem: { + parameters: { + query: { + /** @description Your seed for this generation. Combined with the server seed to produce provably fair output. Defaults to the literal string `"test"` when omitted, so anonymous demos work out of the box — production callers should always pass a stable, caller-owned value (your account id, a session id, etc.) to keep their own deterministic seed history. */ + clientSeed?: components["parameters"]["ClientSeed"]; + /** + * @description Items to choose from. Same encoding as `/api/shuffle`. 1-1000 entries. + * @example common,rare,legendary + */ + items: string | string[]; + /** + * @description Optional non-negative weights, one per item. Defaults to uniform. Must sum to a positive number. + * @example 70,25,5 + */ + weights?: string | number[]; + }; + header?: { + /** + * @description Optional opaque string (≤255 chars). When supplied on any random-generating endpoint (`/api/floats`, `/api/ints`, `/api/shuffle`, `/api/pick`, `/api/bytes`, `/api/dice`, `/api/gaussian`, `/api/batch`), the server stores the response for 24 hours and returns the **same** status, body, and `Content-Type` for any retry that uses the same key — replays are flagged with the `Idempotent-Replayed: true` response header and do **not** consume quota. Reusing the key with a different request body or query parameters returns `409 Conflict` with code `idempotency_key_conflict`. Keys are scoped per API key (or per IP for anonymous calls), so two callers can use the same opaque value without collision. + * @example 8c3d7b9e-1f2a-4c5d-9e8f-7a6b5c4d3e2f + */ + "Idempotency-Key"?: components["parameters"]["IdempotencyKey"]; + }; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description The picked item and its index. */ + 200: { + headers: { + "Server-Timing": components["headers"]["ServerTiming"]; + [name: string]: unknown; + }; + content: { + /** + * @example { + * "outcome": "legendary", + * "index": 2, + * "clientSeed": "loot-roll", + * "serverHash": "9f86d081884c7d65...", + * "nonce": 0, + * "cursor": 0, + * "count": 1, + * "weights": [ + * 70, + * 25, + * 5 + * ], + * "endpoint": "pick", + * "created": 1716566400000 + * } + */ + "application/json": components["schemas"]["PickOutcome"]; + }; + }; + 400: components["responses"]["BadRequest"]; + 401: components["responses"]["InvalidApiKey"]; + 409: components["responses"]["IdempotencyConflict"]; + 429: components["responses"]["RateLimited"]; + 500: components["responses"]["ServerError"]; + }; + }; + revealCommit: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + /** + * @example { + * "commitId": "8c3d7b9e-1f2a-4c5d-9e8f-7a6b5c4d3e2f", + * "clientSeed": "my-app", + * "endpoint": "ints", + * "params": { + * "count": 5, + * "min": 1, + * "max": 100 + * } + * } + */ + "application/json": components["schemas"]["RevealRequest"]; + }; + }; + responses: { + /** @description The outcome computed from the committed server seed and your client seed, plus the revealed server seed. */ + 200: { + headers: { + "Server-Timing": components["headers"]["ServerTiming"]; + [name: string]: unknown; + }; + content: { + /** + * @example { + * "outcome": [ + * 42, + * 87, + * 13, + * 65, + * 29 + * ], + * "clientSeed": "my-app", + * "serverHash": "9f86d081884c7d65...", + * "serverSeed": "b1946ac92492d2347c6235b4d2611184...", + * "nonce": 0, + * "cursor": 0, + * "count": 5, + * "min": 1, + * "max": 100, + * "endpoint": "ints", + * "commitId": "8c3d7b9e-1f2a-4c5d-9e8f-7a6b5c4d3e2f", + * "created": 1716566400000 + * } + */ + "application/json": components["schemas"]["RevealOutcome"]; + }; + }; + 400: components["responses"]["BadRequest"]; + 401: components["responses"]["InvalidApiKey"]; + /** @description The commit was created with a different API key (or anonymously). Reveal with the key that created it. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "commit was created with a different API key" + * } + */ + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Commit not found. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "commit not found or expired" + * } + */ + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Commit has already been revealed (single-use). */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "commit already revealed" + * } + */ + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Commit expired before being revealed. */ + 410: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "commit expired" + * } + */ + "application/json": components["schemas"]["Error"]; + }; + }; + 429: components["responses"]["RateLimited"]; + 500: components["responses"]["ServerError"]; + }; + }; + rotateServerSeed: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + /** + * @example { + * "clientSeed": "my-app" + * } + */ + "application/json": { + /** @description The client seed whose serverSeed should be revealed and rotated. */ + clientSeed: string; + }; + }; + }; + responses: { + /** @description Previous `serverSeed` revealed (verify by checking `sha256(revealed.serverSeed) === revealed.serverHash`) plus the new state. Future calls to `/api/floats`/`/api/ints` for this `clientSeed` will derive from `next.serverHash` at the `next.cursor` / `next.nonce` returned here. */ + 200: { + headers: { + "Server-Timing": components["headers"]["ServerTiming"]; + [name: string]: unknown; + }; + content: { + /** + * @example { + * "clientSeed": "my-app", + * "revealed": { + * "serverSeed": "b1946ac92492d2347c6235b4d2611184a3a6f3c1e5c1c4d8e6b7f1a2c3d4e5f6", + * "serverHash": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08", + * "cursor": 7, + * "nonce": 3 + * }, + * "next": { + * "serverHash": "a3b1c5d7e9f1a3b5c7d9e1f3a5b7c9d1e3f5a7b9c1d3e5f7a9b1c3d5e7f9a1b3", + * "cursor": 0, + * "nonce": 0, + * "rotatedAt": 1716566400000 + * } + * } + */ + "application/json": { + clientSeed: string; + revealed: { + /** @description The previous server seed, now revealed. `null` only on a freshly-created row that never carried one. */ + serverSeed: string | null; + serverHash: string | null; + cursor: number; + nonce: number; + }; + next: { + /** @description Hash of the freshly generated server seed. The new seed itself stays secret until the next rotate. */ + serverHash: string; + cursor: number; + nonce: number; + /** + * Format: int64 + * @description Unix ms at which the rotation was committed. + */ + rotatedAt: number; + }; + }; + }; + }; + 400: components["responses"]["BadRequest"]; + 401: components["responses"]["InvalidApiKey"]; + /** @description The calling key is a `pk_test_*` test key. Test mode has no live chain to rotate. */ + 403: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "rotate requires a live (pk_live_*) api key or anonymous call; test keys have no live chain", + * "code": "test_mode_forbidden" + * } + */ + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description No `seed_state` exists for the addressed chain yet (for authed calls: this api key's chain for this `clientSeed`; for anonymous calls: the anon chain for this `clientSeed`). Call `/api/floats` or `/api/ints` first. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "error": "no seed_state for this (api key, clientSeed) chain — generate an outcome first" + * } + */ + "application/json": components["schemas"]["Error"]; + }; + }; + 429: components["responses"]["RateLimited"]; + 500: components["responses"]["ServerError"]; + }; + }; + shuffleItems: { + parameters: { + query: { + /** @description Your seed for this generation. Combined with the server seed to produce provably fair output. Defaults to the literal string `"test"` when omitted, so anonymous demos work out of the box — production callers should always pass a stable, caller-owned value (your account id, a session id, etc.) to keep their own deterministic seed history. */ + clientSeed?: components["parameters"]["ClientSeed"]; + /** + * @description Items to shuffle. Pass a JSON array (`items=["a","b","c"]`), a comma-separated list (`items=a,b,c`), or repeat the parameter (`items=a&items=b&items=c`). 1-1000 entries. + * @example a,b,c,d + */ + items: string | string[]; + /** @description Reserved JSON object (up to 512 characters) used by supported Provable.io browser tools. API clients normally omit this. */ + toolMeta?: components["parameters"]["ToolMeta"]; + }; + header?: { + /** + * @description Optional opaque string (≤255 chars). When supplied on any random-generating endpoint (`/api/floats`, `/api/ints`, `/api/shuffle`, `/api/pick`, `/api/bytes`, `/api/dice`, `/api/gaussian`, `/api/batch`), the server stores the response for 24 hours and returns the **same** status, body, and `Content-Type` for any retry that uses the same key — replays are flagged with the `Idempotent-Replayed: true` response header and do **not** consume quota. Reusing the key with a different request body or query parameters returns `409 Conflict` with code `idempotency_key_conflict`. Keys are scoped per API key (or per IP for anonymous calls), so two callers can use the same opaque value without collision. + * @example 8c3d7b9e-1f2a-4c5d-9e8f-7a6b5c4d3e2f + */ + "Idempotency-Key"?: components["parameters"]["IdempotencyKey"]; + }; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description The shuffled array and the associated server hash. */ + 200: { + headers: { + "Server-Timing": components["headers"]["ServerTiming"]; + [name: string]: unknown; + }; + content: { + /** + * @example { + * "outcome": [ + * "c", + * "a", + * "d", + * "b" + * ], + * "clientSeed": "my-app", + * "serverHash": "9f86d081884c7d65...", + * "nonce": 0, + * "cursor": 0, + * "count": 4, + * "endpoint": "shuffle", + * "created": 1716566400000 + * } + */ + "application/json": components["schemas"]["ShuffleOutcome"]; + }; + }; + 400: components["responses"]["BadRequest"]; + 401: components["responses"]["InvalidApiKey"]; + 409: components["responses"]["IdempotencyConflict"]; + 429: components["responses"]["RateLimited"]; + 500: components["responses"]["ServerError"]; + }; + }; + streamOutcomes: { + parameters: { + query: { + /** @description Your seed for this generation. Combined with the server seed to produce provably fair output. Defaults to the literal string `"test"` when omitted, so anonymous demos work out of the box — production callers should always pass a stable, caller-owned value (your account id, a session id, etc.) to keep their own deterministic seed history. */ + clientSeed?: components["parameters"]["ClientSeed"]; + /** + * @description Which generator to stream. + * @example floats + */ + endpoint: "floats" | "ints" | "shuffle" | "pick" | "bytes" | "dice" | "gaussian"; + /** @description Milliseconds between outcomes. */ + intervalMs?: number; + /** + * @description Resume after a disconnect. Pass the most recent `outcomeId` you received (`clientSeed:cursor:nonce`); the server will only emit outcomes strictly after that point on the same `clientSeed`. Equivalent to the `Last-Event-ID` request header that `EventSource` sends automatically on auto-reconnect. + * @example my-app:42:0 + */ + lastEventId?: string; + }; + header?: { + /** + * @description Standard SSE resume header. Same semantics as the `lastEventId` query parameter — emit only outcomes strictly after this `clientSeed:cursor:nonce`. Sent automatically by `EventSource` on auto-reconnect. + * @example my-app:42:0 + */ + "Last-Event-ID"?: string; + }; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description An event stream. The body is `text/event-stream`, not JSON. Two event types are emitted: `outcome` (one per interval, `data:` is a JSON outcome with an extra `outcomeId` field) and `done` (terminal, `data:` describes the close `reason` — `max_duration` or `quota_exceeded`). */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example id: my-app:0:0 + * event: outcome + * data: {"outcome":[0.4823],"clientSeed":"my-app","serverHash":"9f86d0...","nonce":0,"cursor":0,"count":1,"endpoint":"floats","created":1716566400000,"outcomeId":"my-app:0:0"} + * + * : heartbeat 1716566415000 + * + * event: done + * data: {"reason":"max_duration","count":600,"durationMs":600000} + */ + "text/event-stream": string; + }; + }; + 400: components["responses"]["BadRequest"]; + 401: components["responses"]["InvalidApiKey"]; + 429: components["responses"]["RateLimited"]; + 500: components["responses"]["ServerError"]; + }; + }; + verifyServerHash: { + parameters: { + query: { + /** @description Your seed for this generation. Combined with the server seed to produce provably fair output. Defaults to the literal string `"test"` when omitted, so anonymous demos work out of the box — production callers should always pass a stable, caller-owned value (your account id, a session id, etc.) to keep their own deterministic seed history. */ + clientSeed?: components["parameters"]["ClientSeed"]; + /** + * @description The server hash returned with the original outcome. + * @example 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08 + */ + serverHash: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Verification result. Returns the literal `true` when either the current `seed_state` for this client seed still carries the supplied `serverHash` (a one-line fast path) **or** any recorded outcome under this client seed (e.g. a revealed commit-reveal outcome) was generated against that `serverHash`. Otherwise returns a `VerifyResult` object whose `verified` flag and `outcomes` array describe whether — and where — the (clientSeed, serverHash) pair appears in recorded history. */ + 200: { + headers: { + "Server-Timing": components["headers"]["ServerTiming"]; + [name: string]: unknown; + }; + content: { + /** + * @example { + * "verified": true, + * "clientSeed": "my-app", + * "serverHash": "9f86d081884c7d65...", + * "outcomes": [ + * { + * "shortId": "k7Qm2A9bXz", + * "permalink": "https://provable.io/o/k7Qm2A9bXz", + * "endpoint": "ints", + * "cursor": 5, + * "nonce": 0, + * "created": 1716566400000 + * } + * ] + * } + */ + "application/json": true | components["schemas"]["VerifyResult"]; + }; + }; + 400: components["responses"]["BadRequest"]; + 401: components["responses"]["InvalidApiKey"]; + 429: components["responses"]["RateLimited"]; + 500: components["responses"]["ServerError"]; + }; + }; + verifyShortId: { + parameters: { + query: { + /** + * @description The 4-32 character alphanumeric `shortId` for the outcome. + * @example k7Qm2A9bXz + */ + shortId: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Verification result for the outcome. */ + 200: { + headers: { + "Server-Timing": components["headers"]["ServerTiming"]; + [name: string]: unknown; + }; + content: { + /** + * @example { + * "verified": true, + * "reason": "Server seed hash on file matches the current state for this client seed.", + * "shortId": "k7Qm2A9bXz", + * "clientSeed": "my-app", + * "serverHash": "9f86d081884c7d65...", + * "cursor": 5, + * "nonce": 0, + * "endpoint": "ints", + * "created": 1716566400000, + * "permalink": "https://provable.io/o/k7Qm2A9bXz" + * } + */ + "application/json": { + verified: boolean; + reason: string; + shortId: string; + clientSeed?: string | null; + serverHash?: string; + cursor?: number | null; + nonce?: number | null; + endpoint?: string | null; + /** @description The original generated result. Its shape depends on endpoint. Null for password-tool records so the password cannot be reconstructed through this public lookup. */ + outcome?: (unknown[] | Record) | null; + count?: number | null; + min?: number | null; + max?: number | null; + notation?: string; + toolMeta?: { + [key: string]: unknown; + } | null; + created?: number | null; + /** @description True when password result material was removed from the public response. */ + redacted?: boolean; + /** Format: uri */ + permalink?: string; + }; + }; + }; + 400: components["responses"]["BadRequest"]; + 401: components["responses"]["InvalidApiKey"]; + 404: components["responses"]["BadRequest"]; + 429: components["responses"]["RateLimited"]; + 500: components["responses"]["ServerError"]; + }; + }; + getOutcomePermalink: { + parameters: { + query?: never; + header?: never; + path: { + /** + * @description The `shortId` returned with the outcome (~10 alphanumeric characters). + * @example k7Qm2A9bXz + */ + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description HTML permalink page rendering the outcome. */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "text/html": string; + }; + }; + /** @description No outcome exists with that short ID. */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "text/html": string; + }; + }; + }; + }; + getOutcomeOgImage: { + parameters: { + query?: never; + header?: never; + path: { + /** + * @description The `shortId` returned with the outcome (~10 alphanumeric characters). + * @example k7Qm2A9bXz + */ + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description 1200×630 PNG preview card (or the fallback `og-image.jpg` if the shortId is unknown or rendering fails). */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "image/png": string; + "image/jpeg": string; + }; + }; + }; + }; +} diff --git a/sdk/typescript/test/client.test.mjs b/sdk/typescript/test/client.test.mjs new file mode 100644 index 0000000..d93a8e2 --- /dev/null +++ b/sdk/typescript/test/client.test.mjs @@ -0,0 +1,120 @@ +// Smoke test for the built SDK. Uses a stub fetch so it doesn't touch the +// network. Run with: `npm test` from sdk/typescript (after `npm run build`). +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { ProvableClient } from "../dist/index.js"; + +function makeStubFetch(handler) { + return async (url, init) => handler(url, init); +} + +test("constructs the right URL, headers, and query string for getInts", async () => { + let captured; + const client = new ProvableClient({ + apiKey: "pk_test_abc", + baseUrl: "https://api.example.test", + fetch: makeStubFetch((url, init) => { + captured = { url, init }; + return new Response( + JSON.stringify({ outcome: [1, 2, 3], serverHash: "deadbeef" }), + { status: 200, headers: { "content-type": "application/json" } }, + ); + }), + }); + + const result = await client.getInts( + { clientSeed: "s1", count: 3, min: 1, max: 6 }, + { idempotencyKey: "idem-1" }, + ); + + assert.equal(result.error, null); + assert.deepEqual(result.data.outcome, [1, 2, 3]); + assert.equal( + captured.url, + "https://api.example.test/api/ints?clientSeed=s1&count=3&min=1&max=6", + ); + assert.equal(captured.init.method, "GET"); + assert.equal(captured.init.headers.get("x-api-key"), "pk_test_abc"); + assert.equal(captured.init.headers.get("idempotency-key"), "idem-1"); +}); + +test("returns the error payload on non-2xx responses without throwing", async () => { + const client = new ProvableClient({ + fetch: makeStubFetch( + () => + new Response( + JSON.stringify({ error: "nope", code: "rate_limited" }), + { status: 429, headers: { "content-type": "application/json" } }, + ), + ), + }); + + const result = await client.getFloats({ clientSeed: "s", count: 1 }); + assert.equal(result.data, null); + assert.equal(result.error.code, "rate_limited"); + assert.equal(result.response.status, 429); +}); + +test("substitutes path parameters for permalink lookup", async () => { + let capturedUrl; + const client = new ProvableClient({ + baseUrl: "https://api.example.test", + fetch: makeStubFetch((url) => { + capturedUrl = url; + return new Response("{}", { + status: 200, + headers: { "content-type": "application/json" }, + }); + }), + }); + + await client.getOutcomePermalink({ id: "abc 123" }); + assert.equal(capturedUrl, "https://api.example.test/o/abc%20123"); +}); + +test("sends bearer token when configured", async () => { + let capturedAuth; + const client = new ProvableClient({ + bearerToken: "pk_live_xyz", + fetch: makeStubFetch((_url, init) => { + capturedAuth = init.headers.get("authorization"); + return new Response("{}", { + status: 200, + headers: { "content-type": "application/json" }, + }); + }), + }); + + await client.getHealth(); + assert.equal(capturedAuth, "Bearer pk_live_xyz"); +}); + +test("POSTs JSON body for /api/batch", async () => { + let captured; + const client = new ProvableClient({ + fetch: makeStubFetch((url, init) => { + captured = { url, init }; + return new Response(JSON.stringify({ results: [] }), { + status: 200, + headers: { "content-type": "application/json" }, + }); + }), + }); + + await client.batch({ + draws: [{ kind: "ints", clientSeed: "s", count: 1, min: 1, max: 2 }], + }); + assert.equal(captured.init.method, "POST"); + assert.equal(captured.init.headers.get("content-type"), "application/json"); + const body = JSON.parse(captured.init.body); + assert.equal(body.draws.length, 1); +}); + +test("every JSON operation in openapi.json has a client method", async () => { + const { readFile } = await import("node:fs/promises"); + const spec = JSON.parse(await readFile(new URL("../../openapi.json", import.meta.url), "utf8")); + const src = await readFile(new URL("../src/index.ts", import.meta.url), "utf8"); + // og.png is an image for social cards, not an API call + const missing = Object.keys(spec.paths).filter((p) => !p.endsWith("/og.png") && !src.includes(`"${p}"`)); + assert.deepEqual(missing, []); +}); diff --git a/sdk/typescript/tsconfig.json b/sdk/typescript/tsconfig.json new file mode 100644 index 0000000..4d98279 --- /dev/null +++ b/sdk/typescript/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "target": "ES2020", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ES2020", "DOM"], + "outDir": "./dist", + "rootDir": "./src", + "declaration": true, + "declarationMap": true, + "sourceMap": true, + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "resolveJsonModule": true + }, + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist", "test"] +}