server/api/shares/[uuid]/index.ts
Jesse Wierzbinski cd12ccd6c1
Some checks failed
CodeQL Scan / Analyze (javascript-typescript) (push) Failing after 0s
Build Docker Images / lint (push) Failing after 6s
Build Docker Images / check (push) Failing after 7s
Build Docker Images / tests (push) Failing after 6s
Build Docker Images / build (server, Dockerfile, ${{ github.repository_owner }}/server) (push) Has been skipped
Build Docker Images / build (worker, Worker.Dockerfile, ${{ github.repository_owner }}/worker) (push) Has been skipped
Deploy Docs to GitHub Pages / build (push) Failing after 0s
Deploy Docs to GitHub Pages / Deploy (push) Has been skipped
Mirror to Codeberg / Mirror (push) Failing after 0s
Nix Build / check (push) Failing after 0s
feat(federation): Implement Share federation support
2025-05-02 12:48:47 +02:00

80 lines
2.6 KiB
TypeScript

import { Status as StatusSchema } from "@versia/client/schemas";
import { Note } from "@versia/kit/db";
import { Notes } from "@versia/kit/tables";
import { and, eq, inArray } from "drizzle-orm";
import { describeRoute } from "hono-openapi";
import { resolver, validator } from "hono-openapi/zod";
import { z } from "zod";
import { apiRoute, handleZodError } from "@/api";
import { ApiError } from "~/classes/errors/api-error";
import { config } from "~/config.ts";
import { ShareSchema } from "~/packages/sdk/schemas";
export default apiRoute((app) =>
app.get(
"/shares/:id",
describeRoute({
summary: "Retrieve the Versia representation of a share.",
tags: ["Federation"],
responses: {
200: {
description: "Share",
content: {
"application/json": {
schema: resolver(ShareSchema),
},
},
},
404: {
description:
"Entity not found, is remote, or the requester is not allowed to view it.",
content: {
"application/json": {
schema: resolver(ApiError.zodSchema),
},
},
},
},
}),
validator(
"param",
z.object({
id: StatusSchema.shape.id,
}),
handleZodError,
),
async (context) => {
const { id } = context.req.valid("param");
const note = await Note.fromSql(
and(
eq(Notes.id, id),
inArray(Notes.visibility, ["public", "unlisted"]),
),
);
if (!(note && (await note.isViewableByUser(null))) || note.remote) {
throw ApiError.noteNotFound();
}
// If base_url uses https and request uses http, rewrite request to use https
// This fixes reverse proxy errors
const reqUrl = new URL(context.req.url);
if (
config.http.base_url.protocol === "https:" &&
reqUrl.protocol === "http:"
) {
reqUrl.protocol = "https:";
}
const { headers } = await note.author.sign(
note.toVersiaShare(),
reqUrl,
"GET",
);
return context.json(note.toVersiaShare(), 200, headers.toJSON());
},
),
);