DenReg/registry/src/utils.ts

87 lines
2.4 KiB
TypeScript
Raw Normal View History

2020-07-28 12:39:54 +00:00
import { ABC } from "./deps.ts";
import { decode } from "https://deno.land/std/encoding/base64.ts";
import config from "./config.ts";
const packageNameRegex = /^[@]?[a-zA-Z][\d\w\-\_]*$/g.compile();
const packageVersionRegex = /^\d(\.\d)?(\.\d)?$/g.compile();
const packageFullVersionRegex = /^\d(\.\d)(\.\d)$/g.compile();
export const isValidPackageName = (name: string) => packageNameRegex.test(name);
export const isValidVersion = (version: string) =>
packageVersionRegex.test(version);
export const isValidFullVersion = (version: string) =>
packageFullVersionRegex.test(version);
const ALg = 1;
const ASm = -ALg;
const Equ = 0;
export const sortVersions = (a: string, b: string) => {
const [a1, a2, a3] = a.split(".").map(Number);
const [b1, b2, b3] = b.split(".").map(Number);
if (a1 > b1) return ALg;
if (a1 < b1) return ASm;
if (a2 > b2) return ALg;
if (a2 < b2) return ASm;
if (a3 > b3) return ALg;
if (a3 < b3) return ASm;
return Equ;
};
export const basicauth = (realm: string) => (next: ABC.HandlerFunc) => (
ctx: ABC.Context
) => {
const value = ctx.request.headers.get("authorization");
console.log("Header:", value);
if (value && value.toLowerCase().startsWith("basic ")) {
const credentials = value.slice(6);
const [username, passwd] = new TextDecoder()
.decode(decode(credentials))
.split(":", 2);
if (config?.user[username]?.password === passwd) {
console.log("User authenticated!");
return next(ctx);
}
}
console.log("Authentication required");
ctx.response.status = 401;
ctx.response.headers.set("WWW-Authenticate", "Basic realm=" + realm);
return {
statusCode: 401,
error: "Authentication required",
};
};
export function extractPackagePath(path: string): [string, string | undefined] {
let packageName = "";
if (path.startsWith("@")) {
packageName = "@";
path = path.slice(1);
}
let parts = path.split("@");
if (parts.length > 2) throw new Error("Invalid package name!");
packageName += parts[0];
let packageVersion: string | undefined = path[1];
if (!isValidPackageName(packageName))
throw new Error("Invalid package name!");
if (packageVersion !== "") {
if (!isValidVersion(packageVersion))
throw new Error("Invalid package version!");
else packageVersion = undefined;
}
return [packageName, packageVersion];
}