Extension File Storage
Extension file storage stores images in Chastify-managed R2 storage. There are two workflows:
| Workflow | Upload from | Ownership |
|---|---|---|
| Setup draft | The setup iframe through the parent bridge | The signed-in user and app, until a lock or template claims the file. |
| Runtime file | Your extension backend | The installed extension's app, session, and lock. |
Save the returned id, then obtain a fresh signedUrl when displaying the image. Signed URLs expire; extension-file:ID is a stored reference, not an image URL. Setup and runtime readers have different ownership checks, described below.
Relation To State Endpoints
Use state.* for small session-scoped JSON and file storage for binary images. Runtime iframes can read state with state.get; state writes require your backend and the credentials described in Developer API Overview.
For example, backend-written state can contain a runtime file ID:
{
"puzzleImageFileId": "64b000000000000000000001",
"lastOpenedTab": "images"
}
Do not store base64 images, browser blob: URLs, or signed URLs as durable state. The app's stateMaxBytes setting limits state writes; its default is 64 KiB. Putting an ID in state does not claim a staged file. Claiming requires a structured reference in saved extension configuration.
Storage Model
Records carry the app and uploading user, plus the applicable session, lock, template, purpose, and draft information. API file IDs are 24-character hexadecimal identifiers. A typical staged upload response is:
{
"file": {
"id": "64b000000000000000000001",
"signedUrl": "https://storage.example/extensions/image.webp?signature=EXAMPLE",
"publicUrl": "https://storage.example/extensions/image.webp?signature=EXAMPLE",
"urlExpiresAt": "2026-10-04T12:10:00.000Z",
"sizeBytes": 123456,
"originalName": "puzzle.jpg",
"mimeType": "image/webp",
"purpose": "puzzle-image",
"staged": true,
"draftId": "setup-draft-example",
"expiresAt": "2026-10-05T12:00:00.000Z",
"uploadedAt": "2026-10-04T12:00:00.000Z"
},
"stagedQuota": {
"bytesUsed": 123456,
"fileCount": 1,
"maxBytes": 10485760,
"remainingBytes": 10362304
}
}
The example URLs are placeholders. Runtime uploads return { "file": ... } without stagedQuota, with staged: false and no staged expiry. publicUrl is a compatibility alias for the same signed URL, not a permanent public link. Optional fields may be absent.
urlExpiresAt is the preview link's deadline. expiresAt is an unclaimed draft's deadline. They are different lifetimes.
Admin Gate And Quotas
Storage is disabled by default and requires configured R2 storage. Check capabilities instead of assuming the administrator has enabled uploads or retained these defaults:
| Setting | Default |
|---|---|
maxFileBytes | 10 MiB per incoming file |
maxBytesPerApp | 500 MiB of claimed files per app |
maxBytesPerSession | 50 MiB per extension session |
maxStagedBytesPerUserPerApp | 10 MiB of unexpired drafts per user and app |
allowedMimePrefixes | ["image/"] |
Uploads accept JPEG, PNG, GIF, and WebP, subject to the configured MIME prefixes. Supply an image filename and matching MIME type. These endpoints do not accept arbitrary binary files or SVG, even if the MIME setting is broadened.
Images are decoded, resized to fit within 1920 × 1920 without enlarging smaller images, and stored as WebP. The input pixel limit is 40 million. Do not depend on preserving original bytes, dimensions, or animation.
Upload checks compare the incoming file size with existing recorded usage, which counts processed bytes. Staging also checks app capacity; claiming checks app capacity again and session capacity when the claim includes a session ID. stagedQuota.remainingBytes is null when that quota is unlimited. Treat capabilities as a snapshot and handle rejected uploads even after a successful check.
Setup Staging Endpoints
Use staging for images selected before saving a lock or template, and for configuration edits on an existing lock. These routes act as the signed-in user through Chastify's parent page. The app must be active and released, or the user must be its owner or an assigned beta tester.
GET /api/extensions/apps/:appId/files/capabilities
The response contains:
enabled,provider: "r2", andr2Configured.supportsStagedSetupFiles: true.premiumBlockedandrequiredSubscriptionPlan("fan","supporter", ornull).settings, containing the storage settings above.stagedQuota, counting all this user's unexpired drafts for the app.
Capabilities and staging accept an optional lockId query parameter. The setup bridge supplies it when editing an existing lock. If the user is authorized for that lock, its participants can contribute subscription eligibility and the draft is bound to that lock. A premium extension can reject uploads with premium_required.
POST /api/extensions/apps/:appId/files/stage
Content-Type: multipart/form-data
Send file as the image, with optional purpose and draftId. The setup bridge supplies its current draft ID automatically. Use a short purpose such as puzzle-image; the server normalizes it to letters, digits, ., _, and -, with a 120-character maximum. Success returns HTTP 201 with file and stagedQuota as shown above.
Drafts expire 24 hours after upload. Save the actual lock or template before expiry; merely previewing the file or closing setup does not claim it.
GET /api/extensions/apps/:appId/files/staged?purpose=puzzle-image
GET /api/extensions/apps/:appId/files/:fileId
DELETE /api/extensions/apps/:appId/files/staged/:fileId
| Route | Result |
|---|---|
| List staged | { items, stagedQuota }; up to 100 unexpired drafts, newest first. Optional purpose and draftId filters; no pagination. |
| Get one | { file } for a file owned by this user and app. Can also refresh an already-claimed setup preview. |
| Delete staged | { ok: true, fileId, stagedQuota }; targets only files still staged. Missing or inaccessible files return file_not_found. |
Omit draftId when listing to restore available drafts across reloads or devices. Include it to narrow the list to one known draft. List query values allow up to 160 characters for draftId and 120 for purpose.
Claiming Staged Files Later
There is no browser-side claim endpoint. Submit a structured reference in the extension config that Chastify saves with the lock or template:
{
"storageDraftId": "setup-draft-example",
"images": [
{
"provider": "chastify_storage",
"fileId": "64b000000000000000000001",
"url": "extension-file:64b000000000000000000001",
"title": "Puzzle image"
}
]
}
Use context.storageDraftId from setup init. The scanner recognizes objects with provider: "chastify_storage" and a valid fileId (or legacy id). Canonical extension-file:ID references are also validated; a bare ID in arbitrary state does not claim a file.
Saving checks that a staged file belongs to the current user and app, has not expired, matches the setup draft ID, and matches its existing lock binding when present. After the parent is saved, accepted files are marked claimed and their draft expiry is removed. Interrupted claims are repaired by reconciliation. Existing claimed files must match an accepted lock, session, template, or server-verified source context. An uploader can reuse files from their saved personal/shared templates, or copy their lock's configured files into a template, after source ownership and references are checked. Later authorized edits retain existing configuration grants without transferring file ownership.
Personal and shared editor snapshots, including private snapshots of active locks, retain their uploaded extension images, including when reused to create multiple templates. Opening an authenticated snapshot share link grants the recipient permission to read and reuse only that snapshot's validated image references. Saved copies remain usable after the original template is changed or deleted. This permission does not allow recipients to delete the original upload. Images remain stored while any saved snapshot, template, or lock references them; merely opening a share link reserves the images for 24 hours while importing.
Opening existing snapshots or the owner-only template editor repairs missing image permissions when ownership or a previously validated copy proves access, without changing image IDs or requiring another upload. Older shared snapshots with no surviving proof of permission require opening a valid share link again. Legacy references alone do not establish access; new saves record proof for the exact authorized app/file pairs. Private active-lock snapshots do not reveal hidden images before the source session ends. Reads preserve unavailable references for later recovery; files already deleted from storage cannot be restored by this repair.
Recognized references retain the stable ID and an extension-file:ID URL; temporary signedUrl, publicUrl, and urlExpiresAt fields are stripped. The top-level storageDraftId is removed after being used to clean unused staged uploads from that draft. Handle save errors such as extension_file_expired, extension_file_not_found, extension_file_already_claimed, and extension_file_context_mismatch. Keep the draft on failure. Reopen an authorized source or shared snapshot to recover existing images where possible; missing objects require a replacement upload.
Saved setup images are available through runtime files.list and files.get for their authorized installation. Template files retain their original ownership and can be read by multiple installations whose saved configurations reference them. Access is checked against the app, lock, extension session, and server-recorded configuration grant; knowing an ID or signed URL is not authorization.
Older lock-bound setup files and shared-template references recover automatically. Ambiguous older saved snapshots without a grant need an authorized re-save of their extension settings or a targeted migration after checking their source; they are not granted access merely because an ID appears in client input.
Session Endpoints
The base path is /api/extensions/sessions/:sessionId/files. sessionId is the installed extension session ID, not the lock ID or app ID.
Reads require locks:read. Uploads and deletes require locks:write and backend authentication:
Authorization: Bearer YOUR_APP_SCOPED_DEVELOPER_KEY
x-chastify-main-token: CURRENT_MAIN_TOKEN_FROM_IFRAME_HASH
The key and launch token must identify the same app. The token must be valid for the requested session and lock, and its user must still hold the corresponding wearer or current keyholder role. Effective permissions are the intersection of the launch grant, current installation, current app, and Developer key scopes. A user-wide Developer API key or launch token alone is insufficient.
The extension must be enabled, its app active, and the lock session still usable. Ended sessions return lock_ended; these routes are not a permanent archive reader. See Developer API Overview for credential handling.
Capabilities
GET /api/extensions/sessions/:sessionId/files/capabilities
Returns enabled, provider: "r2", r2Configured, and settings. Requires locks:read. Runtime capabilities omit setup's stagedQuota and premium eligibility fields. enabled reports upload availability; disabling uploads does not itself prevent listing or refreshing existing files.
List Files
GET /api/extensions/sessions/:sessionId/files
Returns { "items": [...] } with fresh links for up to 500 files, newest first. Requires locks:read and the current app, extension session, and lock. There is no pagination; retain IDs if your workflow needs to address older files individually.
Get One File
GET /api/extensions/sessions/:sessionId/files/:fileId
Returns { "file": ... } with a fresh signed URL. Requires locks:read and the same app, session, and lock ownership as listing. Missing or out-of-context files return HTTP 404 with file_not_found. Possessing an ID or adding it to client-side state does not override those checks. Server-authorized references in saved configuration grant read access without transferring ownership.
Upload File
POST /api/extensions/sessions/:sessionId/files
Content-Type: multipart/form-data
Send the required file and optional purpose. Requires backend credentials and locks:write. Run this on your server, never in browser code:
curl "https://chastify.net/api/extensions/sessions/SESSION_ID/files" \
-H "Authorization: Bearer YOUR_APP_SCOPED_DEVELOPER_KEY" \
-H "x-chastify-main-token: CURRENT_MAIN_TOKEN_FROM_IFRAME_HASH" \
-F "purpose=puzzle-image" \
-F "[email protected];type=image/jpeg"
Let the multipart client generate the Content-Type boundary. Success returns HTTP 201 with { "file": ... }. Save the ID in your backend or backend-written extension state, then let the runtime iframe read it through the bridge.
| Error | What to check |
|---|---|
server_credentials_required, main_token_required, expired_main_token | Backend key and current launch token. Relaunch the extension when the token expires. |
insufficient_scope | Installed extension and Developer API key permissions. |
extension_file_storage_disabled, extension_file_storage_requires_r2 | Capabilities and administrator configuration. |
file_required, invalid_file_type, file_too_large | Multipart field, filename/MIME type, and incoming size. |
extension_app_storage_quota_exceeded, extension_session_storage_quota_exceeded | Current usage and available capacity. |
extension_staged_user_app_storage_quota_exceeded | Setup draft usage; remove unused drafts or wait for expiry. |
extension_file_upload_failed | Display the failure and allow retry; do not save a fabricated reference. |
Delete File
DELETE /api/extensions/sessions/:sessionId/files/:fileId
Requires backend credentials and locks:write. Files must belong to the same app, session, and lock. Confirmed deletion returns ok: true, fileId, deleted: true, physicalDeleteSkipped: false, and pending: false. An already-missing storage object counts as successful deletion. A storage failure fails the request and retains tracking for retry. A file reserved by an in-flight save returns deleted: false and pending: true.
If the active extension config contains the ID or extension-file:ID, deletion is skipped and HTTP 200 returns:
{
"ok": true,
"fileId": "64b000000000000000000001",
"deleted": false,
"physicalDeleteSkipped": true,
"reason": "file_referenced_by_active_extension_config"
}
Check these fields instead of treating every ok: true as physical deletion. Remove the reference through the supported configuration flow before deleting an otherwise eligible runtime file. This protection checks extension config, not references in state or your own database.
Iframe Bridge Actions
The Iframe Quickstart explains runtime initialization and the sample ChastifyBridgeClient. Its file helpers are:
const capabilities = await client.filesCapabilities();
const { items } = await client.filesList();
const { file } = await client.filesGet(savedFileId);
image.src = file.signedUrl;
Handle rejected requests and image-loading failures. Runtime supports only files.capabilities, files.list, and files.get; there is no runtime upload/delete action or filesUpload() helper.
Setup uses the separate chastify:ext:setup:req / chastify:ext:setup:resp channel. The runtime client does not implement it. Start from apps/extension/src/pages/SetupPage.tsx for init/config handling and add request/response handling if setup needs files.
| Setup action | Payload and behavior |
|---|---|
files.capabilities | Empty payload; checks setup upload eligibility. |
files.list / files.staged.list / files.listStaged | Optional draftId, purpose; lists unexpired drafts. |
files.get | { fileId }; refreshes a file owned by the signed-in user and app. |
files.upload | { file, filename?, purpose? } or { dataUrl, filename?, purpose? }; stages an image using the parent's current draft ID. |
files.delete | { fileId }; deletes a staged upload. |
For example, after validating setup init, use its nonce and the exact bridge.parentOrigin from the launch context:
window.parent.postMessage(
{
type: "chastify:ext:setup:req",
v: 1,
id: requestId,
nonce: setupInit.nonce,
action: "files.upload",
payload: {
file: selectedFile,
filename: selectedFile.name,
purpose: "puzzle-image",
},
},
parentOrigin,
);
selectedFile is a File in this example. A Blob is also supported: supply an image filename, since the fallback name has no image extension. dataUrl is an alternative for small generated images. The bridge has a 50 MiB payload ceiling; the server's upload limit still applies and is normally lower.
Listen for the matching response id, checking event.source === window.parent, expected origin, message type, and version. Success is { type: "chastify:ext:setup:resp", v: 1, id, ok: true, data }, where data contains the route response. Failure has ok: false and error: { code, message }. Allow for the parent's 60-second upload timeout and remove listeners when setup closes.
When editing an active extension, deleting an already-claimed file can return deleted: false, physicalDeleteSkipped: true, and reason active_claimed_file_not_deleted_before_save. This avoids deleting the active image before a replacement is saved; removing a preview is not proof of physical deletion.
Signed Links
Links have a default lifetime of 10 minutes. Keep the stable ID and refresh through the appropriate setup or runtime get endpoint. Prefer getting one file over listing everything to refresh a single image.
Treat signed URLs as temporary access links: do not expose them in public logs or treat possession as proof of identity, ownership, or task completion. Refreshing a link does not extend a draft's claim deadline. For file_not_found, check ownership or replace the unavailable image instead of retrying the old URL.
Cleanup Lifecycle
| Event | Behavior |
|---|---|
| Unclaimed setup upload | Expires after 24 hours. Production cleanup checks every 30 minutes; deletion is not immediate. |
| Save or replace configuration | Referenced files stay available. Reservations protect pending saves for 24 hours; unused files are reconciled afterwards. |
| Explicit setup/runtime delete | Requires ownership. Saved configuration references prevent deletion; storage errors retain retry work. |
| Delete a personal/shared/saved template | Records cleanup intent before removing the template. Files still referenced by installations or another saved template remain. |
| Delete a lock or account | Preserves durable extension-file cleanup work and references retained by other valid parents. |
Cleanup rechecks saved references immediately before physical deletion. Idempotent jobs retry storage failures with backoff, and periodic reconciliation recovers pending work even when queue admission failed. Ending or archiving a session is not equivalent to deleting its files.
Legacy claimed files without a reconciliation timestamp are not indiscriminately swept. To identify older orphans, inspect extension-scoped UserFile records whose owning lock/template is missing, then check every matching-app lock, personal template, saved snapshot and legacy URL reference. Missing ownership alone is not deletion authorization. Schedule only confirmed unreferenced records through the cleanup helper; this release does not run a production migration.
Performance Notes
- Check upload capabilities and keep source images within the advertised limits.
- Prefer
FileorBlobover base64dataUrlto reduce browser memory use. - Retain IDs and refresh links when needed instead of polling entire lists.
- Allow for processing/network time, prevent duplicate submissions, and show upload/save errors separately.
Security Notes
- Keep the Developer API key on your backend. Send the current launch token only to the backend you control.
- Validate bridge message source, origin, version, nonce where supplied, and response correlation IDs.
- Use server-side checks for workflows dependent on uploaded images; a URL or file ID alone is not completion evidence.
- Request only needed scopes and respect app/session/lock ownership. Setup access is tied to the uploading user.
- Share image links only with the intended audience; signed links and cleanup are not a substitute for your application's privacy requirements.
Direct Routes vs Bridge
Use the runtime bridge for reads and the setup bridge for staged configuration uploads. The parent keeps the user's Chastify authentication outside the iframe. Use direct runtime routes from your backend with the app-scoped key and current launch token for uploads, deletes, and other mutations.
Continue with Developer API Overview and Iframe Quickstart for browser/backend responsibilities and initialization.