Skip to content

A fully open source & end-to-end encrypted note taking alternative to Evernote.

server(themes): harden sync endpoint and input handling

Abdullah Attabf3980f0c523
diff --git a/servers/themes/src/api.ts b/servers/themes/src/api.ts
index 2c96e41e0..fd2ea2e1b 100644
--- a/servers/themes/src/api.ts
+++ b/servers/themes/src/api.ts
@@ -24,6 +24,8 @@ import { syncThemes } from "./sync";
import { publicProcedure, router } from "./trpc";
import { THEME_COMPATIBILITY_VERSION } from "@notesnook/theme";
import { ThemeQuerySchema } from "./schemas";
+import { TRPCError } from "@trpc/server";
+import { SYNC_TOKEN } from "./constants";
export const ThemesAPI = router({
themes: publicProcedure.input(ThemeQuerySchema).query(async ({ input }) => {
@@ -61,8 +63,10 @@ export const ThemesAPI = router({
const theme = await findTheme(id, compatibilityVersion);
if (theme && theme.version !== version) return theme;
}),
- sync: publicProcedure.query(() => {
- syncThemes();
+ sync: publicProcedure.query(({ ctx }) => {
+ if (SYNC_TOKEN && ctx.authorization !== `Bearer ${SYNC_TOKEN}`)
+ throw new TRPCError({ code: "UNAUTHORIZED" });
+ syncThemes().catch((e) => console.error("Failed to sync themes:", e));
return true;
}),
health: publicProcedure.query(() => {
diff --git a/servers/themes/src/constants.ts b/servers/themes/src/constants.ts
index 2d49ac323..67d20530d 100644
--- a/servers/themes/src/constants.ts
+++ b/servers/themes/src/constants.ts
@@ -26,9 +26,12 @@ import { KVCounter } from "./counter/kv";
const env = readSecrets([
"CLOUDFLARE_ACCOUNT_ID",
"CLOUDFLARE_AUTH_TOKEN",
- "CLOUDFLARE_INSTALLS_KV_NAMESPACE_ID"
+ "CLOUDFLARE_INSTALLS_KV_NAMESPACE_ID",
+ "THEMES_SYNC_TOKEN"
]);
+export const SYNC_TOKEN = env.THEMES_SYNC_TOKEN;
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export const THEMES_REPO_URL =
diff --git a/servers/themes/src/schemas.ts b/servers/themes/src/schemas.ts
index bf1c16aa9..c4a843b89 100644
--- a/servers/themes/src/schemas.ts
+++ b/servers/themes/src/schemas.ts
@@ -29,7 +29,7 @@ export const ThemeQuerySchema = z.object({
})
)
.optional(),
- limit: z.number(),
- cursor: z.number().default(0),
+ limit: z.number().int().min(1).max(100),
+ cursor: z.number().int().min(0).default(0),
compatibilityVersion: z.number().default(THEME_COMPATIBILITY_VERSION)
});
diff --git a/servers/themes/src/secrets.ts b/servers/themes/src/secrets.ts
index b86f490cc..cf068ec62 100644
--- a/servers/themes/src/secrets.ts
+++ b/servers/themes/src/secrets.ts
@@ -35,6 +35,6 @@ export function readSecret(name: string): string | undefined {
if (value) return value;
const file = process.env[`${name}_FILE`];
if (file) {
- return readFileSync(file, "utf-8");
+ return readFileSync(file, "utf-8").trim();
}
}
diff --git a/servers/themes/src/server.ts b/servers/themes/src/server.ts
index 282f8b058..4a5f37e29 100644
--- a/servers/themes/src/server.ts
+++ b/servers/themes/src/server.ts
@@ -21,10 +21,12 @@ import { createHTTPServer } from "@trpc/server/adapters/standalone";
import { ThemesAPI } from "./api";
import { syncThemes } from "./sync";
import cors from "cors";
+import { createContext } from "./trpc";
const server = createHTTPServer({
middleware: cors(),
- router: ThemesAPI
+ router: ThemesAPI,
+ createContext
});
const PORT = parseInt(process.env.PORT || "9000");
const HOST = process.env.HOST || "localhost";
diff --git a/servers/themes/src/sync.ts b/servers/themes/src/sync.ts
index 5c1e9e65c..24f4f4d64 100644
--- a/servers/themes/src/sync.ts
+++ b/servers/themes/src/sync.ts
@@ -16,7 +16,8 @@ GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-import { execSync } from "child_process";
+import { execFile } from "child_process";
+import { promisify } from "util";
import fs from "node:fs";
import { readdir, readFile } from "fs/promises";
import path from "path";
@@ -47,18 +48,32 @@ export type ThemeMetadata = Omit<
const THEME_COMPATIBILITY_VERSIONS: ThemeCompatibilityVersion[] = [1];
-export async function syncThemes() {
+const execFileAsync = promisify(execFile);
+const GIT_TIMEOUT = 60 * 1000;
+let currentSync: Promise<void> | undefined;
+
+export function syncThemes() {
+ // concurrent git pulls fail on index.lock, so piggyback on the running sync
+ if (!currentSync)
+ currentSync = sync().finally(() => (currentSync = undefined));
+ return currentSync;
+}
+
+async function git(args: string[], cwd: string) {
+ const { stdout, stderr } = await execFileAsync("git", args, {
+ cwd,
+ timeout: GIT_TIMEOUT
+ });
+ if (stderr.trim()) console.log(stderr.trim());
+ if (stdout.trim()) console.log(stdout.trim());
+}
+
+async function sync() {
if (!fs.existsSync(THEME_REPO_DIR_PATH)) {
- execSync(`git clone ${THEMES_REPO_URL}`, {
- stdio: [0, 1, 2],
- cwd: path.dirname(THEME_REPO_DIR_PATH)
- });
+ await git(["clone", THEMES_REPO_URL], path.dirname(THEME_REPO_DIR_PATH));
console.log(`Cloned github repo to path ${THEME_REPO_DIR_PATH}`);
} else {
- execSync(`git pull`, {
- stdio: [0, 1, 2],
- cwd: THEME_REPO_DIR_PATH
- });
+ await git(["pull"], THEME_REPO_DIR_PATH);
console.log(`Synced github repo ${THEMES_REPO_URL}`);
}
await generateThemesMetadata();
diff --git a/servers/themes/src/trpc.ts b/servers/themes/src/trpc.ts
index c76d638f5..6e387a974 100644
--- a/servers/themes/src/trpc.ts
+++ b/servers/themes/src/trpc.ts
@@ -18,12 +18,17 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { initTRPC } from "@trpc/server";
+import type { CreateHTTPContextOptions } from "@trpc/server/adapters/standalone";
/**
* Initialization of tRPC backend
* Should be done only once per backend!
*/
-const t = initTRPC.create();
+export function createContext({ req }: CreateHTTPContextOptions) {
+ return { authorization: req.headers.authorization };
+}
+
+const t = initTRPC.context<typeof createContext>().create();
/**
* Export reusable router and procedure helpers