Shield Verify Beta

Shield API, version 1

Verification is open to everyone, with no key and no account. Issuing certificates requires an issuer key, granted to beta issuers on request.

Quickstart: sign from your server

Every call goes to https://shield.megga.sh and follows four rules.

Your key
Send Authorization: Bearer shld_live_…. The key comes from the one-time invitation link you received. Keep it on your server: never in a browser, a mobile app or a repository. Verification needs no key; a key raises your quota and changes nothing in the answer.
A User-Agent that names your client
For example User-Agent: acme-studio/1.4 (+https://acme.example). The edge refuses Python's default Python-urllib/3.x with Cloudflare error 1010, before the request reaches the API.
The whole body, with its length
Uploads are multipart/form-data sent with a Content-Length header. A chunked upload is refused with 411. curl, requests, httpx and fetch with a FormData body send the length; a streamed body does not.
One Idempotency-Key per image
Generate one (a UUID; at most 255 characters) and send it again on every retry of that image. For 24 hours, the same key with the same file and declaration returns the first response again, with Idempotent-Replay: true, instead of issuing a second certificate. The same key with a different file or declaration is refused with 409. If your own process can restart between two attempts, store the key with the job.

POST /v1/sign takes two parts. file is the image; the extension of its file name sets the format and must match the bytes: .png, .jpg or .jpeg, .webp, .tif or .tiff. Video and audio have their own formats and their own conditions, below. declaration is JSON: how the image was made and which markings you ask for (IssuanceDeclaration in the reference). The answer is 201 with the certificate and asset.url, where the signed file waits for you until asset.expires_at, 24 hours later. Publish that file, not your original: the signature and the watermark are in its bytes. The certificate itself does not expire.

POST /v1/verify takes the file as multipart/form-data only. Verifying by address, the JSON form {"url": "…"} listed in the reference, is planned and not served yet: this deployment answers it 400, so fetch the file yourself and send its bytes.

The answer names a verdict and reports each layer. derived_from_certified means the metadata is gone and the watermark and the fingerprint lead to one certificate: it says where the picture comes from, not that it is unchanged, which only an intact signature proves. The perceptual layer says how strong a match is as a strength level, strong, moderate, weak or none, the same answer for every caller.

curl

BASE=https://shield.megga.sh
UA="acme-studio/1.4 (+https://acme.example)"   # name your client
# export SHIELD_KEY=shld_live_…                  # from your secret store

# One Idempotency-Key per image, reused on every retry of that image.
IDEMPOTENCY_KEY=$(uuidgen)

# Sign. --retry waits out 429 and 503 as Retry-After says, with the same key.
curl --fail-with-body --retry 4 --retry-max-time 60 \
     -A "$UA" \
     -H "Authorization: Bearer $SHIELD_KEY" \
     -H "Idempotency-Key: $IDEMPOTENCY_KEY" \
     -F file=@image.png \
     -F 'declaration={"creation":{"kind":"ai_generated","digital_source_type":"http://cv.iptc.org/newscodes/digitalsourcetype/trainedAlgorithmicMedia"},"disclosure":{"marking":["signed_metadata","watermark"]}}' \
     -o result.json \
     "$BASE/v1/sign"

# The signed file. Publish it instead of your original, and fetch it before
# asset.expires_at (24 hours). The certificate itself does not expire.
curl --fail -A "$UA" -o image.signed.png "$(jq -r .asset.url result.json)"
jq -r .certificate.certificate_id result.json

# Verify. Multipart only; no key needed (a key raises your quota, nothing else).
curl --fail-with-body --retry 4 --retry-max-time 60 \
     -A "$UA" -F file=@image.signed.png -o verdict.json "$BASE/v1/verify"
jq -r .verdict verdict.json

Python

# pip install requests
import json
import os
import time
import uuid

import requests

BASE = "https://shield.megga.sh"
MAX_WAIT = 60  # seconds; a longer Retry-After means a daily quota is spent

session = requests.Session()
session.headers.update({
    "Authorization": f"Bearer {os.environ['SHIELD_KEY']}",  # shld_live_…
    "User-Agent": "acme-studio/1.4 (+https://acme.example)",  # name your client
})

DECLARATION = {
    "creation": {
        "kind": "ai_generated",
        "digital_source_type": "http://cv.iptc.org/newscodes/digitalsourcetype/trainedAlgorithmicMedia",
    },
    "disclosure": {"marking": ["signed_metadata", "watermark"]},
}


class ShieldError(Exception):
    pass


def post(path, files, data=None, idempotency_key=None, attempts=5):
    headers = {"Idempotency-Key": idempotency_key} if idempotency_key else {}
    for attempt in range(1, attempts + 1):
        try:
            r = session.post(BASE + path, files=files, data=data, headers=headers, timeout=120)
        except (requests.ConnectionError, requests.Timeout):
            if attempt == attempts:
                raise
            time.sleep(2 ** attempt)  # same key: a retry cannot sign twice
            continue
        if r.ok:
            return r
        problem = r.json() if "problem+json" in r.headers.get("Content-Type", "") else {}
        wait = int(r.headers.get("Retry-After", "0"))
        retryable = r.status_code in (429, 503) \
            or problem.get("type", "").endswith("/idempotency-in-progress")
        if retryable and attempt < attempts and wait <= MAX_WAIT:
            time.sleep(wait or 2 ** attempt)
            continue
        raise ShieldError(f"{r.status_code} {problem.get('type', '')}: "
                          f"{problem.get('detail', r.text[:200])}")


def sign(path, declaration=DECLARATION):
    """Sign one image. Returns (certificate id, signed bytes to publish)."""
    with open(path, "rb") as f:
        image = f.read()  # bytes, not the file object, so a retry sends them again
    result = post(
        "/v1/sign",
        files={"file": (os.path.basename(path), image)},  # the extension sets the format
        data={"declaration": json.dumps(declaration)},
        idempotency_key=str(uuid.uuid4()),  # one per image, the same on every retry
    ).json()
    signed = session.get(result["asset"]["url"], timeout=120)  # before asset.expires_at
    signed.raise_for_status()
    return result["certificate"]["certificate_id"], signed.content


def verify(path):
    with open(path, "rb") as f:
        image = f.read()
    return post("/v1/verify", files={"file": (os.path.basename(path), image)}).json()


if __name__ == "__main__":
    certificate_id, signed = sign("image.png")
    with open("image.signed.png", "wb") as f:
        f.write(signed)
    print(certificate_id, verify("image.signed.png")["verdict"])

TypeScript

// Node 18 or later: fetch, FormData and Blob are built in.
import { randomUUID } from "node:crypto";
import { readFile, writeFile } from "node:fs/promises";
import { basename } from "node:path";

const BASE = "https://shield.megga.sh";
const MAX_WAIT = 60; // seconds; a longer Retry-After means a daily quota is spent
const HEADERS = {
  Authorization: `Bearer ${process.env.SHIELD_KEY}`, // shld_live_…
  "User-Agent": "acme-studio/1.4 (+https://acme.example)", // name your client
};

const declaration = {
  creation: {
    kind: "ai_generated",
    digital_source_type: "http://cv.iptc.org/newscodes/digitalsourcetype/trainedAlgorithmicMedia",
  },
  disclosure: { marking: ["signed_metadata", "watermark"] },
};

const sleep = (seconds: number) => new Promise((done) => setTimeout(done, seconds * 1000));

async function post(path: string, form: FormData, idempotencyKey?: string, attempts = 5): Promise<Response> {
  const headers: Record<string, string> = { ...HEADERS };
  if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;
  for (let attempt = 1; ; attempt++) {
    let res: Response;
    try {
      res = await fetch(BASE + path, { method: "POST", headers, body: form });
    } catch (error) {
      if (attempt >= attempts) throw error;
      await sleep(2 ** attempt); // same key: a retry cannot sign twice
      continue;
    }
    if (res.ok) return res;
    const problem = res.headers.get("Content-Type")?.includes("problem+json")
      ? await res.json()
      : { detail: (await res.text()).slice(0, 200) };
    const wait = Number(res.headers.get("Retry-After") ?? 0);
    const retryable = res.status === 429 || res.status === 503
      || String(problem.type).endsWith("/idempotency-in-progress");
    if (retryable && attempt < attempts && wait <= MAX_WAIT) {
      await sleep(wait || 2 ** attempt);
      continue;
    }
    throw new Error(`${res.status} ${problem.type ?? ""}: ${problem.detail ?? ""}`);
  }
}

// Sign one image. Returns the certificate id and the signed bytes to publish.
export async function sign(path: string) {
  const form = new FormData();
  form.append("file", new Blob([new Uint8Array(await readFile(path))]), basename(path)); // the extension sets the format
  form.append("declaration", JSON.stringify(declaration));
  const result = await (await post("/v1/sign", form, randomUUID())).json(); // one key per image
  const signed = await fetch(result.asset.url, { headers: HEADERS }); // before asset.expires_at
  if (!signed.ok) throw new Error(`download failed: ${signed.status}`);
  return { certificateId: result.certificate.certificate_id, bytes: new Uint8Array(await signed.arrayBuffer()) };
}

export async function verify(path: string) {
  const form = new FormData();
  form.append("file", new Blob([new Uint8Array(await readFile(path))]), basename(path));
  return (await post("/v1/verify", form)).json();
}

const { certificateId, bytes } = await sign("image.png");
await writeFile("image.signed.png", bytes);
console.log(certificateId, (await verify("image.signed.png")).verdict);

Video and audio

The same two calls sign and verify video (.mp4, .mov) and audio (.m4a, .mp3, .wav, .flac), under the same 25 MB limit and with the same synchronous answer. Three things differ from an image.

They are opened per deployment, then per key
A deployment accepts images unless its operator has opened video or audio. For a kind it does not accept it answers 415 unsupported-media-type, to a signature and to a verification alike. Where a kind is accepted, verifying it needs no key. Signing it needs a key that was granted that kind: the role issue_video or issue_audio, next to issue. Without it the answer is 403 media-kind-not-granted, and your key still signs images. Ask the operator to grant the role: it is added to the key you hold, which does not change and carries it from its next request. To know before sending anything, call GET /v1/me with your key: media_kinds.accepted lists what the deployment takes, and media_kinds.signable what your key can sign on it.
They are signed, timestamped and registered, and nothing more
The watermark and the fingerprint are image techniques in this version. If your declaration asks for watermark or fingerprint_registry on a video or an audio file, the answer is still 201, and applied.skipped lists them with the reason not available for video in this version (or audio). The certificate states signed_metadata alone. Read applied: it is what was done.
A verification reports two layers as not applicable
soft_binding and perceptual answer applicable: false, with present: false and a note that starts not applicable to video in this version. They were not run. Branch on applicable, which is true on every layer of an image. A signed file verifies by its manifest and its exact hash; one changed byte of picture or sound gives modified. A file whose manifest was removed, or that was re-encoded, gives unknown: nothing in it leads back to its certificate. Publish the signed file as it is, and expect unknown from any copy a platform has transcoded.

The extension must say what the bytes are. A video sent as .m4a or .png, or an image sent as .mp4, is refused with 422, and detail names the extension to use. For an MP4-family file the tracks decide: a file with a picture track is a video, whatever brand it was written with.

Errors and retries

Errors are application/problem+json (RFC 9457). Branch on type, which ends with the name below; detail says what to change.

StatusTypeWhat happenedWhat to do
400malformed-request Not multipart/form-data, no file part, a declaration that is not a JSON object, or a verification sent as JSON. Fix the request. Do not resend it unchanged.
400unknown-field The declaration carries a field that creation or disclosure does not have, a misspelling for instance; fields names each one. It is refused rather than ignored, so that no declaration is silently not made. Fix the spelling against IssuanceDeclaration in the reference.
401unauthenticated The key is missing, mistyped or revoked. Check the key; ask for a new invitation if it was revoked.
403insufficient-scope The key cannot issue. Sign with an issuance key.
403media-kind-not-granted The key issues, and was not granted video or audio; required_role names the role. Ask the operator for a key that carries it. Do not resend unchanged.
409idempotency-conflict This Idempotency-Key was used in the last 24 hours with a different file or declaration. A different image needs a new key.
409idempotency-in-progress The first request with this key is still being served. Wait Retry-After (2 seconds) and resend: you receive its response.
411length-required No Content-Length: a chunked upload. Send the body in one piece, with its length.
413asset-too-large The request body is over 25 MB (26,214,400 bytes), for any kind of media, or the image has more than 50 megapixels. Send a smaller copy.
415unsupported-media-type A video or an audio file, sent to a deployment that does not accept that kind; accepted lists what it takes. Do not resend it here.
422unprocessable An extension outside the formats listed above, bytes that are not what the extension announces or that cannot be read, or a declaration that cannot be acted on; detail says which. Fix the file or the declaration. Do not resend it unchanged.
426tls-required Plain HTTP, or a TLS version older than 1.3. Use https:// with TLS 1.3.
429quota-exhausted Your quota for the current window is spent. Wait Retry-After seconds, then resend with the same key.
503overloaded, dependency-unavailable Every work slot is busy (Retry-After: 5), the service is restarting, or a service that issuance needs, such as the timestamp authority, is unreachable. Wait Retry-After seconds, or a few seconds when it is absent, then resend with the same Idempotency-Key.

Quotas

Verification is free and needs no account, within these published limits:

WhoVerifySign or register
No key, per client address100 a minute, 5 000 a dayNot allowed
Issuer key300 a minute, 20 000 a day60 a minute, 2 000 a day
Key registered for public-interest verification300 a minute, no daily ceiling60 a minute, 2 000 a day

Every metered answer carries your quota, for the window closest to running out. For an issuer key signing, for instance:

RateLimit: "burst";r=59;t=60
RateLimit-Policy: "burst";q=60;w=60, "daily";q=2000;w=86400

r is what remains and t the seconds the window still runs; each window in RateLimit-Policy allows q requests per w seconds. A 429 whose Retry-After runs to hours means a daily window is spent: queue the work rather than hold the request open. The examples above give up beyond 60 seconds.

Every answer also carries X-Request-Id. Send your own (8 to 128 letters, digits, ., _, : or -) to find a request in your logs and ours; quote it when you ask us about one.

Webhooks

A delivery is signed in Shield-Signature: t=<unix>,v1=<hex>, where v1 is an HMAC-SHA256 with your subscription secret over <t>.<body>: the timestamp, a full stop and the raw body as received. Recompute it over those bytes, compare in constant time, and refuse a delivery whose t is more than 5 minutes from your clock: signing the timestamp with the body is what makes a captured delivery useless later.

Redeploys

When a new version is deployed, the service is replaced and does not answer for a few seconds (about eight, measured). A GET or HEAD is held through it and does not notice. A POST gets a 503 with Retry-After: resend it after that delay with the same Idempotency-Key. If the first attempt was signed before the switch, the retry returns that certificate, with Idempotent-Replay: true, rather than a second one. The three examples above do exactly this.

Reference