Skip to content

Commit

Permalink
Switch to pages functions and remove extra deploy step
Browse files Browse the repository at this point in the history
This should make the site a bit easier to self host since
it only requires a few settings on the dashboard instead.
  • Loading branch information
LostLuma committed May 19, 2022
1 parent 54eefc4 commit 8b9c803
Show file tree
Hide file tree
Showing 12 changed files with 1,765 additions and 485 deletions.
17 changes: 0 additions & 17 deletions .github/workflows/deploy.yaml

This file was deleted.

3 changes: 1 addition & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
dist
.mf
node_modules
worker
2 changes: 1 addition & 1 deletion .prettierrc
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{ "printWidth": 100 }
{ "printWidth": 120 }
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,20 @@

A hastebin-compatible paste site running on Cloudflare Workers.

# Deployment

To deploy as a pages project you will need to set up the following:

KV namespace bindings:

- ``STORAGE``: A KV namespace to storage pastes in

Environment variables:

- ``DOCUMENT_KEY_SIZE``: Number of digits to use for document URLs
- ``MAX_DOCUMENT_SIZE``: Maximum number of characters allowed per paste
- ``DOCUMENT_EXPIRE_TTL``: Number of seconds until documents expire

# TODO

I did not invest any time into creating my own frontend yet, all static
Expand Down
44 changes: 44 additions & 0 deletions functions/_middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
MIT License
Copyright (c) 2019 - 2022 Lilly Rose Berner
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

import { HTTPError } from "..";

export async function onRequest({ next }) {
try {
return await next();
} catch (e) {
if (!(e instanceof HTTPError)) {
throw e;
}

const json = { message: e.message };
const headers = {
"Cache-Control": "no-cache",
"Content-Type": "application/json; charset=UTF-8",
};

const data = JSON.stringify(json);
return new Response(data, { headers, status: e.status });
}
}
41 changes: 41 additions & 0 deletions functions/documents/[id].js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/*
MIT License
Copyright (c) 2019 - 2022 Lilly Rose Berner
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

import { HTTPError } from "../..";

export async function onRequestGet({ params, env }) {
const content = await env.STORAGE.get(`documents:${params.id}`);

if (content) {
const json = { key: params.id, data: content };
const headers = {
"Content-Type": "application/json; charset=UTF-8",
};

const data = JSON.stringify(json);
return new Response(data, { headers, status: 200 });
}

throw new HTTPError(404, `Document "${params.id}" not found.`);
}
66 changes: 66 additions & 0 deletions functions/documents/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
MIT License
Copyright (c) 2019 - 2022 Lilly Rose Berner
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

import { HTTPError } from "../..";

function generateId(size) {
let id = "";
const keyspace = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

for (let idx = 0; idx < size; idx++) {
id += keyspace.charAt(Math.random() * keyspace.length);
}

return id;
}

export async function onRequestPost({ request, env }) {
const length = Number(request.headers.get("Content-Length") || 0);

if (!length) {
throw new HTTPError(400, "Content must contain at least one character.");
}

if (length > env.MAX_DOCUMENT_SIZE) {
throw new HTTPError(400, `Content must be shorter than ${env.MAX_DOCUMENT_SIZE} characters (was ${length}).`);
}

const content = await request.text();
const id = generateId(env.DOCUMENT_KEY_SIZE);

await env.STORAGE.put(`documents:${id}`, content, { expirationTtl: env.DOCUMENT_EXPIRE_TTL });

const domain = new URL(request.url).hostname;

const json = {
key: id,
url: `https://${domain}/${id}`,
};
const headers = {
"Content-Type": "application/json; charset=UTF-8",
};

const data = JSON.stringify(json);
return new Response(data, { headers, status: 200 });
}
38 changes: 38 additions & 0 deletions functions/raw/[id].js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
MIT License
Copyright (c) 2019 - 2022 Lilly Rose Berner
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

import { HTTPError } from "../..";

export async function onRequestGet({ params, env }) {
const content = await env.STORAGE.get(`documents:${params.id}`);

if (content) {
const headers = {
"Content-Type": "text/plain; charset=UTF-8",
};
return new Response(content, { headers, status: 200 });
}

throw new HTTPError(404, `Document "${params.id}" not found.`);
}
111 changes: 1 addition & 110 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,118 +27,9 @@ const DOCUMENT_KEY_SIZE = 6;
const MAX_DOCUMENT_SIZE = 400000;
const DOCUMENT_EXPIRE_TTL = 86400 * 180;

class HTTPError extends Error {
export class HTTPError extends Error {
constructor(status, message) {
super(message);
this.status = status;
}
}

function generateId() {
let id = "";
const keyspace = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

for (let idx = 0; idx < DOCUMENT_KEY_SIZE; idx++) {
id += keyspace.charAt(Math.random() * keyspace.length);
}

return id;
}

async function getRawId(id) {
const content = await STORAGE.get(`documents:${id}`);

if (!content) {
throw new HTTPError(404, `Document "${id}" not found.`);
}

const headers = {
"Content-Type": "text/plain; charset=UTF-8",
};
return new Response(content, { headers, status: 200 });
}

async function postDocuments(request) {
const length = Number(request.headers.get("Content-Length") || 0);

if (!length) {
throw new HTTPError(400, "Content must contain at least one character.");
}

if (length > MAX_DOCUMENT_SIZE) {
throw new HTTPError(400, `Content must be shorter than ${MAX_DOCUMENT_SIZE} (was ${length}).`);
}

const id = generateId();
const content = await request.text();

await STORAGE.put(`documents:${id}`, content, { expirationTtl: DOCUMENT_EXPIRE_TTL });

const json = {
key: id,
url: `https://starb.in/${id}`,
};
const headers = {
"Content-Type": "application/json; charset=UTF-8",
};

const data = JSON.stringify(json);
return new Response(data, { headers, status: 200 });
}

async function getDocumentsId(id) {
const content = await STORAGE.get(`documents:${id}`);

if (!content) {
throw new HTTPError(404, `Document "${id}" not found.`);
}

const json = { key: id, data: content };
const headers = {
"Content-Type": "application/json; charset=UTF-8",
};

const data = JSON.stringify(json);
return new Response(data, { headers, status: 200 });
}

async function handleRequest({ request }) {
const { method, url } = request;
const { host, pathname } = new URL(url);

const match = /^\/(?:documents|raw)\/(\w+)$/.exec(pathname);
const documentId = match ? match[1] : null;

if (method === "GET" && pathname.startsWith("/raw")) {
return await getRawId(documentId);
} else if (method === "GET" && pathname.startsWith("/documents")) {
return await getDocumentsId(documentId);
} else if (method === "POST" && pathname === "/documents") {
return await postDocuments(request);
}

throw new HTTPError(404, "File not found.");
}

async function handleEvent(event) {
try {
return await handleRequest(event);
} catch (e) {
if (!(e instanceof HTTPError)) {
throw e;
}

const json = { message: e.message };
const headers = {
"Cache-Control": "no-cache",
"Content-Type": "application/json; charset=UTF-8",
};

const data = JSON.stringify(json);
return new Response(data, { headers, status: e.status });
}
}

addEventListener("fetch", (event) => {
event.respondWith(handleEvent(event));
});
Loading

0 comments on commit 8b9c803

Please sign in to comment.