move to private routes

This commit is contained in:
miloschwartz
2026-03-24 20:27:15 -07:00
parent 212b7a104f
commit 3525b367b3
24 changed files with 1054 additions and 103 deletions

View File

@@ -0,0 +1,145 @@
/*
* This file is part of a proprietary work.
*
* Copyright (c) 2025 Fossorial, Inc.
* All rights reserved.
*
* This file is licensed under the Fossorial Commercial License.
* You may not use this file except in compliance with the License.
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
*
* This file is not licensed under the AGPLv3.
*/
import { NextFunction, Request, Response } from "express";
import { db, siteProvisioningKeyOrg, siteProvisioningKeys } from "@server/db";
import HttpCode from "@server/types/HttpCode";
import { z } from "zod";
import { fromError } from "zod-validation-error";
import createHttpError from "http-errors";
import response from "@server/lib/response";
import moment from "moment";
import {
generateId,
generateIdFromEntropySize
} from "@server/auth/sessions/app";
import logger from "@server/logger";
import { hashPassword } from "@server/auth/password";
import type { CreateSiteProvisioningKeyResponse } from "@server/routers/siteProvisioning/types";
const paramsSchema = z.object({
orgId: z.string().nonempty()
});
const bodySchema = z
.strictObject({
name: z.string().min(1).max(255),
maxBatchSize: z.union([
z.null(),
z.coerce.number().int().positive().max(1_000_000)
]),
validUntil: z.string().max(255).optional()
})
.superRefine((data, ctx) => {
const v = data.validUntil;
if (v == null || v.trim() === "") {
return;
}
if (Number.isNaN(Date.parse(v))) {
ctx.addIssue({
code: "custom",
message: "Invalid validUntil",
path: ["validUntil"]
});
}
});
export type CreateSiteProvisioningKeyBody = z.infer<typeof bodySchema>;
export async function createSiteProvisioningKey(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
const parsedParams = paramsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
const parsedBody = bodySchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
);
}
const { orgId } = parsedParams.data;
const { name, maxBatchSize } = parsedBody.data;
const vuRaw = parsedBody.data.validUntil;
const validUntil =
vuRaw == null || vuRaw.trim() === ""
? null
: new Date(Date.parse(vuRaw)).toISOString();
const siteProvisioningKeyId = `spk-${generateId(15)}`;
const siteProvisioningKey = generateIdFromEntropySize(25);
const siteProvisioningKeyHash = await hashPassword(siteProvisioningKey);
const lastChars = siteProvisioningKey.slice(-4);
const createdAt = moment().toISOString();
await db.transaction(async (trx) => {
await trx.insert(siteProvisioningKeys).values({
siteProvisioningKeyId,
name,
siteProvisioningKeyHash,
createdAt,
lastChars,
lastUsed: null,
maxBatchSize,
numUsed: 0,
validUntil
});
await trx.insert(siteProvisioningKeyOrg).values({
siteProvisioningKeyId,
orgId
});
});
try {
return response<CreateSiteProvisioningKeyResponse>(res, {
data: {
siteProvisioningKeyId,
orgId,
name,
siteProvisioningKey,
lastChars,
createdAt,
lastUsed: null,
maxBatchSize,
numUsed: 0,
validUntil
},
success: true,
error: false,
message: "Site provisioning key created",
status: HttpCode.CREATED
});
} catch (e) {
logger.error(e);
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Failed to create site provisioning key"
)
);
}
}

View File

@@ -0,0 +1,129 @@
/*
* This file is part of a proprietary work.
*
* Copyright (c) 2025 Fossorial, Inc.
* All rights reserved.
*
* This file is licensed under the Fossorial Commercial License.
* You may not use this file except in compliance with the License.
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
*
* This file is not licensed under the AGPLv3.
*/
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import {
db,
siteProvisioningKeyOrg,
siteProvisioningKeys
} from "@server/db";
import { and, eq } from "drizzle-orm";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
import { fromError } from "zod-validation-error";
const paramsSchema = z.object({
siteProvisioningKeyId: z.string().nonempty(),
orgId: z.string().nonempty()
});
export async function deleteSiteProvisioningKey(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedParams = paramsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
const { siteProvisioningKeyId, orgId } = parsedParams.data;
const [row] = await db
.select()
.from(siteProvisioningKeys)
.where(
eq(
siteProvisioningKeys.siteProvisioningKeyId,
siteProvisioningKeyId
)
)
.innerJoin(
siteProvisioningKeyOrg,
and(
eq(
siteProvisioningKeys.siteProvisioningKeyId,
siteProvisioningKeyOrg.siteProvisioningKeyId
),
eq(siteProvisioningKeyOrg.orgId, orgId)
)
)
.limit(1);
if (!row) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
`Site provisioning key with ID ${siteProvisioningKeyId} not found`
)
);
}
await db.transaction(async (trx) => {
await trx
.delete(siteProvisioningKeyOrg)
.where(
and(
eq(
siteProvisioningKeyOrg.siteProvisioningKeyId,
siteProvisioningKeyId
),
eq(siteProvisioningKeyOrg.orgId, orgId)
)
);
const siteProvisioningKeyOrgs = await trx
.select()
.from(siteProvisioningKeyOrg)
.where(
eq(
siteProvisioningKeyOrg.siteProvisioningKeyId,
siteProvisioningKeyId
)
);
if (siteProvisioningKeyOrgs.length === 0) {
await trx
.delete(siteProvisioningKeys)
.where(
eq(
siteProvisioningKeys.siteProvisioningKeyId,
siteProvisioningKeyId
)
);
}
});
return response(res, {
data: null,
success: true,
error: false,
message: "Site provisioning key deleted successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}

View File

@@ -0,0 +1,17 @@
/*
* This file is part of a proprietary work.
*
* Copyright (c) 2025 Fossorial, Inc.
* All rights reserved.
*
* This file is licensed under the Fossorial Commercial License.
* You may not use this file except in compliance with the License.
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
*
* This file is not licensed under the AGPLv3.
*/
export * from "./createSiteProvisioningKey";
export * from "./listSiteProvisioningKeys";
export * from "./deleteSiteProvisioningKey";
export * from "./updateSiteProvisioningKey";

View File

@@ -0,0 +1,126 @@
/*
* This file is part of a proprietary work.
*
* Copyright (c) 2025 Fossorial, Inc.
* All rights reserved.
*
* This file is licensed under the Fossorial Commercial License.
* You may not use this file except in compliance with the License.
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
*
* This file is not licensed under the AGPLv3.
*/
import {
db,
siteProvisioningKeyOrg,
siteProvisioningKeys
} from "@server/db";
import logger from "@server/logger";
import HttpCode from "@server/types/HttpCode";
import response from "@server/lib/response";
import { NextFunction, Request, Response } from "express";
import createHttpError from "http-errors";
import { z } from "zod";
import { fromError } from "zod-validation-error";
import { eq } from "drizzle-orm";
import type { ListSiteProvisioningKeysResponse } from "@server/routers/siteProvisioning/types";
const paramsSchema = z.object({
orgId: z.string().nonempty()
});
const querySchema = z.object({
limit: z
.string()
.optional()
.default("1000")
.transform(Number)
.pipe(z.int().positive()),
offset: z
.string()
.optional()
.default("0")
.transform(Number)
.pipe(z.int().nonnegative())
});
function querySiteProvisioningKeys(orgId: string) {
return db
.select({
siteProvisioningKeyId:
siteProvisioningKeys.siteProvisioningKeyId,
orgId: siteProvisioningKeyOrg.orgId,
lastChars: siteProvisioningKeys.lastChars,
createdAt: siteProvisioningKeys.createdAt,
name: siteProvisioningKeys.name,
lastUsed: siteProvisioningKeys.lastUsed,
maxBatchSize: siteProvisioningKeys.maxBatchSize,
numUsed: siteProvisioningKeys.numUsed,
validUntil: siteProvisioningKeys.validUntil
})
.from(siteProvisioningKeyOrg)
.innerJoin(
siteProvisioningKeys,
eq(
siteProvisioningKeys.siteProvisioningKeyId,
siteProvisioningKeyOrg.siteProvisioningKeyId
)
)
.where(eq(siteProvisioningKeyOrg.orgId, orgId));
}
export async function listSiteProvisioningKeys(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedParams = paramsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error)
)
);
}
const parsedQuery = querySchema.safeParse(req.query);
if (!parsedQuery.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedQuery.error)
)
);
}
const { orgId } = parsedParams.data;
const { limit, offset } = parsedQuery.data;
const siteProvisioningKeysList = await querySiteProvisioningKeys(orgId)
.limit(limit)
.offset(offset);
return response<ListSiteProvisioningKeysResponse>(res, {
data: {
siteProvisioningKeys: siteProvisioningKeysList,
pagination: {
total: siteProvisioningKeysList.length,
limit,
offset
}
},
success: true,
error: false,
message: "Site provisioning keys retrieved successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}

View File

@@ -0,0 +1,199 @@
/*
* This file is part of a proprietary work.
*
* Copyright (c) 2025 Fossorial, Inc.
* All rights reserved.
*
* This file is licensed under the Fossorial Commercial License.
* You may not use this file except in compliance with the License.
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
*
* This file is not licensed under the AGPLv3.
*/
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import {
db,
siteProvisioningKeyOrg,
siteProvisioningKeys
} from "@server/db";
import { and, eq } from "drizzle-orm";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
import { fromError } from "zod-validation-error";
import type { UpdateSiteProvisioningKeyResponse } from "@server/routers/siteProvisioning/types";
const paramsSchema = z.object({
siteProvisioningKeyId: z.string().nonempty(),
orgId: z.string().nonempty()
});
const bodySchema = z
.strictObject({
maxBatchSize: z
.union([
z.null(),
z.coerce.number().int().positive().max(1_000_000)
])
.optional(),
validUntil: z.string().max(255).optional()
})
.superRefine((data, ctx) => {
if (
data.maxBatchSize === undefined &&
data.validUntil === undefined
) {
ctx.addIssue({
code: "custom",
message: "Provide maxBatchSize and/or validUntil",
path: ["maxBatchSize"]
});
}
const v = data.validUntil;
if (v == null || v.trim() === "") {
return;
}
if (Number.isNaN(Date.parse(v))) {
ctx.addIssue({
code: "custom",
message: "Invalid validUntil",
path: ["validUntil"]
});
}
});
export type UpdateSiteProvisioningKeyBody = z.infer<typeof bodySchema>;
export async function updateSiteProvisioningKey(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedParams = paramsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
const parsedBody = bodySchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
);
}
const { siteProvisioningKeyId, orgId } = parsedParams.data;
const body = parsedBody.data;
const [row] = await db
.select()
.from(siteProvisioningKeys)
.where(
eq(
siteProvisioningKeys.siteProvisioningKeyId,
siteProvisioningKeyId
)
)
.innerJoin(
siteProvisioningKeyOrg,
and(
eq(
siteProvisioningKeys.siteProvisioningKeyId,
siteProvisioningKeyOrg.siteProvisioningKeyId
),
eq(siteProvisioningKeyOrg.orgId, orgId)
)
)
.limit(1);
if (!row) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
`Site provisioning key with ID ${siteProvisioningKeyId} not found`
)
);
}
const setValues: {
maxBatchSize?: number | null;
validUntil?: string | null;
} = {};
if (body.maxBatchSize !== undefined) {
setValues.maxBatchSize = body.maxBatchSize;
}
if (body.validUntil !== undefined) {
setValues.validUntil =
body.validUntil.trim() === ""
? null
: new Date(Date.parse(body.validUntil)).toISOString();
}
await db
.update(siteProvisioningKeys)
.set(setValues)
.where(
eq(
siteProvisioningKeys.siteProvisioningKeyId,
siteProvisioningKeyId
)
);
const [updated] = await db
.select({
siteProvisioningKeyId:
siteProvisioningKeys.siteProvisioningKeyId,
name: siteProvisioningKeys.name,
lastChars: siteProvisioningKeys.lastChars,
createdAt: siteProvisioningKeys.createdAt,
lastUsed: siteProvisioningKeys.lastUsed,
maxBatchSize: siteProvisioningKeys.maxBatchSize,
numUsed: siteProvisioningKeys.numUsed,
validUntil: siteProvisioningKeys.validUntil
})
.from(siteProvisioningKeys)
.where(
eq(
siteProvisioningKeys.siteProvisioningKeyId,
siteProvisioningKeyId
)
)
.limit(1);
if (!updated) {
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Failed to load updated site provisioning key"
)
);
}
return response<UpdateSiteProvisioningKeyResponse>(res, {
data: {
...updated,
orgId
},
success: true,
error: false,
message: "Site provisioning key updated successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}