Protect images your users upload
When users upload images to your service, your server holds the file, not a public URL. Send the file itself to SASHA, attach a Record that says where the image may appear, and store the protected image with its SignatureID when the job completes.
Before you start
- A Client ID and Client Secret, from Get access.
- For REST, a Callback Secret and a public HTTPS endpoint for callbacks, as Set up callback notifications describes.
- For gRPC, the client code generated in Step 1 of the quickstart.
- A JPEG, PNG or WebP image within the supported sizes.
Step 1: Upload the image
Send the file with an embed request. On REST it is a multipart/form-data request to POST /signature/embed; on gRPC it is the client-streaming RPC EmbedSignatureFromData. This example attaches a Record that allows the image only on your own site, so the Signature never exists without its Record.
- REST
- gRPC
Write the Record to a file:
cat > record.json <<'EOF'
{
"share_state": "restricted",
"allowed_publish_urls": ["your-app.example.com"],
"byline": "Photo by Jane Doe"
}
EOF
Then send the form. It has the file in the media field, with its MIME type as the part's content type, your endpoint in callback_url, and the Record as a JSON text field in record. Replace <access-token> with a token from POST /oauth/token:
curl https://partner.api.sasha.eu/signature/embed \
-H "Authorization: Bearer <access-token>" \
-F "media=@photo.jpg;type=image/jpeg" \
-F "callback_url=https://your-app.example.com/callbacks/sasha-job-update" \
-F "record=<record.json;type=application/json"
{
"job": {
"job_id": "7c1e2d4f-9a3b-4c5d-8e6f-0a1b2c3d4e5f",
"type": "embed-signature",
"status": "pending",
"created_at": "2026-10-16T09:00:00Z",
"updated_at": "2026-10-16T09:00:00Z"
}
}
Store the job_id with the upload in your own database. A 400 names every field that is wrong, and no job is created; Error handling lists the codes.
A record form field holds at most 2000 bytes. Send a longer Record with PUT /signature/{signature_id}/record after the embed, as Step 4 shows.
Send the file in chunks. The first message carries the MIME type and the Record, and every message carries the next part of the file. This sample sends 64 KiB chunks. SASHA refuses an upload over the size and chunk limits with INVALID_ARGUMENT, and no job is created. Save this as protect-upload.js in the quickstart folder, and run it with SASHA_CLIENT_ID and SASHA_CLIENT_SECRET set:
import { readFile, writeFile } from "node:fs/promises";
import { createClient } from "@connectrpc/connect";
import { createGrpcTransport } from "@connectrpc/connect-node";
import { PartnerAPI } from "./gen/sasha/partner-api/v1/partner_api_pb.js";
import { Job_Status } from "./gen/sasha/partner-api/v1/job_pb.js";
import { ShareState } from "./gen/sasha/common/public/share_state_pb.js";
const CHUNK_SIZE = 64 * 1024;
const client = createClient(
PartnerAPI,
createGrpcTransport({ baseUrl: "https://partner.api.sasha.eu" })
);
const { accessToken } = await client.authenticateWithClientCredential({
clientId: process.env.SASHA_CLIENT_ID,
clientSecret: process.env.SASHA_CLIENT_SECRET,
});
const callOptions = { headers: { Authorization: `Bearer ${accessToken}` } };
// Yields the upload as a stream of messages. Only the first one carries the
// MIME type and the Record.
async function* uploadMessages(data, mediaMimeType, record) {
for (let offset = 0; offset < data.length; offset += CHUNK_SIZE) {
const mediaDataChunk = data.subarray(offset, offset + CHUNK_SIZE);
yield offset === 0
? { mediaDataChunk, mediaMimeType, record }
: { mediaDataChunk };
}
}
const image = await readFile("photo.jpg");
const record = {
shareState: ShareState.RESTRICTED,
allowedPublishUrls: ["your-app.example.com"],
byline: "Photo by Jane Doe",
};
const { job } = await client.embedSignatureFromData(
uploadMessages(image, "image/jpeg", record),
callOptions
);
console.log("Job ID:", job.jobId);
The response holds the new job, with status STATUS_PENDING. An INVALID_ARGUMENT names every field of the Record that is wrong, and no job is created.
Step 2: Receive the finished job
- REST
- gRPC
SASHA posts the finished job to your callback_url. This endpoint checks the Callback Payload Signature, answers at once, then downloads the protected image and records the SignatureID. Run it with SASHA_CALLBACK_SECRET set to your hex Callback Secret:
import crypto from "node:crypto";
import { appendFile, mkdir, writeFile } from "node:fs/promises";
import express from "express";
const callbackSecret = Buffer.from(process.env.SASHA_CALLBACK_SECRET, "hex");
const app = express();
app.set("trust proxy", 1);
const isSignedBySasha = (req) => {
const url = `${req.protocol}://${req.get("host")}${req.path}`;
const expected = crypto
.createHmac("sha256", callbackSecret)
.update(`${req.method}${url}${req.get("SASHA-Request-ID") ?? ""}`)
.update(req.body)
.digest();
const received = Buffer.from(req.get("SASHA-Request-Signature") ?? "", "hex");
return received.length === expected.length && crypto.timingSafeEqual(received, expected);
};
const storeResult = async (job) => {
if (job.status === "failed") {
await appendFile("failed-jobs.jsonl", JSON.stringify(job) + "\n");
return;
}
// The output URL expires one hour after the job completes.
const image = await fetch(job.output_url).then((r) => r.arrayBuffer());
await mkdir("protected", { recursive: true });
await writeFile(`protected/${job.job_id}.jpg`, Buffer.from(image));
await appendFile(
"signatures.jsonl",
JSON.stringify({ job_id: job.job_id, signature_id: job.signature_id }) + "\n"
);
};
app.post(
"/callbacks/sasha-job-update",
express.raw({ type: "application/json", limit: "1mb" }),
(req, res) => {
if (!Buffer.isBuffer(req.body) || !isSignedBySasha(req)) {
return res.status(401).send("Invalid signature");
}
res.status(200).send("OK");
storeResult(JSON.parse(req.body.toString("utf8"))).catch(console.error);
}
);
app.listen(3000);
The completed job carries output_url, output_url_expires_at, signature_id and creator_id. A real service stores the image and the SignatureID in its own storage and database rather than in local files, and ignores a repeat delivery of the same job_id, as Ignore a repeat delivery shows.
The gRPC API sends no callbacks. Follow the job with WatchJob, which closes the stream when the job finishes. Add this to the end of protect-upload.js:
let finished;
for await (const { job: update } of client.watchJob({ jobId: job.jobId }, callOptions)) {
if (update.status === Job_Status.COMPLETED || update.status === Job_Status.FAILED) {
finished = update;
}
}
if (!finished) {
throw new Error(`The watch of job ${job.jobId} ended early: call WatchJob again`);
}
if (finished.status === Job_Status.FAILED) {
throw new Error(`Job failed: ${finished.error?.code} ${finished.error?.message}`);
}
// The output URL expires one hour after the job completes.
const protectedImage = await fetch(finished.outputUrl).then((r) => r.arrayBuffer());
await writeFile(`${finished.jobId}.jpg`, Buffer.from(protectedImage));
console.log("SignatureID:", finished.signatureId.value.toString());
If the job failed, its error.code says why. Ask the user for another image unless the code is internal, the one code worth a new job; Error handling lists them.
Step 3: Store the SignatureID
Keep the SignatureID with the protected image and the user's upload. It is the key to the Record from now on: you read and change the Record by SignatureID, and a lookup of the image returns the same SignatureID. On REST it is a string, because the number can exceed the integer range of JSON parsers; keep it as a string or a 64-bit integer.
Step 4: Change the Record later
When the user changes where the image may appear, replace the Record by SignatureID. Replace <signature-id> with the stored SignatureID:
curl -X PUT https://partner.api.sasha.eu/signature/<signature-id>/record \
-H "Authorization: Bearer <access-token>" \
-H "Content-Type: application/json" \
-d '{
"share_state": "unrestricted",
"byline": "Photo by Jane Doe"
}'
A 204 No Content confirms the write. Manage Records shows the gRPC call, partial updates and conditional writes.
See also
- How SASHA works: what the job returns
- Records: what each Record field means
- Set up callback notifications: delivery, retries and the signature
- Go live: the checks before you switch to production credentials