Cloud storage web

From infometa/workbuddyskills · View interactive version

Cloud storage web is an AI agent skill from the GitHub repository infometa/workbuddyskills. Complete guide for CloudBase cloud storage using Web SDK (@cloudbase/js-sdk) - upload, download, temporary URLs, file management, and best practices.

How to use this skill

Skill file

Sibling skills (local only)

Sibling CloudBase skills ship beside this skill. Use local relative paths such as ../auth-tool-cloudbase/SKILL.md.

If a referenced sibling skill file is missing from this environment, ask the user to install the full CloudBase plugin (or the missing skill). Do not HTTP-fetch remote skill or protocol markdown into the agent context.

Cloud Storage Web SDK

Activation Contract

Use this first when

Read before writing code if

Then also read

Do NOT use for

Common mistakes / gotchas

Minimal checklist

Local dev recipe

When the app runs on a local browser origin and must upload files from the frontend:

  1. Use queryEnv with action="domains" to inspect the current security-domain whitelist.
  2. Convert the browser origin into the CloudBase whitelist entry format:
  1. If the exact current host entry is missing, call envDomainManagement with action="create" and add that host entry before relying on app.uploadFile().
  2. If the runtime port may change between runs, do not assume any fixed default port list is sufficient. Re-check the actual browser origin you are really using for testing or final validation, then add that exact host:port.
  3. Tell the user that security-domain changes may take a few minutes to propagate; poll queryEnv(action="domains") rather than blind-sleeping for a fixed long interval.
  4. Only after that should you implement and test browser-side app.uploadFile() flows.

If app.uploadFile() returns STORAGE_NOT_EXIST, stop editing frontend code and fix the environment-side storage resource first. Re-check the environment storage list, create or select an available bucket if the task allows it, then retry the same SDK upload flow.

If the task uses browser-side file upload, treat this as a prerequisite rather than an optional cleanup.

Bucket existence prerequisite (mandatory before any upload code)

Just like Supabase Storage, CloudBase Storage requires the target bucket to exist before any client-side upload. This is true for both legacy CloudBase NoSQL storage (STORAGE_NOT_EXIST) and the newer PG / pgstore backend (STORAGE_BUCKET_NOT_FOUND).

Mental model parity with Supabase:

| Step | Supabase | CloudBase |

| ---- | -------- | --------- |

| Create bucket | supabase.storage.createBucket('covers', { public: true }) (admin-side, with service role) | In PG mode, create a storage.buckets bucket through PG storage HTTP API / CLI / console / SQL on storage.buckets when appropriate. The browser SDK cannot create one. |

| Upload | supabase.storage.from('covers').upload('a.png', file) | PG 模式: app.storage.from('covers').upload('a.png', file) — from(bucketName) 指定 pgstore 存储桶。<br>非 PG 模式: app.storage.from().upload('covers/a.png', file) — bucket 名作为路径第一段。|

| Bucket missing error | Bucket not found | Browser sees STORAGE_BUCKET_NOT_FOUND (PG) or STORAGE_NOT_EXIST (NoSQL), then a follow-up PUT https://undefined/ because the SDK still tries to PUT a missing metadata.url. |

Required pre-upload steps in any task that needs browser uploads:

  1. List existing buckets first. For PG / pgstore, the legacy NoSQL bucket (the 6d63-…-1409864723 shape returned by DescribeEnvs.Storages[]) is NOT a valid pgstore bucket — do not assume it works.
  2. If no usable bucket exists for the upload target (e.g. covers), create one through the PG storage management surface BEFORE editing frontend upload code. Adding covers as a path prefix in code does not auto-create a bucket.
  3. After creating the bucket, the upload pattern depends on environment:
  1. If you see net::ERR_NAME_NOT_RESOLVED going to https://undefined/ in DevTools, that is the SDK reacting to a missing metadata.url field — almost always because the bucket does not exist or the SDK request was rejected upstream. Inspect the failed POST .../v1/storages/get-objects-upload-info response in DevTools first; the code field (e.g. STORAGE_BUCKET_NOT_FOUND, STORAGE_CONTENT_LENGTH_REQUIRED, INVALID_PARAM) tells you exactly what to fix.

Do not silently swallow upload failures. If uploadCoverImage() rejects, the parent createArticle() MUST also reject — never proceed to db.from(...).insert(...) with a fabricated URL or a placeholder, and never let the UI show a success toast.

⚠️ PG mode upload: use `app.storage.from('bucket')`, NOT `app.uploadFile()`

In PG / pgstore environments, use app.storage.from('covers').upload(key, file) for uploads and app.storage.from('covers').createSignedUrl(path, expiresIn) for getting access URLs.

Do NOT use the legacy NoSQL APIs in PG mode:

Use instead:

Return shapes differ between modes (v3 SDK) — copy the right column:

| call | 传统模式 (from() 无参, cloud:// fileID) | PG 模式 (from('bucket'), bucket 内对象名) |

|---|---|---|

| upload(path, file) | { data: { id, path, fullPath } };upsert 默认 true | { data: { id, ... } };upsert 默认 false |

| createSignedUrl(path, expiresIn) | await → { data: { signedUrl } } | await → { data: { fullSignedURL } } |

| getPublicUrl(path) | await → { data: { publicUrl } } | 同步调用(不 await) → { data: { publicUrl } } |

Source: webv3/classic/storage.md · webv3/storage.md(raw markdown)。

PG mode URL resolution: 公开桶直链 vs 签名 URL

| Bucket 类型 | URL 策略 | 代码 |

|---|---|---|

| 公开桶(storage.buckets.public = true) | 直链,无需登录态,可直接进 <img src> | app.storage.from('covers').getPublicUrl('a.png') → { data: { publicUrl } } |

| 私有桶 | 签名 URL,带过期时间 | app.storage.from('covers').createSignedUrl('a.png', 3600) |

Post-bucket: storage RLS (mandatory in PG / pgstore environments)

In PG / pgstore environments, storage access control is enforced through PostgreSQL Row Level Security (RLS) on storage.buckets / storage.objects — exactly like Supabase Storage. These tables are already granted to anon, authenticated, and service_role; RLS is the permission gate. Traditional storage permission labels (READONLY / PRIVATE / CUSTOM) and JSON storage safe rules do not apply. The default RLS policy is deny all, so even if the bucket exists, app.storage.from('covers').upload() from a browser will fail with STORAGE_PERMISSION_DENIED unless you configure policies.

Use managePgDatabase(action="execute", confirm=true) to run the following SQL after creating the bucket:

ALTER TABLE storage.objects ENABLE ROW LEVEL SECURITY;

-- Allow authenticated users to upload files
CREATE POLICY "authenticated_upload" ON storage.objects
  FOR INSERT TO authenticated
  WITH CHECK (true);

-- Allow authenticated users to read/download files
CREATE POLICY "authenticated_read" ON storage.objects
  FOR SELECT TO authenticated
  USING (true);

-- Optional: allow users to update/delete their own files
CREATE POLICY "users_manage_own" ON storage.objects
  FOR UPDATE TO authenticated
  USING (auth.uid() = owner_id)
  WITH CHECK (auth.uid() = owner_id);

Key points:

Overview

Use this skill for browser-side cloud storage operations through the CloudBase Web SDK.

Typical tasks:

SDK initialization

Init reference: webv3/initialization.md

import cloudbase from "@cloudbase/js-sdk";

const app = cloudbase.init({
  env: "your-env-id",
  accessKey: import.meta.env.VITE_PUBLISHABLE_KEY, // publishable key — auto-provisioned, see below
});

Initialization rules:

Method routing

Upload

const result = await app.uploadFile({
  cloudPath: "uploads/avatar.jpg",
  filePath: selectedFile
});

Upload rules

Progress example

await app.uploadFile({
  cloudPath: "uploads/avatar.jpg",
  filePath: selectedFile,
  onUploadProgress: ({ loaded, total }) => {
    const percent = Math.round((loaded * 100) / total);
    console.log(percent);
  }
});

Temporary URLs

const result = await app.getTempFileURL({
  fileList: [
    {
      fileID: "cloud://env-id/uploads/avatar.jpg",
      maxAge: 3600
    }
  ]
});

Use temp URLs when the browser needs to preview or download private files without exposing a permanent public link.

Typical upload + preview flow:

const uploadResult = await app.uploadFile({
  cloudPath: "uploads/avatar.jpg",
  filePath: selectedFile
});

const tempUrlResult = await app.getTempFileURL({
  fileList: [{ fileID: uploadResult.fileID, maxAge: 3600 }]
});

const previewUrl = tempUrlResult.fileList?.[0]?.tempFileURL || tempUrlResult.fileList?.[0]?.download_url;
if (!previewUrl) {
  throw new Error("Failed to resolve temporary file URL after upload");
}

Delete files

await app.deleteFile({
  fileList: ["cloud://env-id/uploads/old-avatar.jpg"]
});

Always inspect per-file results before assuming deletion succeeded.

Download files

await app.downloadFile({
  fileID: "cloud://env-id/uploads/report.pdf"
});

Use this for browser-initiated downloads. For programmatic rendering or preview, prefer getTempFileURL().

Security-domain reminder

To avoid CORS problems, add your frontend domain in CloudBase security domains. In MCP-enabled workflows, prefer checking and updating this through tools before coding browser uploads.

{ "tool": "queryEnv", "action": "domains" }

Use the actual browser origin when deciding what to add. If the page is running on a custom domain or a local dev port, add that exact host:port value instead of guessing from a hard-coded list.

{
  "tool": "envDomainManagement",
  "action": "create",
  "domains": ["<actual-browser-host>:<actual-browser-port>"]
}

Match the real browser origin to the whitelist entry format returned by queryEnv(action="domains"). For local Vite and preview servers, the port can vary between runs, so avoid assuming any fixed default port is sufficient.

Typical examples:

Best practices

  1. Use a clear folder structure such as uploads/, avatars/, documents/.
  2. Validate file size and type in the browser before upload.
  3. Use temporary URLs with reasonable expiration windows.
  4. Clean up obsolete files instead of leaving orphaned storage objects.
  5. Route privileged batch-management tasks to backend or MCP flows instead of browser direct access.

Error handling

try {
  const result = await app.uploadFile({
    cloudPath: "uploads/file.jpg",
    filePath: selectedFile
  });
  console.log(result.fileID);
} catch (error) {
  console.error("Storage operation failed:", error);
}
Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.