Repository navigation
feat(studio-local): functions management api - function blob artifacts - #42349
Conversation
|
Thanks for contributing to Supabase! ❤️ Our team will review your PR. A few tips for a smoother review process:
|
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
@kallebysantos is attempting to deploy a commit to the Supabase Team on Vercel. A member of the Team first needs to authorize it. |
WalkthroughAdds IS_PLATFORM gating across Edge Functions UI and File Explorer, exposes function file entries via a new FileSystem store method and authenticated multipart GET API endpoint, and adds Monaco language modules for JavaScript, TypeScript, and Markdown. Changes
Sequence DiagramsequenceDiagram
participant Client as Client/Browser
participant API as Next API Handler (body.ts)
participant Store as FunctionsArtifactStore
participant FS as File System
participant Stream as Multipart Stream Builder
Client->>API: GET /api/v1/projects/[ref]/functions/[slug]/body
API->>API: validate slug & auth
API->>Store: getFileEntriesBySlug(slug)
Store->>FS: read folder recursively
FS-->>Store: file entries + stats
Store-->>API: FunctionFileEntry[]
API->>Stream: build metadata part
loop for each file
API->>Stream: add file part (headers)
Stream->>FS: stream file contents
FS-->>Stream: file data
end
Stream->>Client: stream multipart/form-data response
Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Fix all issues with AI agents
In `@apps/studio/lib/api/self-hosted/functions/fileSystemStore.ts`:
- Around line 72-85: The function parseFileToFunctionBlobArtifact is returning a
filename that leaks the full server path by using path.join(file.parentPath,
file.name) instead of a path relative to the function root; change it to compute
a relative path from originalFolderPath (e.g., use
path.relative(originalFolderPath, path.join(file.parentPath, file.name)) and use
that relativePath for the filename field), normalizing separators if needed so
the client receives a clean relative filename rather than an absolute server
path.
- Around line 33-40: The code in getBlobArtifactsBySlug allows path traversal by
joining slug directly to this.folderPath; change to resolve and validate the
target before reading: compute const base = path.resolve(this.folderPath) and
const target = path.resolve(base, slug), then ensure path.relative(base, target)
does not start with '..' (and optionally that path.isAbsolute(target) is within
base); if the check fails, throw or return []; after that use await stat(target)
to confirm it's a directory before calling readdir on functionFolderPath. Ensure
you reference function names/vars getBlobArtifactsBySlug, this.folderPath,
functionFolderPath/target, and readdir/stat in the change.
In `@apps/studio/pages/api/v1/projects/`[ref]/functions/[slug]/body.ts:
- Around line 49-56: The response is currently sending multipartResponse.text(),
which decodes UTF-8 and corrupts binary parts; instead read the body with
multipartResponse.arrayBuffer(), convert to a Node Buffer, set the Content-Type
header from multipartResponse.headers.get('content-type') (already done via
multipartResponse), and send the Buffer via res.status(200).send(...). Update
the code paths that reference multipartResponse, form, and res to use
arrayBuffer -> Buffer.from(arrayBuffer) and send that buffer.
🧹 Nitpick comments (2)
apps/studio/data/edge-functions/edge-function-body-query.ts (1)
6-6: Unused import after removingIS_PLATFORMgating.The
IS_PLATFORMconstant is imported but no longer used in this file after removing it from theenabledcondition. Consider removing this import to avoid dead code.🧹 Suggested cleanup
-import { IS_PLATFORM } from 'lib/constants'apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx (1)
54-61: DuplicaterefetchOnMountoption.
refetchOnMount: falseappears twice in the query options (lines 55 and 58). The second declaration shadows the first, which is harmless but indicates unintentional duplication.🧹 Remove duplicate option
{ // [Alaister]: These parameters prevent the function files // from being refetched when the user is editing the code retry: false, retryOnMount: false, refetchOnWindowFocus: false, staleTime: Infinity, - refetchOnMount: false, refetchOnReconnect: false, refetchInterval: false, refetchIntervalInBackground: false, }
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In `@apps/studio/lib/api/self-hosted/functions/fileSystemStore.ts`:
- Around line 36-42: The code calls readdir(functionFolderPath, ...) which
throws ENOENT when slug refers to a non-existent function; wrap the readdir call
in a try/catch inside the same function so that if the caught error.code ===
'ENOENT' you return an empty array (preserving the current guard that checks
functionFolderPath.startsWith(...)), and for any other error rethrow it; update
references to functionFolderPath, slug and readdir accordingly so the behaviour
is consistent and only ENOENT is handled silently.
In `@apps/studio/pages/api/v1/projects/`[ref]/functions/[slug]/body.ts:
- Around line 57-59: Add a defensive null check for multipartResponse.body
before calling Readable.fromWeb; if multipartResponse.body is null/undefined,
set an appropriate status (e.g., res.status(204) or res.status(500) with an
error message) and end the response instead of using the non-null assertion.
Locate the code that builds/receives multipartResponse (variable
multipartResponse) and replace the current lines that call
Readable.fromWeb(multipartResponse.body!) and readable.pipe(res) with a guard
that returns early when body is missing, otherwise create the Readable via
Readable.fromWeb(multipartResponse.body) and pipe it to res.
🧹 Nitpick comments (2)
apps/studio/lib/api/self-hosted/functions/fileSystemStore.ts (1)
46-47: RedundantisFile()check in helper function.Line 46 already filters entries to files only, so the
if (!file.isFile()) returncheck at line 78 is redundant. Consider removing it for clarity.apps/studio/pages/api/v1/projects/[ref]/functions/[slug]/body.ts (1)
30-48: Consider returning 404 when function has no artifacts.If
getBlobArtifactsBySlugreturns an empty array (e.g., function slug doesn't exist or has no files), the endpoint returns 200 with only metadata. This may confuse clients expecting function code or a clear "not found" signal.💡 Suggested check
const blobArtifacts = await store.getBlobArtifactsBySlug(slug) + if (blobArtifacts.length === 0) { + return res.status(404).json({ error: { message: `Function '${slug}' not found or has no files` } }) + } + const form = new FormData()
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In `@apps/studio/lib/api/self-hosted/functions/fileSystemStore.ts`:
- Around line 33-59: Prettier formatting is failing for the getFileEntriesBySlug
function in fileSystemStore.ts; run the project's Prettier/formatting tool (or
npm/yarn format script) against
apps/studio/lib/api/self-hosted/functions/fileSystemStore.ts to apply the repo's
formatting rules, then commit the updated file so the CI Prettier check
passes—ensure you preserve existing logic in getFileEntriesBySlug, including use
of path.resolve, readdir/stat, and the returned fileEntries structure.
In `@apps/studio/pages/api/v1/projects/`[ref]/functions/[slug]/body.ts:
- Around line 63-66: The multipart header writes entry.relativePath directly
into Content-Disposition which can contain quotes or CR/LF and corrupt the
stream; update the code that builds the header (the res.write call using
boundary and entry.relativePath) to produce a safe filename by
sanitizing/encoding the value—e.g., remove or replace CR and LF, escape
quotes/backslashes, and include an encoded fallback (filename* with RFC5987
percent-encoding or use encodeURIComponent on the name) so the header uses only
safe characters; ensure the same sanitized/encoded identifier is used both for
filename and filename* parameters.
5998132 to
c8be8fb
Compare
| multipartResponse.headers.get('content-type') ?? 'multipart/form-data' | ||
| ) | ||
|
|
||
| return res.status(200).send(await multipartResponse.text()) |
There was a problem hiding this comment.
This loads everything into memory which could be significant, let's try streaming instead
| async getBlobArtifactsBySlug(slug: string): Promise<FunctionBlobArtifact[]> { | ||
| if (slug === 'main') return [] | ||
|
|
||
| const functionFolderPath = path.join(this.folderPath, slug) |
There was a problem hiding this comment.
possible path traversal here?
…nments (#42992) Feature ## What is the current behavior? The Functions counter on the Home page is only displayed in platform environments. In self-hosted setups, the counter is hidden due to a platform guard, even though Functions may be available. ## What is the new behavior? The Functions counter is now also displayed in self-hosted environments. This is now possible thanks to the following PRs: - #40690 - #42322 - #42349 - #42350 These PRs introduce and enable the API required for listing Functions in Studio, making it feasible to show the Functions count outside of the platform environment. ## Additional context Related issues: #36285 This change removes the platform-only restriction around the Functions card in the Home interface, allowing feature parity between platform and self-hosted deployments where the Functions API is available. --------- Co-authored-by: Andrey A. <[email protected]> Co-authored-by: Charis Lam <[email protected]>
What kind of change does this PR introduce?
Feature
What is the current behavior?
Functions page on self-hosted differs from Platform
What is the new behavior?
Note
This PR only add readonly operations. Function edit and deploy should be implemented in a future one.
Adds the possibility to download and see function code in Self-Host version.
Details
Summary by CodeRabbit
New Features
Improvements
Editor