Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

fix(security): delete media files from Cloudinary only when Twiligent created them

spacesdrive87b952de52e7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 77a5507..c94101a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -25,6 +25,7 @@ YouTube publishing, media tools for Claude, and the fixes from the second securi
- The Claude connection accepts only access tokens until connector sign-in is turned on, and refuses oversized requests (#152)
- The scheduler's run logs no longer include account ids or stored data from failed database calls (#152)
- Google tokens are stored encrypted, and disconnecting a channel revokes Twiligent's access at Google (#147)
+- Deleting media removes the file from Cloudinary only when Twiligent created it for you, so no one can add another member's upload to their library and delete it (#146)
## [3.1.0] - 2026-11-05
diff --git a/backend/lib/cloudinaryAddress.ts b/backend/lib/cloudinaryAddress.ts
new file mode 100644
index 0000000..570f88a
--- /dev/null
+++ b/backend/lib/cloudinaryAddress.ts
@@ -0,0 +1,24 @@
+// Cloudinary delivers an untransformed upload at /<cloud>/<type>/upload/[v<version>/]<public id>[.<format>]
+const VERSION_SEGMENT = /^v\d+\//;
+const FORMAT_SUFFIX = /^\.[A-Za-z0-9]+$/;
+
+export function isDeliveryAddressFor(address: string, cloudName: string, resourceType: string, publicId: string): boolean {
+ let url: URL;
+ try {
+ url = new URL(address);
+ } catch {
+ return false;
+ }
+ if (url.protocol !== 'https:' || url.hostname !== 'res.cloudinary.com' || url.search || url.hash) return false;
+ const prefix = `/${cloudName}/${resourceType}/upload/`;
+ let path: string;
+ try {
+ path = decodeURIComponent(url.pathname);
+ } catch {
+ return false;
+ }
+ if (!path.startsWith(prefix)) return false;
+ const rest = path.slice(prefix.length).replace(VERSION_SEGMENT, '');
+ if (rest === publicId) return true;
+ return rest.startsWith(publicId) && FORMAT_SUFFIX.test(rest.slice(publicId.length));
+}
diff --git a/backend/mcp/tools/mediaTools.ts b/backend/mcp/tools/mediaTools.ts
index 9c5813a..67d71d1 100644
--- a/backend/mcp/tools/mediaTools.ts
+++ b/backend/mcp/tools/mediaTools.ts
@@ -2,7 +2,7 @@ import { READ_ONLY, defineTool } from '../tool.ts';
import { idProperty, objectSchema, pageOf, pageProperties, parsePage, requiredId, withConfirmation } from '../schemas.ts';
import { MAX_MEDIA_LABEL_LENGTH, parseMediaImport, parseMediaLabel } from '../../validators/mediaValidators.ts';
import type { Page } from '../schemas.ts';
-import type { MediaImport } from '../../services/mediaService.ts';
+import type { FileKeptReason, MediaImport } from '../../services/mediaService.ts';
const labelProperty = { type: 'string', maxLength: MAX_MEDIA_LABEL_LENGTH, description: 'A short name to find the file by later' };
@@ -50,10 +50,15 @@ export const updateMedia = defineTool<{ mediaId: string; label: string }>({
},
});
+const FILE_KEPT_NOTES: Record<FileKeptReason, string> = {
+ no_api_secret: 'The file is still on Cloudinary: this instance has no Cloudinary API secret to delete it with. Its address keeps working until the owner deletes it in the Cloudinary console.',
+ not_created_by_twiligent: 'The file is still on Cloudinary: it was uploaded from the browser or already existed, so Twiligent cannot tell it is only yours and never deletes it. The instance owner can delete it in the Cloudinary console.',
+};
+
export const deleteMedia = defineTool<{ mediaId: string }>({
name: 'delete_media',
title: 'Delete media',
- description: 'Deletes one of your imported files. A post already scheduled with its address will fail to publish. When the instance has a Cloudinary API secret the file is deleted from Cloudinary too; otherwise only Twiligent\'s record goes and the result says so. Asks for a confirmation first.',
+ description: 'Deletes one of your imported files. A post already scheduled with its address will fail to publish. When the instance has a Cloudinary API secret, a file Twiligent imported is deleted from Cloudinary too; a file uploaded from the browser, or an instance without the secret, keeps the file and the result says so. Asks for a confirmation first.',
inputSchema: withConfirmation(objectSchema({ mediaId: idProperty('media') }, ['mediaId'])),
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
permission: 'write',
@@ -61,12 +66,8 @@ export const deleteMedia = defineTool<{ mediaId: string }>({
describe: ({ mediaId }) => `Delete media ${mediaId}; a post scheduled with it would fail to publish.`,
parse: args => ({ mediaId: requiredId(args, 'mediaId', 'media') }),
async run({ mediaId }, { services, principal }) {
- const { removedFromCloudinary } = await services.media.remove(principal.userId, mediaId);
- return {
- deleted: mediaId,
- removedFromCloudinary,
- note: removedFromCloudinary ? undefined : 'The file is still on Cloudinary: this instance has no Cloudinary API secret to delete it with. Its address keeps working until the owner deletes it in the Cloudinary console.',
- };
+ const { removedFromCloudinary, fileKept } = await services.media.remove(principal.userId, mediaId);
+ return { deleted: mediaId, removedFromCloudinary, note: fileKept ? FILE_KEPT_NOTES[fileKept] : undefined };
},
});
diff --git a/backend/repositories/mediaAssetRepository.ts b/backend/repositories/mediaAssetRepository.ts
index 6b8d830..a6885f8 100644
--- a/backend/repositories/mediaAssetRepository.ts
+++ b/backend/repositories/mediaAssetRepository.ts
@@ -14,6 +14,7 @@ interface MediaRow {
height: number | null;
duration_seconds: number | null;
label: string;
+ owns_file: boolean;
created_at: string;
}
@@ -27,12 +28,13 @@ export interface NewMediaAsset {
height: number | null;
durationSeconds: number | null;
label: string;
+ ownsFile: boolean;
}
// the Cloudinary id stays inside the Worker: it is what deleting needs, and a caller never sends one
-export type StoredMediaAsset = MediaAsset & { publicId: string };
+export type StoredMediaAsset = MediaAsset & { publicId: string; ownsFile: boolean };
-const COLUMNS = 'id, public_id, resource_type, url, format, bytes, width, height, duration_seconds, label, created_at';
+const COLUMNS = 'id, public_id, resource_type, url, format, bytes, width, height, duration_seconds, label, owns_file, created_at';
function toAsset(row: MediaRow): StoredMediaAsset {
return {
@@ -46,6 +48,7 @@ function toAsset(row: MediaRow): StoredMediaAsset {
height: row.height,
durationSeconds: row.duration_seconds === null ? null : Number(row.duration_seconds),
label: row.label,
+ ownsFile: row.owns_file,
createdAt: row.created_at,
};
}
@@ -75,6 +78,7 @@ export function createMediaAssetRepository(db: SupabaseClient): MediaAssetReposi
height: asset.height,
duration_seconds: asset.durationSeconds,
label: asset.label,
+ owns_file: asset.ownsFile,
}).select(COLUMNS));
return toAsset(created[0]);
},
diff --git a/backend/services/cloudinary/cloudinaryApi.ts b/backend/services/cloudinary/cloudinaryApi.ts
index d66a60e..4a2c923 100644
--- a/backend/services/cloudinary/cloudinaryApi.ts
+++ b/backend/services/cloudinary/cloudinaryApi.ts
@@ -15,6 +15,8 @@ export interface CloudinaryUpload {
width?: number;
height?: number;
duration?: number;
+ // set when the upload landed on a file that was already there, which may be someone else's
+ existing?: boolean;
}
interface CloudinaryErrorBody {
diff --git a/backend/services/mediaService.ts b/backend/services/mediaService.ts
index fa1536d..c003655 100644
--- a/backend/services/mediaService.ts
+++ b/backend/services/mediaService.ts
@@ -1,4 +1,5 @@
import { destroyFile, fileSize, uploadFromUrl } from './cloudinary/cloudinaryApi.ts';
+import { isDeliveryAddressFor } from '../lib/cloudinaryAddress.ts';
import { NotConfiguredError, NotFoundError, UpstreamError, ValidationError, isUniqueViolation } from '../lib/errors.ts';
import type { MediaRegistration } from '../validators/mediaValidators.ts';
import type { MediaResourceType } from './cloudinary/cloudinaryApi.ts';
@@ -21,9 +22,12 @@ export interface MediaImport {
label: string;
}
+// why a deleted record's file stayed on Cloudinary: the instance cannot delete files, or Twiligent did not create this one
+export type FileKeptReason = 'no_api_secret' | 'not_created_by_twiligent';
+
export interface MediaRemoval {
- // false when the instance has no Cloudinary API secret, so only Twiligent's record was removed
removedFromCloudinary: boolean;
+ fileKept: FileKeptReason | null;
}
export interface MediaService {
@@ -37,7 +41,7 @@ export interface MediaService {
}
// the Cloudinary id never leaves the Worker; callers only ever see Twiligent's own id
-function publicView({ publicId: _publicId, ...asset }: StoredMediaAsset): MediaAsset {
+function publicView({ publicId: _publicId, ownsFile: _ownsFile, ...asset }: StoredMediaAsset): MediaAsset {
return asset;
}
@@ -71,6 +75,8 @@ export function createMediaService({ media, audit, config, context }: MediaDeps)
height: uploaded.height ?? null,
durationSeconds: uploaded.duration ?? null,
label,
+ // an import that landed on a file already there may have landed on someone else's
+ ownsFile: uploaded.existing !== true,
};
let saved: StoredMediaAsset;
try {
@@ -87,15 +93,14 @@ export function createMediaService({ media, audit, config, context }: MediaDeps)
async registerUpload(userId, upload) {
if (!config.cloudinary) throw new NotConfiguredError('Cloudinary is not set up on this server.');
- const url = new URL(upload.url);
- // only a file on this instance's own cloud, at the address Cloudinary gives the id it names
- const ownPath = `/${config.cloudinary.cloudName}/${upload.resourceType}/upload/`;
- if (url.hostname !== 'res.cloudinary.com' || !url.pathname.startsWith(ownPath) || !decodeURIComponent(url.pathname).includes(`/${upload.publicId}`)) {
+ // only a file on this instance's own cloud, at the exact address Cloudinary gives the id it names
+ if (!isDeliveryAddressFor(upload.url, config.cloudinary.cloudName, upload.resourceType, upload.publicId)) {
throw new ValidationError('The file is not on this server\'s Cloudinary account. Upload it from the Publish page.');
}
// the size decides every chunk boundary, so it is measured, not taken from the browser
const bytes = await fileSize(upload.url, signal);
- const record = { ...upload, bytes };
+ // nothing proves the caller uploaded it, so removing it from the library never deletes the file
+ const record = { ...upload, bytes, ownsFile: false };
try {
const saved = await media.createForUser(userId, record);
await audit.recordForUser(userId, { action: 'media_asset.imported', subjectType: 'media_asset', subjectId: saved.id, details: { resourceType: upload.resourceType } });
@@ -117,10 +122,11 @@ export function createMediaService({ media, audit, config, context }: MediaDeps)
async remove(userId, id) {
const asset = await findOwned(userId, id);
const admin = config.cloudinaryAdmin;
- if (admin) await destroyFile(admin, asset.publicId, asset.resourceType, signal);
+ const fileKept: FileKeptReason | null = !admin ? 'no_api_secret' : asset.ownsFile ? null : 'not_created_by_twiligent';
+ if (admin && !fileKept) await destroyFile(admin, asset.publicId, asset.resourceType, signal);
await media.deleteForUser(id, userId);
- await audit.recordForUser(userId, { action: 'media_asset.deleted', subjectType: 'media_asset', subjectId: id, details: { fromCloudinary: Boolean(admin) } });
- return { removedFromCloudinary: Boolean(admin) };
+ await audit.recordForUser(userId, { action: 'media_asset.deleted', subjectType: 'media_asset', subjectId: id, details: { fromCloudinary: !fileKept } });
+ return { removedFromCloudinary: !fileKept, fileKept };
},
canDeleteFiles: () => config.cloudinaryAdmin !== null,
diff --git a/backend/tests/lib/cloudinaryAddress.test.ts b/backend/tests/lib/cloudinaryAddress.test.ts
new file mode 100644
index 0000000..db211ca
--- /dev/null
+++ b/backend/tests/lib/cloudinaryAddress.test.ts
@@ -0,0 +1,18 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { isDeliveryAddressFor } from '../../lib/cloudinaryAddress.ts';
+
+test('an address matches only the exact delivery path of the id it names', () => {
+ const at = (address: string, publicId: string) => isDeliveryAddressFor(address, 'demo', 'video', publicId);
+ assert.equal(at('https://res.cloudinary.com/demo/video/upload/v17/a/b.mp4', 'a/b'), true);
+ assert.equal(at('https://res.cloudinary.com/demo/video/upload/a/b', 'a/b'), true);
+ assert.equal(at('https://res.cloudinary.com/demo/video/upload/v17/a/b.mp4', 'b'), false);
+ assert.equal(at('https://res.cloudinary.com/demo/video/upload/v17/a/b.mp4', 'a'), false);
+ assert.equal(at('https://res.cloudinary.com/demo/video/upload/v17/a/bc.mp4', 'a/b'), false);
+ assert.equal(at('https://res.cloudinary.com/demo/video/upload/w_100/v17/a/b.mp4', 'a/b'), false);
+ assert.equal(at('https://res.cloudinary.com/demo/image/upload/v17/a/b.jpg', 'a/b'), false);
+ assert.equal(at('https://res.cloudinary.com/other/video/upload/v17/a/b.mp4', 'a/b'), false);
+ assert.equal(at('https://evil.example/demo/video/upload/v17/a/b.mp4', 'a/b'), false);
+ assert.equal(at('https://res.cloudinary.com/demo/video/upload/v17/a/b.mp4?x=1', 'a/b'), false);
+ assert.equal(at('https://res.cloudinary.com/demo/video/upload/%E0%A4%A.mp4', 'x'), false);
+});
diff --git a/backend/tests/mcp/mediaTools.test.ts b/backend/tests/mcp/mediaTools.test.ts
index d75977b..b6ca3f8 100644
--- a/backend/tests/mcp/mediaTools.test.ts
+++ b/backend/tests/mcp/mediaTools.test.ts
@@ -17,7 +17,7 @@ function context(canDelete: boolean): ToolContext & { removed: string[] } {
list: async userId => (userId === 'user-1' ? [asset('a'), asset('b'), asset('c')] : []),
async remove(_userId, id) {
removed.push(id);
- return { removedFromCloudinary: canDelete };
+ return { removedFromCloudinary: canDelete, fileKept: canDelete ? null : 'no_api_secret' };
},
};
return { services: { media } as unknown as Services, principal: { userId: 'user-1', permission: 'write', via: 'token:t1' }, removed };
diff --git a/backend/tests/services/mediaService.test.ts b/backend/tests/services/mediaService.test.ts
index 99da289..2f95349 100644
--- a/backend/tests/services/mediaService.test.ts
+++ b/backend/tests/services/mediaService.test.ts
@@ -1,7 +1,7 @@
import { test, mock } from 'node:test';
import assert from 'node:assert/strict';
import { createMediaService } from '../../services/mediaService.ts';
-import { NotConfiguredError, NotFoundError, UpstreamError } from '../../lib/errors.ts';
+import { NotConfiguredError, NotFoundError, UpstreamError, ValidationError } from '../../lib/errors.ts';
import { readConfig } from '../../lib/config.ts';
import { createLogger } from '../../lib/logger.ts';
import type { AuditRepository } from '../../repositories/auditRepository.ts';
@@ -10,6 +10,8 @@ import type { Env } from '../../types/env.ts';
const CONTEXT = { requestId: 'req-test', signal: new AbortController().signal, log: createLogger() };
const WITH_CLOUDINARY = { CLOUDINARY_CLOUD_NAME: 'demo', CLOUDINARY_UPLOAD_PRESET: 'unsigned' } as Env;
+const WITH_SECRET = { ...WITH_CLOUDINARY, CLOUDINARY_API_KEY: 'KEY', CLOUDINARY_API_SECRET: 'SECRET' } as Env;
+const UPLOADED = 'https://res.cloudinary.com/demo/video/upload/v1730000000/folder/clip-abc.mp4';
// an in-memory table with the same ownership rule as the repository: every lookup needs the user id
function memory() {
@@ -79,12 +81,37 @@ test('without the API secret a delete removes only the record and says so; with
const plain = createMediaService({ media, audit, config: readConfig(WITH_CLOUDINARY), context: CONTEXT });
const first = await plain.importFromUrl('user-1', { url: 'https://example.com/a.jpg', resourceType: 'image', label: '' });
const second = await plain.importFromUrl('user-1', { url: 'https://example.com/b.jpg', resourceType: 'image', label: '' });
- assert.deepEqual(await plain.remove('user-1', first.id), { removedFromCloudinary: false });
+ assert.deepEqual(await plain.remove('user-1', first.id), { removedFromCloudinary: false, fileKept: 'no_api_secret' });
assert.equal(fetchMock.mock.callCount(), 2);
- const withSecret = { ...WITH_CLOUDINARY, CLOUDINARY_API_KEY: 'KEY', CLOUDINARY_API_SECRET: 'SECRET' } as Env;
- const admin = createMediaService({ media, audit, config: readConfig(withSecret), context: CONTEXT });
+ const admin = createMediaService({ media, audit, config: readConfig(WITH_SECRET), context: CONTEXT });
await assert.rejects(admin.remove('user-2', second.id), NotFoundError);
- assert.deepEqual(await admin.remove('user-1', second.id), { removedFromCloudinary: true });
+ assert.deepEqual(await admin.remove('user-1', second.id), { removedFromCloudinary: true, fileKept: null });
assert.match(String(fetchMock.mock.calls[2].arguments[0]), /\/demo\/image\/destroy$/);
assert.equal(rows.length, 0);
});
+
+test('a browser upload is added only at the exact address Cloudinary gives its id, and deleting it never deletes the file', async t => {
+ const fetchMock = mock.method(globalThis, 'fetch', async () => new Response(null, { status: 200, headers: { 'Content-Length': '4096' } }));
+ t.after(() => fetchMock.mock.restore());
+ const { media, audit } = memory();
+ const service = createMediaService({ media, audit, config: readConfig(WITH_SECRET), context: CONTEXT });
+ const upload = { url: UPLOADED, publicId: 'folder/clip-abc', resourceType: 'video' as const, format: 'mp4', width: 1080, height: 1920, durationSeconds: 9, label: '' };
+ for (const publicId of ['clip-abc', 'folder/clip', 'folder']) {
+ await assert.rejects(service.registerUpload('user-2', { ...upload, publicId }), ValidationError);
+ }
+ await assert.rejects(service.registerUpload('user-2', { ...upload, url: 'https://res.cloudinary.com/other/video/upload/v1/folder/clip-abc.mp4' }), ValidationError);
+ assert.equal(fetchMock.mock.callCount(), 0);
+ const registered = await service.registerUpload('user-2', upload);
+ assert.equal(registered.bytes, 4096);
+ assert.deepEqual(await service.remove('user-2', registered.id), { removedFromCloudinary: false, fileKept: 'not_created_by_twiligent' });
+ assert.equal(fetchMock.mock.callCount(), 1);
+});
+
+test('an import that landed on a file Cloudinary already had is never deleted from Cloudinary', async t => {
+ const fetchMock = cloudinaryAnswers(t, { public_id: 'shared', secure_url: 'https://res.cloudinary.com/demo/image/upload/shared.jpg', resource_type: 'image', existing: true });
+ const { media, audit } = memory();
+ const service = createMediaService({ media, audit, config: readConfig(WITH_SECRET), context: CONTEXT });
+ const imported = await service.importFromUrl('user-1', { url: 'https://example.com/shared.jpg', resourceType: 'image', label: '' });
+ assert.deepEqual(await service.remove('user-1', imported.id), { removedFromCloudinary: false, fileKept: 'not_created_by_twiligent' });
+ assert.equal(fetchMock.mock.callCount(), 1);
+});
diff --git a/backend/tests/services/youtubeUploadService.test.ts b/backend/tests/services/youtubeUploadService.test.ts
index d050635..10a1cda 100644
--- a/backend/tests/services/youtubeUploadService.test.ts
+++ b/backend/tests/services/youtubeUploadService.test.ts
@@ -14,7 +14,7 @@ const ENV = { GOOGLE_CLIENT_ID: 'client', GOOGLE_CLIENT_SECRET: 'secret', TOKEN_
const VIDEO: StoredMediaAsset = {
id: 'm-video', publicId: 'v', resourceType: 'video', url: 'https://res.cloudinary.com/demo/video/upload/v.mp4', format: 'mp4',
- bytes: 1000, width: 1080, height: 1920, durationSeconds: 45, label: '', createdAt: '',
+ bytes: 1000, width: 1080, height: 1920, durationSeconds: 45, label: '', ownsFile: false, createdAt: '',
};
const IMAGE: StoredMediaAsset = { ...VIDEO, id: 'm-image', resourceType: 'image', url: 'https://res.cloudinary.com/demo/image/upload/t.jpg', format: 'jpg', bytes: 5000 };
diff --git a/docs/architecture/database/SCHEMA.md b/docs/architecture/database/SCHEMA.md
index b24d299..a08e78d 100644
--- a/docs/architecture/database/SCHEMA.md
+++ b/docs/architecture/database/SCHEMA.md
@@ -464,6 +464,7 @@ The images and videos each person imported through the Claude media tools. The C
| `url` | text | not null, starts with `https://` | The public address Instagram publishes from |
| `format`, `bytes`, `width`, `height`, `duration_seconds` | text, bigint, integer, integer, numeric | | As Cloudinary reported them |
| `label` | text | not null, default `''`, at most 200 characters | The person's name for the file |
+| `owns_file` | boolean | not null, default false | True only when Twiligent created the file for this person (an import Cloudinary did not answer with `existing`); deleting the row deletes the file from Cloudinary only then, because a browser upload proves no ownership on the shared account |
| `created_at`, `updated_at` | timestamptz | not null, default now() | |
Index `media_assets_user_created_idx` on `(user_id, created_at desc)` serves the list.
diff --git a/docs/platform-v2/MCP_DOCUMENTATION.md b/docs/platform-v2/MCP_DOCUMENTATION.md
index 5df90d6..46da728 100644
--- a/docs/platform-v2/MCP_DOCUMENTATION.md
+++ b/docs/platform-v2/MCP_DOCUMENTATION.md
@@ -129,7 +129,7 @@ Every tool works only on the caller's own data. Read tools need no confirmation.
| `list_media` | read | `limit`, `cursor` | `media` (id, type, public https `url`, size and dimensions, label), `nextCursor`, `total` |
| `import_media_from_url` | write | `url` (public https), `resourceType` (`image` or `video`), `label` | `media`. Cloudinary downloads the file, not the Worker; private and non-https addresses are refused |
| `update_media` | write | `mediaId`, `label` | `media` |
-| `delete_media` | write, confirm | `mediaId` | `deleted`, `removedFromCloudinary`, and a `note` when the file stays on Cloudinary because the instance has no API secret |
+| `delete_media` | write, confirm | `mediaId` | `deleted`, `removedFromCloudinary`, and a `note` when the file stays on Cloudinary: the instance has no API secret, or Twiligent did not create the file (a browser upload, or an import that landed on a file Cloudinary already had) |
| `list_youtube_channels` | read | none | `channels` (no tokens), `configured` |
| `list_youtube_uploads`, `get_youtube_upload` | read | `limit`, `cursor`; or `uploadId` | Upload jobs with state, progress, video id and error |
| `create_youtube_upload` | write, confirm when public, unlisted or scheduled | `connectionId`, `mediaId`, `title`, `privacy`, `madeForKids`, and optional `description`, `tags`, `categoryId`, `publishAt`, `syntheticMedia`, `notifySubscribers`, `thumbnailMediaId`, `clientRequestId` | `upload`, `alreadyQueued` |
diff --git a/docs/platform-v2/SECURITY_AUDIT.md b/docs/platform-v2/SECURITY_AUDIT.md
index 791890e..65c1f36 100644
--- a/docs/platform-v2/SECURITY_AUDIT.md
+++ b/docs/platform-v2/SECURITY_AUDIT.md
@@ -120,3 +120,4 @@ None of the four could be confirmed from source alone, since each depends on Sup
- Accepted for now: revoked access tokens stay in the table (only active ones count toward the limit of 20), and an access token does not re-check the Supabase account's status; deleting the account deletes its tokens.
Deferred by the run (quick profile, one wave): browser sign-in establishment beyond N2, and access token lifetime against account recovery or email change.
+,## YouTube publishing and media review (#147, #146),,Claude Code `security-review` ran on the diff from `fix/audit-leads` to `feat/youtube-publishing` (media tools, the second audit's fixes, YouTube publishing). It found no vulnerability at confidence 8 or above. It checked cross-user access on every new repository method, the Google sign-in binding and state signature, token sealing and leakage, server-side requests from the runner and the media routes, the two new SQL functions and the new tables' browser access.,,It raised one lead below the bar, and it was fixed:,,| Id | Lead | Status |,|---|---|---|,| M1 | `POST /api/media` accepted any file on the instance's Cloudinary account and only checked that the address contained the id somewhere. A member who learned another member's file address could add it to their own library, then delete it from the shared account with `delete_media`, which uses the instance's API secret | Fixed: the address must be exactly the one Cloudinary gives the id (`backend/lib/cloudinaryAddress.ts`), and `media_assets.owns_file` records whether Twiligent created the file for this person. Only such a file is deleted from Cloudinary; a browser upload, or an import that landed on a file Cloudinary already had (`existing`), keeps its file and the tool says why. Tests: `backend/tests/lib/cloudinaryAddress.test.ts`, `backend/tests/services/mediaService.test.ts` |,
\ No newline at end of file
diff --git a/site/content/docs/reference/environment.mdx b/site/content/docs/reference/environment.mdx
index 64b5b46..c4563aa 100644
--- a/site/content/docs/reference/environment.mdx
+++ b/site/content/docs/reference/environment.mdx
@@ -31,7 +31,7 @@ The backend only answers browsers on `FRONTEND_URL` and the addresses in `ALLOWE
| `RESEND_API_KEY` <Badge tone="secret">Secret</Badge> | <Badge tone="optional">Optional</Badge> | Resend, API Keys (sending access) | Sends sign-in and verification codes and other auth emails. |
| `EMAIL_FROM` | <Badge tone="optional">Optional</Badge> | A sender on a domain verified in Resend, for example {'Twiligent <[email protected]>'} | The sender of those emails. |
| `EMAIL_DAILY_LIMIT` | <Badge tone="optional">Optional</Badge> | A whole number; 100 when not set | Emails a day before the sign-in page pauses email codes and points people to Google or a password. |
-| `CLOUDINARY_API_KEY`, `CLOUDINARY_API_SECRET` <Badge tone="secret">Secret</Badge> | <Badge tone="optional">For Claude</Badge> | Cloudinary, Settings, API Keys | Lets Claude delete media files it imported. Without them, a delete only removes Twiligent's record. |
+| `CLOUDINARY_API_KEY`, `CLOUDINARY_API_SECRET` <Badge tone="secret">Secret</Badge> | <Badge tone="optional">For Claude</Badge> | Cloudinary, Settings, API Keys | Lets Claude delete media files it imported from a link. Without them, and for files uploaded from the browser, a delete only removes Twiligent's record. |
| `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET` <Badge tone="secret">Secret</Badge> | <Badge tone="optional">For YouTube publishing</Badge> | Google Cloud, Clients, your Web application client | Lets members connect their YouTube channels to upload videos. See [YouTube publishing](/docs/self-host/youtube-publishing). |
| `TOKEN_ENCRYPTION_KEY` <Badge tone="secret">Secret</Badge> | <Badge tone="optional">For Claude and YouTube</Badge> | 32 or more random characters, for example from {'openssl rand -base64 48'} | Signs the confirmations Claude needs before it schedules or cancels a post, and seals the stored Google tokens. If it changes, members connect YouTube again. |
| `MCP_OAUTH_ENABLED` | <Badge tone="optional">For Claude</Badge> | `true` | Lets Claude on the web, desktop and mobile connect, after you turn on Supabase's OAuth server. |
diff --git a/supabase/migrations/20261105034040_create_media_assets.sql b/supabase/migrations/20261105034040_create_media_assets.sql
index ac5b736..f5fca9e 100644
--- a/supabase/migrations/20261105034040_create_media_assets.sql
+++ b/supabase/migrations/20261105034040_create_media_assets.sql
@@ -12,6 +12,8 @@ create table public.media_assets (
height integer,
duration_seconds numeric,
label text not null default '',
+ -- true only when Twiligent created the file for this person; a browser upload proves no ownership, so it is never deleted from Cloudinary
+ owns_file boolean not null default false,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now(),
constraint media_assets_user_public_id_key unique (user_id, public_id),
diff --git a/supabase/schemas/public/tables/media_assets.sql b/supabase/schemas/public/tables/media_assets.sql
index 347e561..494c0b4 100644
--- a/supabase/schemas/public/tables/media_assets.sql
+++ b/supabase/schemas/public/tables/media_assets.sql
@@ -10,6 +10,7 @@ CREATE TABLE "public"."media_assets" (
"height" integer,
"duration_seconds" numeric,
"label" text NOT NULL DEFAULT ''::text,
+ "owns_file" boolean NOT NULL DEFAULT false,
"created_at" timestamp with time zone NOT NULL DEFAULT now(),
"updated_at" timestamp with time zone NOT NULL DEFAULT now(),
CONSTRAINT "media_assets_label_check" CHECK ((char_length(label) <= 200)),