refactor(libsql): update form validation and import resolver

- Replaced zodResolver import with standardSchemaResolver for improved schema handling.
- Refactored DockerProviderSchema to streamline validation logic and enhance readability.
- Updated external port validation to check for empty values and ensure proper error handling.
- Adjusted service access checks in the libsql router for better permission management.
This commit is contained in:
Mauricio Siu
2026-03-23 00:51:45 -06:00
parent b61ca31981
commit b9aa275759
4 changed files with 359 additions and 410 deletions
@@ -1,4 +1,4 @@
import { zodResolver } from "@hookform/resolvers/zod"; import { standardSchemaResolver as zodResolver } from "@hookform/resolvers/standard-schema";
import Link from "next/link"; import Link from "next/link";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useForm } from "react-hook-form"; import { useForm } from "react-hook-form";
@@ -26,64 +26,37 @@ import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
import { api } from "@/utils/api"; import { api } from "@/utils/api";
const createDockerProviderSchema = (sqldNode?: string) => const DockerProviderSchema = z.object({
z externalPort: z.preprocess((a) => {
.object({ if (a === null || a === undefined || a === "") return null;
externalPort: z.preprocess((a) => { const parsed = Number.parseInt(String(a), 10);
if (a !== null) { return Number.isNaN(parsed) ? null : parsed;
const parsed = Number.parseInt(z.string().parse(a), 10); }, z
return Number.isNaN(parsed) ? null : parsed; .number()
} .gte(0, "Range must be 0 - 65535")
return null; .lte(65535, "Range must be 0 - 65535")
}, z .nullable()),
.number() externalGRPCPort: z.preprocess((a) => {
.gte(0, "Range must be 0 - 65535") if (a === null || a === undefined || a === "") return null;
.lte(65535, "Range must be 0 - 65535") const parsed = Number.parseInt(String(a), 10);
.nullable()), return Number.isNaN(parsed) ? null : parsed;
externalGRPCPort: z.preprocess((a) => { }, z
if (a !== null) { .number()
const parsed = Number.parseInt(z.string().parse(a), 10); .gte(0, "Range must be 0 - 65535")
return Number.isNaN(parsed) ? null : parsed; .lte(65535, "Range must be 0 - 65535")
} .nullable()),
return null; externalAdminPort: z.preprocess((a) => {
}, z if (a === null || a === undefined || a === "") return null;
.number() const parsed = Number.parseInt(String(a), 10);
.gte(0, "Range must be 0 - 65535") return Number.isNaN(parsed) ? null : parsed;
.lte(65535, "Range must be 0 - 65535") }, z
.nullable()), .number()
externalAdminPort: z.preprocess((a) => { .gte(0, "Range must be 0 - 65535")
if (a !== null) { .lte(65535, "Range must be 0 - 65535")
const parsed = Number.parseInt(z.string().parse(a), 10); .nullable()),
return Number.isNaN(parsed) ? null : parsed; });
}
return null; type DockerProvider = z.infer<typeof DockerProviderSchema>;
}, z
.number()
.gte(0, "Range must be 0 - 65535")
.lte(65535, "Range must be 0 - 65535")
.nullable()),
})
.superRefine((data, ctx) => {
if (
data.externalPort === null &&
data.externalGRPCPort === null &&
data.externalAdminPort === null
) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
"Either externalPort, externalGRPCPort or externalAdminPort must be provided.",
path: ["externalPort", "externalGRPCPort", "externalAdminPort"],
});
}
if (sqldNode === "replica" && data.externalGRPCPort !== null) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "externalGRPCPort cannot be set when sqldNode is 'replica'",
path: ["externalGRPCPort"],
});
}
});
interface Props { interface Props {
libsqlId: string; libsqlId: string;
@@ -96,31 +69,18 @@ export const ShowExternalLibsqlCredentials = ({ libsqlId }: Props) => {
const [connectionGRPCUrl, setGRPCConnectionUrl] = useState(""); const [connectionGRPCUrl, setGRPCConnectionUrl] = useState("");
const getIp = data?.server?.ipAddress || ip; const getIp = data?.server?.ipAddress || ip;
const DockerProviderSchema = createDockerProviderSchema(data?.sqldNode); const form = useForm({
type DockerProvider = z.infer<typeof DockerProviderSchema>;
const form = useForm<DockerProvider>({
defaultValues: {}, defaultValues: {},
resolver: zodResolver(DockerProviderSchema), resolver: zodResolver(DockerProviderSchema),
}); });
useEffect(() => { useEffect(() => {
const fieldsToUpdate: Partial<DockerProvider> = {}; if (data) {
form.reset({
if (data?.externalPort !== undefined) { externalPort: data.externalPort,
fieldsToUpdate.externalPort = data.externalPort; externalGRPCPort: data.externalGRPCPort,
} externalAdminPort: data.externalAdminPort,
});
if (data?.externalGRPCPort !== undefined) {
fieldsToUpdate.externalGRPCPort = data.externalGRPCPort;
}
if (data?.externalAdminPort !== undefined) {
fieldsToUpdate.externalAdminPort = data.externalAdminPort;
}
if (Object.keys(fieldsToUpdate).length > 0) {
form.reset(fieldsToUpdate);
} }
}, [form.reset, data, form]); }, [form.reset, data, form]);
@@ -135,168 +95,157 @@ export const ShowExternalLibsqlCredentials = ({ libsqlId }: Props) => {
toast.success("External port/ports updated"); toast.success("External port/ports updated");
await refetch(); await refetch();
}) })
.catch(() => { .catch((error: Error) => {
toast.error("Error saving the external port/ports"); toast.error(error?.message || "Error saving the external port/ports");
}); });
}; };
useEffect(() => { useEffect(() => {
const buildConnectionUrl = () => { const port = form.watch("externalPort") || data?.externalPort;
const port = form.watch("externalPort") || data?.externalPort; setConnectionUrl(
`http://${data?.databaseUser}:${data?.databasePassword}@${getIp}:${port}`,
);
return `http://${data?.databaseUser}:${data?.databasePassword}@${getIp}:${port}`; if (data?.sqldNode !== "replica") {
}; const grpcPort =
form.watch("externalGRPCPort") || data?.externalGRPCPort;
setConnectionUrl(buildConnectionUrl()); setGRPCConnectionUrl(
`http://${data?.databaseUser}:${data?.databasePassword}@${getIp}:${grpcPort}`,
const buildGRPCConnectionUrl = () => { );
if (data?.sqldNode === "replica") return ""; }
const port = form.watch("externalGRPCPort") || data?.externalGRPCPort; }, [data?.externalGRPCPort, data?.databasePassword, form, data?.databaseUser, getIp]);
return `http://${data?.databaseUser}:${data?.databasePassword}@${getIp}:${port}`;
};
setGRPCConnectionUrl(buildGRPCConnectionUrl());
}, [
data?.appName,
data?.externalGRPCPort,
data?.databasePassword,
form,
data?.databaseUser,
getIp,
]);
return ( return (
<> <div className="flex w-full flex-col gap-5">
<div className="flex w-full flex-col gap-5 "> <Card className="bg-background">
<Card className="bg-background"> <CardHeader>
<CardHeader> <CardTitle className="text-xl">External Credentials</CardTitle>
<CardTitle className="text-xl">External Credentials</CardTitle> <CardDescription>
<CardDescription> In order to make the database reachable through the internet, you
In order to make the database reachable through the internet, you must set a port and ensure that the port is not being used by
must set a port and ensure that the port is not being used by another application or database
another application or database </CardDescription>
</CardDescription> </CardHeader>
</CardHeader> <CardContent className="flex w-full flex-col gap-4">
<CardContent className="flex w-full flex-col gap-4"> {!getIp && (
{!getIp && ( <AlertBlock type="warning">
<AlertBlock type="warning"> You need to set an IP address in your{" "}
You need to set an IP address in your{" "} <Link
<Link href="/dashboard/settings/server"
href="/dashboard/settings/server" className="text-primary"
className="text-primary"
>
{data?.serverId
? "Remote Servers -> Server -> Edit Server -> Update IP Address"
: "Web Server -> Server -> Update Server IP"}
</Link>{" "}
to fix the database url connection.
</AlertBlock>
)}
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="flex flex-col gap-4"
> >
<div className="grid md:grid-cols-2 gap-4 "> {data?.serverId
<div className="md:col-span-2 space-y-4"> ? "Remote Servers -> Server -> Edit Server -> Update IP Address"
<FormField : "Web Server -> Server -> Update Server IP"}
control={form.control} </Link>{" "}
name="externalPort" to fix the database url connection.
render={({ field }) => { </AlertBlock>
return ( )}
<FormItem> <Form {...form}>
<FormLabel>External Port (Internet)</FormLabel> <form
<FormControl> onSubmit={form.handleSubmit(onSubmit)}
<Input className="flex flex-col gap-4"
placeholder="8080" >
{...field} <div className="grid grid-cols-2 gap-4">
value={field.value || ""} <div className="col-span-2 space-y-4">
/> <FormField
</FormControl> control={form.control}
<FormMessage /> name="externalPort"
</FormItem> render={({ field }) => (
); <FormItem>
}} <FormLabel>External Port (Internet)</FormLabel>
/> <FormControl>
<Input
placeholder="8080"
{...field}
value={field.value as string}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
</div>
{!!data?.externalPort && (
<div className="grid w-full gap-8">
<div className="flex flex-col gap-3">
<Label>External Host</Label>
<ToggleVisibilityInput value={connectionUrl} disabled />
</div> </div>
{!!data?.externalPort && ( </div>
<div className="md:col-span-2"> )}
<Label>External Host</Label>
<ToggleVisibilityInput value={connectionUrl} disabled /> <div className="grid grid-cols-2 gap-4">
</div> <div className="col-span-2 space-y-4">
)} <FormField
<div className="md:col-span-2 space-y-4"> control={form.control}
<FormField name="externalAdminPort"
control={form.control} render={({ field }) => (
name="externalAdminPort" <FormItem>
render={({ field }) => { <FormLabel>External Admin Port (Internet)</FormLabel>
return ( <FormControl>
<Input
placeholder="5000"
{...field}
value={field.value as string}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
</div>
{data?.sqldNode !== "replica" && (
<>
<div className="grid grid-cols-2 gap-4">
<div className="col-span-2 space-y-4">
<FormField
control={form.control}
name="externalGRPCPort"
render={({ field }) => (
<FormItem> <FormItem>
<FormLabel> <FormLabel>
External Admin Port (Internet) External GRPC Port (Internet)
</FormLabel> </FormLabel>
<FormControl> <FormControl>
<Input <Input
placeholder="5000" placeholder="5001"
{...field} {...field}
value={field.value || ""} value={field.value as string}
/> />
</FormControl> </FormControl>
<FormMessage /> <FormMessage />
</FormItem> </FormItem>
); )}
}} />
/> </div>
</div> </div>
{data?.sqldNode !== "replica" && ( {!!data?.externalGRPCPort && (
<> <div className="grid w-full gap-8">
<div className="md:col-span-2 space-y-4"> <div className="flex flex-col gap-3">
<FormField <Label>External GRPC Host</Label>
control={form.control} <ToggleVisibilityInput
name="externalGRPCPort" value={connectionGRPCUrl}
render={({ field }) => { disabled
return (
<FormItem>
<FormLabel>
External GRPC Port (Internet)
</FormLabel>
<FormControl>
<Input
placeholder="5001"
{...field}
value={field.value || ""}
/>
</FormControl>
<FormMessage />
</FormItem>
);
}}
/> />
</div> </div>
{!!data?.externalGRPCPort && ( </div>
<div className="md:col-span-2">
<Label>External GRPC Host</Label>
<ToggleVisibilityInput
value={connectionGRPCUrl}
disabled
/>
</div>
)}
</>
)} )}
</div> </>
)}
<div className="flex justify-end"> <div className="flex justify-end">
<Button type="submit" isLoading={isPending}> <Button type="submit" isLoading={isPending}>
Save Save
</Button> </Button>
</div> </div>
</form> </form>
</Form> </Form>
</CardContent> </CardContent>
</Card> </Card>
</div> </div>
</>
); );
}; };
@@ -1,4 +1,4 @@
import { zodResolver } from "@hookform/resolvers/zod"; import { standardSchemaResolver as zodResolver } from "@hookform/resolvers/standard-schema";
import { PenBoxIcon } from "lucide-react"; import { PenBoxIcon } from "lucide-react";
import { useEffect } from "react"; import { useEffect } from "react";
import { useForm } from "react-hook-form"; import { useForm } from "react-hook-form";
+168 -165
View File
@@ -1,6 +1,5 @@
import { import {
addNewService, checkPortInUse,
checkServiceAccess,
createLibsql, createLibsql,
createMount, createMount,
deployLibsql, deployLibsql,
@@ -17,11 +16,16 @@ import {
stopServiceRemote, stopServiceRemote,
updateLibsqlById, updateLibsqlById,
} from "@dokploy/server"; } from "@dokploy/server";
import {
addNewService,
checkServiceAccess,
checkServicePermissionAndAccess,
} from "@dokploy/server/services/permission";
import { TRPCError } from "@trpc/server"; import { TRPCError } from "@trpc/server";
import { observable } from "@trpc/server/observable";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
import { z } from "zod"; import { z } from "zod";
import { createTRPCRouter, protectedProcedure } from "@/server/api/trpc"; import { createTRPCRouter, protectedProcedure } from "@/server/api/trpc";
import { audit } from "@/server/api/utils/audit";
import { db } from "@/server/db"; import { db } from "@/server/db";
import { import {
apiChangeLibsqlStatus, apiChangeLibsqlStatus,
@@ -40,18 +44,10 @@ export const libsqlRouter = createTRPCRouter({
.input(apiCreateLibsql) .input(apiCreateLibsql)
.mutation(async ({ input, ctx }) => { .mutation(async ({ input, ctx }) => {
try { try {
// Get project from environment
const environment = await findEnvironmentById(input.environmentId); const environment = await findEnvironmentById(input.environmentId);
const project = await findProjectById(environment.projectId); const project = await findProjectById(environment.projectId);
if (ctx.user.role === "member") { await checkServiceAccess(ctx, project.projectId, "create");
await checkServiceAccess(
ctx.user.id,
project.projectId,
ctx.session.activeOrganizationId,
"create",
);
}
if (IS_CLOUD && !input.serverId) { if (IS_CLOUD && !input.serverId) {
throw new TRPCError({ throw new TRPCError({
@@ -69,13 +65,7 @@ export const libsqlRouter = createTRPCRouter({
const newLibsql = await createLibsql({ const newLibsql = await createLibsql({
...input, ...input,
}); });
if (ctx.user.role === "member") { await addNewService(ctx, newLibsql.libsqlId);
await addNewService(
ctx.user.id,
newLibsql.libsqlId,
project.organizationId,
);
}
await createMount({ await createMount({
serviceId: newLibsql.libsqlId, serviceId: newLibsql.libsqlId,
@@ -85,25 +75,22 @@ export const libsqlRouter = createTRPCRouter({
type: "volume", type: "volume",
}); });
await audit(ctx, {
action: "create",
resourceType: "service",
resourceId: newLibsql.libsqlId,
resourceName: newLibsql.appName,
});
return true; return true;
} catch (error) { } catch (error) {
if (error instanceof TRPCError) {
throw error;
}
throw error; throw error;
} }
}), }),
one: protectedProcedure one: protectedProcedure
.input(apiFindOneLibsql) .input(apiFindOneLibsql)
.query(async ({ input, ctx }) => { .query(async ({ input, ctx }) => {
if (ctx.user.role === "member") { await checkServiceAccess(ctx, input.libsqlId, "read");
await checkServiceAccess(
ctx.user.id,
input.libsqlId,
ctx.session.activeOrganizationId,
"access",
);
}
const libsql = await findLibsqlById(input.libsqlId); const libsql = await findLibsqlById(input.libsqlId);
if ( if (
libsql.environment.project.organizationId !== libsql.environment.project.organizationId !==
@@ -120,30 +107,34 @@ export const libsqlRouter = createTRPCRouter({
start: protectedProcedure start: protectedProcedure
.input(apiFindOneLibsql) .input(apiFindOneLibsql)
.mutation(async ({ input, ctx }) => { .mutation(async ({ input, ctx }) => {
const service = await findLibsqlById(input.libsqlId); await checkServicePermissionAndAccess(ctx, input.libsqlId, {
if ( deployment: ["create"],
service.environment.project.organizationId !== });
ctx.session.activeOrganizationId const libsql = await findLibsqlById(input.libsqlId);
) {
throw new TRPCError({ if (libsql.serverId) {
code: "UNAUTHORIZED", await startServiceRemote(libsql.serverId, libsql.appName);
message: "You are not authorized to start this Libsql",
});
}
if (service.serverId) {
await startServiceRemote(service.serverId, service.appName);
} else { } else {
await startService(service.appName); await startService(libsql.appName);
} }
await updateLibsqlById(input.libsqlId, { await updateLibsqlById(input.libsqlId, {
applicationStatus: "done", applicationStatus: "done",
}); });
return service; await audit(ctx, {
action: "start",
resourceType: "service",
resourceId: libsql.libsqlId,
resourceName: libsql.appName,
});
return libsql;
}), }),
stop: protectedProcedure stop: protectedProcedure
.input(apiFindOneLibsql) .input(apiFindOneLibsql)
.mutation(async ({ input }) => { .mutation(async ({ input, ctx }) => {
await checkServicePermissionAndAccess(ctx, input.libsqlId, {
deployment: ["create"],
});
const libsql = await findLibsqlById(input.libsqlId); const libsql = await findLibsqlById(input.libsqlId);
if (libsql.serverId) { if (libsql.serverId) {
@@ -155,49 +146,77 @@ export const libsqlRouter = createTRPCRouter({
applicationStatus: "idle", applicationStatus: "idle",
}); });
await audit(ctx, {
action: "stop",
resourceType: "service",
resourceId: libsql.libsqlId,
resourceName: libsql.appName,
});
return libsql; return libsql;
}), }),
saveExternalPorts: protectedProcedure saveExternalPorts: protectedProcedure
.input(apiSaveExternalPortsLibsql) .input(apiSaveExternalPortsLibsql)
.mutation(async ({ input, ctx }) => { .mutation(async ({ input, ctx }) => {
await checkServicePermissionAndAccess(ctx, input.libsqlId, {
service: ["create"],
});
const libsql = await findLibsqlById(input.libsqlId); const libsql = await findLibsqlById(input.libsqlId);
if (
libsql.environment.project.organizationId !==
ctx.session.activeOrganizationId
) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "You are not authorized to save this external port",
});
}
if (libsql.sqldNode === "replica" && input.externalGRPCPort !== null) { if (libsql.sqldNode === "replica" && input.externalGRPCPort !== null) {
throw new TRPCError({ throw new TRPCError({
code: "BAD_REQUEST", code: "BAD_REQUEST",
message: "externalGRPCPort cannot be set when sqldNode is 'replica'", message: "externalGRPCPort cannot be set when sqldNode is 'replica'",
}); });
} }
const portsToCheck = [
{ port: input.externalPort, name: "externalPort", current: libsql.externalPort },
{ port: input.externalGRPCPort, name: "externalGRPCPort", current: libsql.externalGRPCPort },
{ port: input.externalAdminPort, name: "externalAdminPort", current: libsql.externalAdminPort },
];
for (const { port, name, current } of portsToCheck) {
if (port && port !== current) {
const portCheck = await checkPortInUse(
port,
libsql.serverId || undefined,
);
if (portCheck.isInUse) {
throw new TRPCError({
code: "CONFLICT",
message: `Port ${port} (${name}) is already in use by ${portCheck.conflictingContainer}`,
});
}
}
}
await updateLibsqlById(input.libsqlId, { await updateLibsqlById(input.libsqlId, {
externalPort: input.externalPort, externalPort: input.externalPort,
externalGRPCPort: input.externalGRPCPort, externalGRPCPort: input.externalGRPCPort,
externalAdminPort: input.externalAdminPort, externalAdminPort: input.externalAdminPort,
}); });
await deployLibsql(input.libsqlId); await deployLibsql(input.libsqlId);
await audit(ctx, {
action: "update",
resourceType: "service",
resourceId: libsql.libsqlId,
resourceName: libsql.appName,
});
return libsql; return libsql;
}), }),
deploy: protectedProcedure deploy: protectedProcedure
.input(apiDeployLibsql) .input(apiDeployLibsql)
.mutation(async ({ input, ctx }) => { .mutation(async ({ input, ctx }) => {
await checkServicePermissionAndAccess(ctx, input.libsqlId, {
deployment: ["create"],
});
const libsql = await findLibsqlById(input.libsqlId); const libsql = await findLibsqlById(input.libsqlId);
if ( await audit(ctx, {
libsql.environment.project.organizationId !== action: "deploy",
ctx.session.activeOrganizationId resourceType: "service",
) { resourceId: libsql.libsqlId,
throw new TRPCError({ resourceName: libsql.appName,
code: "UNAUTHORIZED", });
message: "You are not authorized to deploy this Libsql",
});
}
return deployLibsql(input.libsqlId); return deployLibsql(input.libsqlId);
}), }),
deployWithLogs: protectedProcedure deployWithLogs: protectedProcedure
@@ -210,55 +229,54 @@ export const libsqlRouter = createTRPCRouter({
}, },
}) })
.input(apiDeployLibsql) .input(apiDeployLibsql)
.subscription(async ({ input, ctx }) => { .subscription(async function* ({ input, ctx, signal }) {
const libsql = await findLibsqlById(input.libsqlId); await checkServicePermissionAndAccess(ctx, input.libsqlId, {
if ( deployment: ["create"],
libsql.environment.project.organizationId !==
ctx.session.activeOrganizationId
) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "You are not authorized to deploy this Libsql",
});
}
return observable<string>((emit) => {
deployLibsql(input.libsqlId, (log) => {
emit.next(log);
});
}); });
const queue: string[] = [];
const done = false;
deployLibsql(input.libsqlId, (log) => {
queue.push(log);
});
while (!done || queue.length > 0) {
if (queue.length > 0) {
yield queue.shift()!;
} else {
await new Promise((r) => setTimeout(r, 50));
}
if (signal?.aborted) {
return;
}
}
}), }),
changeStatus: protectedProcedure changeStatus: protectedProcedure
.input(apiChangeLibsqlStatus) .input(apiChangeLibsqlStatus)
.mutation(async ({ input, ctx }) => { .mutation(async ({ input, ctx }) => {
await checkServicePermissionAndAccess(ctx, input.libsqlId, {
deployment: ["create"],
});
const libsql = await findLibsqlById(input.libsqlId); const libsql = await findLibsqlById(input.libsqlId);
if (
libsql.environment.project.organizationId !==
ctx.session.activeOrganizationId
) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "You are not authorized to change this Libsql status",
});
}
await updateLibsqlById(input.libsqlId, { await updateLibsqlById(input.libsqlId, {
applicationStatus: input.applicationStatus, applicationStatus: input.applicationStatus,
}); });
await audit(ctx, {
action: "update",
resourceType: "service",
resourceId: libsql.libsqlId,
resourceName: libsql.appName,
});
return libsql; return libsql;
}), }),
remove: protectedProcedure remove: protectedProcedure
.input(apiFindOneLibsql) .input(apiFindOneLibsql)
.mutation(async ({ input, ctx }) => { .mutation(async ({ input, ctx }) => {
if (ctx.user.role === "member") { await checkServiceAccess(ctx, input.libsqlId, "delete");
await checkServiceAccess(
ctx.user.id,
input.libsqlId,
ctx.session.activeOrganizationId,
"delete",
);
}
const libsql = await findLibsqlById(input.libsqlId); const libsql = await findLibsqlById(input.libsqlId);
if ( if (
libsql.environment.project.organizationId !== libsql.environment.project.organizationId !==
ctx.session.activeOrganizationId ctx.session.activeOrganizationId
@@ -268,7 +286,12 @@ export const libsqlRouter = createTRPCRouter({
message: "You are not authorized to delete this Libsql", message: "You are not authorized to delete this Libsql",
}); });
} }
await audit(ctx, {
action: "delete",
resourceType: "service",
resourceId: libsql.libsqlId,
resourceName: libsql.appName,
});
const cleanupOperations = [ const cleanupOperations = [
async () => await removeService(libsql?.appName, libsql.serverId), async () => await removeService(libsql?.appName, libsql.serverId),
async () => await removeLibsqlById(input.libsqlId), async () => await removeLibsqlById(input.libsqlId),
@@ -285,16 +308,9 @@ export const libsqlRouter = createTRPCRouter({
saveEnvironment: protectedProcedure saveEnvironment: protectedProcedure
.input(apiSaveEnvironmentVariablesLibsql) .input(apiSaveEnvironmentVariablesLibsql)
.mutation(async ({ input, ctx }) => { .mutation(async ({ input, ctx }) => {
const libsql = await findLibsqlById(input.libsqlId); await checkServicePermissionAndAccess(ctx, input.libsqlId, {
if ( envVars: ["write"],
libsql.environment.project.organizationId !== });
ctx.session.activeOrganizationId
) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "You are not authorized to save this environment",
});
}
const service = await updateLibsqlById(input.libsqlId, { const service = await updateLibsqlById(input.libsqlId, {
env: input.env, env: input.env,
}); });
@@ -306,21 +322,20 @@ export const libsqlRouter = createTRPCRouter({
}); });
} }
await audit(ctx, {
action: "update",
resourceType: "service",
resourceId: input.libsqlId,
});
return true; return true;
}), }),
reload: protectedProcedure reload: protectedProcedure
.input(apiResetLibsql) .input(apiResetLibsql)
.mutation(async ({ input, ctx }) => { .mutation(async ({ input, ctx }) => {
await checkServicePermissionAndAccess(ctx, input.libsqlId, {
deployment: ["create"],
});
const libsql = await findLibsqlById(input.libsqlId); const libsql = await findLibsqlById(input.libsqlId);
if (
libsql.environment.project.organizationId !==
ctx.session.activeOrganizationId
) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "You are not authorized to reload this Libsql",
});
}
if (libsql.serverId) { if (libsql.serverId) {
await stopServiceRemote(libsql.serverId, libsql.appName); await stopServiceRemote(libsql.serverId, libsql.appName);
} else { } else {
@@ -338,33 +353,38 @@ export const libsqlRouter = createTRPCRouter({
await updateLibsqlById(input.libsqlId, { await updateLibsqlById(input.libsqlId, {
applicationStatus: "done", applicationStatus: "done",
}); });
await audit(ctx, {
action: "reload",
resourceType: "service",
resourceId: libsql.libsqlId,
resourceName: libsql.appName,
});
return true; return true;
}), }),
update: protectedProcedure update: protectedProcedure
.input(apiUpdateLibsql) .input(apiUpdateLibsql)
.mutation(async ({ input, ctx }) => { .mutation(async ({ input, ctx }) => {
const { libsqlId, ...rest } = input; const { libsqlId, ...rest } = input;
const libsql = await findLibsqlById(libsqlId); await checkServicePermissionAndAccess(ctx, libsqlId, {
if ( service: ["create"],
libsql.environment.project.organizationId !== });
ctx.session.activeOrganizationId const libsql = await updateLibsqlById(libsqlId, {
) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "You are not authorized to update this Libsql",
});
}
const service = await updateLibsqlById(libsqlId, {
...rest, ...rest,
}); });
if (!service) { if (!libsql) {
throw new TRPCError({ throw new TRPCError({
code: "BAD_REQUEST", code: "BAD_REQUEST",
message: "Update: Error updating Libsql", message: "Error updating Libsql",
}); });
} }
await audit(ctx, {
action: "update",
resourceType: "service",
resourceId: libsqlId,
resourceName: libsql.appName,
});
return true; return true;
}), }),
move: protectedProcedure move: protectedProcedure
@@ -375,31 +395,10 @@ export const libsqlRouter = createTRPCRouter({
}), }),
) )
.mutation(async ({ input, ctx }) => { .mutation(async ({ input, ctx }) => {
const libsql = await findLibsqlById(input.libsqlId); await checkServicePermissionAndAccess(ctx, input.libsqlId, {
if ( service: ["create"],
libsql.environment.project.organizationId !== });
ctx.session.activeOrganizationId
) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "You are not authorized to move this libsql",
});
}
const targetEnvironment = await findEnvironmentById(
input.targetEnvironmentId,
);
if (
targetEnvironment.project.organizationId !==
ctx.session.activeOrganizationId
) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "You are not authorized to move to this environment",
});
}
// Update the libsql's projectId
const updatedLibsql = await db const updatedLibsql = await db
.update(libsqlTable) .update(libsqlTable)
.set({ .set({
@@ -416,23 +415,27 @@ export const libsqlRouter = createTRPCRouter({
}); });
} }
await audit(ctx, {
action: "move",
resourceType: "service",
resourceId: updatedLibsql.libsqlId,
resourceName: updatedLibsql.appName,
});
return updatedLibsql; return updatedLibsql;
}), }),
rebuild: protectedProcedure rebuild: protectedProcedure
.input(apiRebuildLibsql) .input(apiRebuildLibsql)
.mutation(async ({ input, ctx }) => { .mutation(async ({ input, ctx }) => {
const libsql = await findLibsqlById(input.libsqlId); await checkServicePermissionAndAccess(ctx, input.libsqlId, {
if ( deployment: ["create"],
libsql.environment.project.organizationId !== });
ctx.session.activeOrganizationId
) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "You are not authorized to rebuild this MariaDB database",
});
}
await rebuildDatabase(libsql.libsqlId, "libsql"); await rebuildDatabase(input.libsqlId, "libsql");
await audit(ctx, {
action: "rebuild",
resourceType: "service",
resourceId: input.libsqlId,
});
return true; return true;
}), }),
}); });
+23 -26
View File
@@ -96,15 +96,6 @@ const createSchema = createInsertSchema(mounts, {
mountPath: z.string().min(1), mountPath: z.string().min(1),
mountId: z.string().optional(), mountId: z.string().optional(),
filePath: z.string().optional(), filePath: z.string().optional(),
serviceType: z.enum([
"application",
"postgres",
"mysql",
"mariadb",
"mongo",
"redis",
"compose",
]),
}); });
export const apiCreateMount = createSchema export const apiCreateMount = createSchema
@@ -118,6 +109,16 @@ export const apiCreateMount = createSchema
}) })
.extend({ .extend({
serviceId: z.string().min(1), serviceId: z.string().min(1),
serviceType: z.enum([
"application",
"postgres",
"mysql",
"mariadb",
"mongo",
"redis",
"compose",
"libsql",
]),
}); });
export const apiFindOneMount = z.object({ export const apiFindOneMount = z.object({
@@ -133,23 +134,19 @@ export const apiRemoveMount = createSchema
// }) // })
.required(); .required();
export const apiFindMountByApplicationId = createSchema export const apiFindMountByApplicationId = z.object({
.extend({ serviceId: z.string().min(1),
serviceId: z.string().min(1), serviceType: z.enum([
serviceType: z.enum([ "application",
"application", "postgres",
"postgres", "mysql",
"mysql", "mariadb",
"mariadb", "mongo",
"mongo", "redis",
"redis", "compose",
"compose", "libsql",
]), ]),
}) });
.pick({
serviceId: true,
serviceType: true,
});
export const apiUpdateMount = createSchema.partial().extend({ export const apiUpdateMount = createSchema.partial().extend({
mountId: z.string().min(1), mountId: z.string().min(1),