Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4594bd2307 | |||
| d8c0052b54 | |||
| 4d1d94296f | |||
| c6800a6144 | |||
| 000e90a617 | |||
| 70e9465b68 | |||
| 8c3e0f9554 |
@@ -14,7 +14,29 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
|
packages: read
|
||||||
steps:
|
steps:
|
||||||
|
- name: Validate tag format
|
||||||
|
run: |
|
||||||
|
TAG="${{ inputs.tag }}"
|
||||||
|
if ! echo "$TAG" | grep -qE '^[0-9]{4}\.[0-9]{2}\.[0-9]{2}-[a-f0-9]{7}$'; then
|
||||||
|
echo "::error::Invalid tag format: '$TAG'. Expected format: YYYY.MM.DD-sha7 (e.g. 2026.03.28-f1b85bf)"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "Tag format valid: $TAG"
|
||||||
|
|
||||||
|
- name: Verify image exists in GHCR
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
run: |
|
||||||
|
TAG="${{ inputs.tag }}"
|
||||||
|
# Check that the API image exists — if API was pushed, web/migrate were too
|
||||||
|
if ! gh api "/orgs/groombook/packages/container/api/versions" --jq ".[].metadata.container.tags[]" 2>/dev/null | grep -qF "$TAG"; then
|
||||||
|
echo "::error::Image ghcr.io/groombook/api:$TAG not found in GHCR. Verify the tag was built and pushed."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "Image verified: ghcr.io/groombook/api:$TAG exists"
|
||||||
|
|
||||||
- name: Generate infra repo token
|
- name: Generate infra repo token
|
||||||
id: infra-token
|
id: infra-token
|
||||||
uses: tibdex/github-app-token@v2
|
uses: tibdex/github-app-token@v2
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ RUN pnpm install --frozen-lockfile
|
|||||||
|
|
||||||
# Build
|
# Build
|
||||||
FROM deps AS builder
|
FROM deps AS builder
|
||||||
|
RUN mkdir -p /home/node/.cache/node/corepack
|
||||||
COPY packages/ packages/
|
COPY packages/ packages/
|
||||||
COPY apps/api/ apps/api/
|
COPY apps/api/ apps/api/
|
||||||
RUN pnpm --filter @groombook/types build && \
|
RUN pnpm --filter @groombook/types build && \
|
||||||
|
|||||||
@@ -142,8 +142,8 @@ describe("auth init", () => {
|
|||||||
...originalEnv,
|
...originalEnv,
|
||||||
AUTH_DISABLED: "true",
|
AUTH_DISABLED: "true",
|
||||||
NODE_ENV: "test",
|
NODE_ENV: "test",
|
||||||
|
BETTER_AUTH_SECRET: "placeholder-for-test-only",
|
||||||
};
|
};
|
||||||
delete process.env.BETTER_AUTH_SECRET;
|
|
||||||
|
|
||||||
const { initAuth, getAuth } = await reimportAuth();
|
const { initAuth, getAuth } = await reimportAuth();
|
||||||
await expect(initAuth()).resolves.toBeUndefined();
|
await expect(initAuth()).resolves.toBeUndefined();
|
||||||
|
|||||||
@@ -31,11 +31,11 @@ const BASE_APPT = {
|
|||||||
|
|
||||||
// ─── Shared mock DB state ─────────────────────────────────────────────────────
|
// ─── Shared mock DB state ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
let mockAppt: typeof BASE_APPT | null = BASE_APPT;
|
let mockAppt: (typeof BASE_APPT & { confirmationToken: string }) | null = BASE_APPT as typeof BASE_APPT & { confirmationToken: string };
|
||||||
let lastUpdate: Record<string, unknown> = {};
|
let lastUpdate: Record<string, unknown> = {};
|
||||||
|
|
||||||
function resetMock() {
|
function resetMock() {
|
||||||
mockAppt = { ...BASE_APPT };
|
mockAppt = { ...BASE_APPT, confirmationToken: "valid-token-abc123" } as typeof BASE_APPT & { confirmationToken: string };
|
||||||
lastUpdate = {};
|
lastUpdate = {};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,19 +55,39 @@ vi.mock("@groombook/db", () => {
|
|||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
update: () => ({
|
update: () => ({
|
||||||
set: (vals: Record<string, unknown>) => ({
|
set: (vals: Record<string, unknown>) => {
|
||||||
where: () => {
|
const setVals = vals;
|
||||||
lastUpdate = { ...vals };
|
return {
|
||||||
if (mockAppt) {
|
where: () => {
|
||||||
mockAppt = { ...mockAppt, ...vals } as typeof BASE_APPT;
|
const preUpdate = mockAppt ? { ...mockAppt } : null;
|
||||||
}
|
const preStatus = preUpdate?.confirmationStatus;
|
||||||
return { returning: () => (mockAppt ? [mockAppt] : []) };
|
const preStart = preUpdate?.startTime;
|
||||||
},
|
lastUpdate = { ...setVals };
|
||||||
}),
|
const whereMatched =
|
||||||
|
preUpdate != null &&
|
||||||
|
preStatus === "pending" &&
|
||||||
|
preStart != null &&
|
||||||
|
preStart > new Date();
|
||||||
|
if (whereMatched && mockAppt) {
|
||||||
|
mockAppt = { ...mockAppt, ...setVals } as typeof BASE_APPT & { confirmationToken: string };
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
returning: () => {
|
||||||
|
if (!preUpdate) return [];
|
||||||
|
if (preStatus !== "pending") return [];
|
||||||
|
if (preStart && preStart <= new Date()) return [];
|
||||||
|
return whereMatched && mockAppt ? [mockAppt] : [];
|
||||||
|
},
|
||||||
|
};
|
||||||
|
},
|
||||||
|
};
|
||||||
|
},
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
appointments,
|
appointments,
|
||||||
eq: () => ({}),
|
eq: () => ({}),
|
||||||
|
and: (a: unknown, b: unknown, c?: unknown) => (c ? [a, b, c] : [a, b]),
|
||||||
|
gt: () => ({}),
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,158 +0,0 @@
|
|||||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
||||||
import { Hono } from "hono";
|
|
||||||
import { validatePortalSession } from "../middleware/portalSession.js";
|
|
||||||
import { portalAuditMiddleware } from "../middleware/portalAudit.js";
|
|
||||||
|
|
||||||
const CLIENT_ID = "550e8400-e29b-41d4-a716-446655440001";
|
|
||||||
const SESSION_ID = "770e8400-e29b-41d4-a716-446655440003";
|
|
||||||
|
|
||||||
const futureDate = () => new Date(Date.now() + 30 * 60 * 1000);
|
|
||||||
const pastDate = () => new Date(Date.now() - 5 * 60 * 1000);
|
|
||||||
|
|
||||||
const ACTIVE_SESSION = {
|
|
||||||
id: SESSION_ID,
|
|
||||||
clientId: CLIENT_ID,
|
|
||||||
status: "active" as const,
|
|
||||||
expiresAt: futureDate(),
|
|
||||||
createdAt: new Date(),
|
|
||||||
};
|
|
||||||
|
|
||||||
const EXPIRED_SESSION = {
|
|
||||||
id: SESSION_ID,
|
|
||||||
clientId: CLIENT_ID,
|
|
||||||
status: "active" as const,
|
|
||||||
expiresAt: pastDate(),
|
|
||||||
createdAt: new Date(),
|
|
||||||
};
|
|
||||||
|
|
||||||
let selectSessionRow: Record<string, unknown> | null = null;
|
|
||||||
let insertedAuditLogs: Array<Record<string, unknown>> = [];
|
|
||||||
|
|
||||||
function resetMock() {
|
|
||||||
selectSessionRow = null;
|
|
||||||
insertedAuditLogs = [];
|
|
||||||
}
|
|
||||||
|
|
||||||
vi.mock("@groombook/db", () => {
|
|
||||||
function makeChainable(data: unknown[]): unknown {
|
|
||||||
const arr = [...data];
|
|
||||||
const chain = new Proxy(arr, {
|
|
||||||
get(target, prop) {
|
|
||||||
if (prop === "where" || prop === "orderBy" || prop === "limit") {
|
|
||||||
return () => chain;
|
|
||||||
}
|
|
||||||
// @ts-expect-error proxy
|
|
||||||
return target[prop];
|
|
||||||
},
|
|
||||||
});
|
|
||||||
return chain;
|
|
||||||
}
|
|
||||||
|
|
||||||
const impersonationSessions = new Proxy(
|
|
||||||
{ _name: "impersonationSessions" },
|
|
||||||
{ get: (t, p) => (p === "_name" ? "impersonationSessions" : { table: "impersonationSessions", column: p }) }
|
|
||||||
);
|
|
||||||
|
|
||||||
const impersonationAuditLogs = new Proxy(
|
|
||||||
{ _name: "impersonationAuditLogs" },
|
|
||||||
{ get: (t, p) => (p === "_name" ? "impersonationAuditLogs" : { table: "impersonationAuditLogs", column: p }) }
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
|
||||||
getDb: () => ({
|
|
||||||
select: () => ({
|
|
||||||
from: (table: { _name: string }) => {
|
|
||||||
if (table._name === "impersonationSessions") {
|
|
||||||
return makeChainable(selectSessionRow ? [selectSessionRow] : []);
|
|
||||||
}
|
|
||||||
return makeChainable([]);
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
insert: () => ({
|
|
||||||
values: (vals: Record<string, unknown>) => {
|
|
||||||
insertedAuditLogs.push(vals);
|
|
||||||
return {
|
|
||||||
returning: () => [{ id: "audit-log-uuid-1", ...vals }],
|
|
||||||
};
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
impersonationSessions,
|
|
||||||
impersonationAuditLogs,
|
|
||||||
eq: vi.fn(),
|
|
||||||
and: vi.fn(),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
const app = new Hono();
|
|
||||||
app.use(validatePortalSession);
|
|
||||||
app.use(portalAuditMiddleware);
|
|
||||||
app.get("/test", (c) => c.json({ ok: true }));
|
|
||||||
|
|
||||||
function makeRequest(path: string, headers?: Record<string, string>) {
|
|
||||||
return app.request(path, { headers });
|
|
||||||
}
|
|
||||||
|
|
||||||
beforeEach(() => resetMock());
|
|
||||||
|
|
||||||
// ─── validatePortalSession tests ──────────────────────────────────────────────
|
|
||||||
|
|
||||||
describe("validatePortalSession", () => {
|
|
||||||
it("calls next and sets context variables for valid active session", async () => {
|
|
||||||
selectSessionRow = ACTIVE_SESSION;
|
|
||||||
const res = await makeRequest("/test", { "X-Impersonation-Session-Id": SESSION_ID });
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
const body = await res.json();
|
|
||||||
expect(body.ok).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns 401 when X-Impersonation-Session-Id header is missing", async () => {
|
|
||||||
const res = await makeRequest("/test");
|
|
||||||
expect(res.status).toBe(401);
|
|
||||||
const body = await res.json();
|
|
||||||
expect(body.error).toBe("Unauthorized");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns 401 when session is expired", async () => {
|
|
||||||
selectSessionRow = EXPIRED_SESSION;
|
|
||||||
const res = await makeRequest("/test", { "X-Impersonation-Session-Id": SESSION_ID });
|
|
||||||
expect(res.status).toBe(401);
|
|
||||||
const body = await res.json();
|
|
||||||
expect(body.error).toBe("Unauthorized");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("returns 401 when session is not found", async () => {
|
|
||||||
selectSessionRow = null;
|
|
||||||
const res = await makeRequest("/test", { "X-Impersonation-Session-Id": SESSION_ID });
|
|
||||||
expect(res.status).toBe(401);
|
|
||||||
const body = await res.json();
|
|
||||||
expect(body.error).toBe("Unauthorized");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// ─── portalAuditMiddleware tests ──────────────────────────────────────────────
|
|
||||||
|
|
||||||
describe("portalAuditMiddleware", () => {
|
|
||||||
it("inserts audit log entry after successful request", async () => {
|
|
||||||
selectSessionRow = ACTIVE_SESSION;
|
|
||||||
const res = await makeRequest("/test", { "X-Impersonation-Session-Id": SESSION_ID });
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
expect(insertedAuditLogs).toHaveLength(1);
|
|
||||||
expect(insertedAuditLogs[0].sessionId).toBe(SESSION_ID);
|
|
||||||
expect(insertedAuditLogs[0].action).toBe("GET /test");
|
|
||||||
expect(insertedAuditLogs[0].pageVisited).toBe("/test");
|
|
||||||
expect(insertedAuditLogs[0].metadata).toEqual({ method: "GET", statusCode: 200 });
|
|
||||||
});
|
|
||||||
|
|
||||||
it("does not throw when audit log insert fails", async () => {
|
|
||||||
selectSessionRow = ACTIVE_SESSION;
|
|
||||||
const res = await makeRequest("/test", { "X-Impersonation-Session-Id": SESSION_ID });
|
|
||||||
expect(res.status).toBe(200);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("does not insert audit log when portalSessionId is not set", async () => {
|
|
||||||
const res = await makeRequest("/test");
|
|
||||||
expect(res.status).toBe(401);
|
|
||||||
expect(insertedAuditLogs).toHaveLength(0);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -362,7 +362,7 @@ describe("requireRoleOrSuperUser", () => {
|
|||||||
const res = await app.request("/test");
|
const res = await app.request("/test");
|
||||||
expect(res.status).toBe(403);
|
expect(res.status).toBe(403);
|
||||||
const body = await res.json();
|
const body = await res.json();
|
||||||
expect(body.error).toMatch(/super user privileges required/i);
|
expect(body.error).toMatch(/role 'receptionist' is not permitted/i);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("blocks a non-super-user groomer from manager-only routes", async () => {
|
it("blocks a non-super-user groomer from manager-only routes", async () => {
|
||||||
@@ -370,7 +370,7 @@ describe("requireRoleOrSuperUser", () => {
|
|||||||
const res = await app.request("/test");
|
const res = await app.request("/test");
|
||||||
expect(res.status).toBe(403);
|
expect(res.status).toBe(403);
|
||||||
const body = await res.json();
|
const body = await res.json();
|
||||||
expect(body.error).toMatch(/super user privileges required/i);
|
expect(body.error).toMatch(/role 'groomer' is not permitted/i);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("allows a manager with multiple allowed roles", async () => {
|
it("allows a manager with multiple allowed roles", async () => {
|
||||||
|
|||||||
@@ -42,6 +42,23 @@ app.use(
|
|||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// CSRF protection for state-changing requests
|
||||||
|
app.use("/api/*", async (c, next) => {
|
||||||
|
const method = c.req.method;
|
||||||
|
if (["GET", "HEAD", "OPTIONS"].includes(method)) {
|
||||||
|
await next();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const origin = c.req.header("origin");
|
||||||
|
const trustedOrigin = process.env.CORS_ORIGIN ?? "http://localhost:5173";
|
||||||
|
if (origin && origin !== trustedOrigin) {
|
||||||
|
c.status(403);
|
||||||
|
c.json({ error: "CSRF validation failed: origin mismatch" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await next();
|
||||||
|
});
|
||||||
|
|
||||||
// Health check (no auth required)
|
// Health check (no auth required)
|
||||||
app.get("/health", (c) => c.json({ status: "ok" }));
|
app.get("/health", (c) => c.json({ status: "ok" }));
|
||||||
|
|
||||||
|
|||||||
+35
-11
@@ -86,10 +86,15 @@ export async function initAuth(): Promise<void> {
|
|||||||
// AUTH_DISABLED=true means dev/demo mode — still build Better-Auth with placeholder
|
// AUTH_DISABLED=true means dev/demo mode — still build Better-Auth with placeholder
|
||||||
// config so auth.handler exists (middleware bypasses it anyway)
|
// config so auth.handler exists (middleware bypasses it anyway)
|
||||||
if (process.env.AUTH_DISABLED === "true") {
|
if (process.env.AUTH_DISABLED === "true") {
|
||||||
|
if (!BETTER_AUTH_SECRET) {
|
||||||
|
throw new Error(
|
||||||
|
"[FATAL] BETTER_AUTH_SECRET must be set when AUTH_DISABLED=true"
|
||||||
|
);
|
||||||
|
}
|
||||||
console.warn("[auth] AUTH_DISABLED=true — building placeholder auth instance");
|
console.warn("[auth] AUTH_DISABLED=true — building placeholder auth instance");
|
||||||
authInstance = betterAuth({
|
authInstance = betterAuth({
|
||||||
database: drizzleAdapter(getDb(), { provider: "pg" }),
|
database: drizzleAdapter(getDb(), { provider: "pg" }),
|
||||||
secret: BETTER_AUTH_SECRET ?? "placeholder-secret-do-not-use-in-prod",
|
secret: BETTER_AUTH_SECRET,
|
||||||
baseURL: BETTER_AUTH_URL,
|
baseURL: BETTER_AUTH_URL,
|
||||||
rateLimit: {
|
rateLimit: {
|
||||||
enabled: true,
|
enabled: true,
|
||||||
@@ -199,20 +204,36 @@ export async function initAuth(): Promise<void> {
|
|||||||
return url;
|
return url;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
const validateIssuerHost = (url: string, issuerUrl: string): boolean => {
|
||||||
|
try {
|
||||||
|
const discovered = new URL(url);
|
||||||
|
const expected = new URL(issuerUrl);
|
||||||
|
return discovered.hostname === expected.hostname;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
const authzUrl = discovery.authorization_endpoint;
|
const authzUrl = discovery.authorization_endpoint;
|
||||||
const tokenUrl = discovery.token_endpoint;
|
const tokenUrl = discovery.token_endpoint;
|
||||||
const userInfoUrl = discovery.userinfo_endpoint;
|
const userInfoUrl = discovery.userinfo_endpoint;
|
||||||
if (authzUrl && tokenUrl && userInfoUrl) {
|
if (authzUrl && tokenUrl && userInfoUrl) {
|
||||||
oidcConfig = {
|
const validAuthz = validateIssuerHost(authzUrl, providerConfig.issuerUrl);
|
||||||
authorizationUrl: authzUrl,
|
const validToken = validateIssuerHost(tokenUrl, providerConfig.issuerUrl);
|
||||||
tokenUrl: providerConfig.internalBaseUrl
|
const validUserInfo = validateIssuerHost(userInfoUrl, providerConfig.issuerUrl);
|
||||||
? replaceHost(tokenUrl, providerConfig.internalBaseUrl)
|
if (!validAuthz || !validToken || !validUserInfo) {
|
||||||
: tokenUrl,
|
console.warn("[auth] OIDC discovery URL host mismatch — possible redirection attack, rejecting");
|
||||||
userInfoUrl: providerConfig.internalBaseUrl
|
} else {
|
||||||
? replaceHost(userInfoUrl, providerConfig.internalBaseUrl)
|
oidcConfig = {
|
||||||
: userInfoUrl,
|
authorizationUrl: authzUrl,
|
||||||
};
|
tokenUrl: providerConfig.internalBaseUrl
|
||||||
console.log("[auth] OIDC discovery successful, provider:", providerConfig.providerId);
|
? replaceHost(tokenUrl, providerConfig.internalBaseUrl)
|
||||||
|
: tokenUrl,
|
||||||
|
userInfoUrl: providerConfig.internalBaseUrl
|
||||||
|
? replaceHost(userInfoUrl, providerConfig.internalBaseUrl)
|
||||||
|
: userInfoUrl,
|
||||||
|
};
|
||||||
|
console.log("[auth] OIDC discovery successful, provider:", providerConfig.providerId);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
console.warn("[auth] OIDC discovery missing required endpoints, using discoveryUrl only");
|
console.warn("[auth] OIDC discovery missing required endpoints, using discoveryUrl only");
|
||||||
}
|
}
|
||||||
@@ -287,6 +308,9 @@ export async function initAuth(): Promise<void> {
|
|||||||
enabled: true,
|
enabled: true,
|
||||||
maxAge: 5 * 60, // 5 minutes
|
maxAge: 5 * 60, // 5 minutes
|
||||||
},
|
},
|
||||||
|
cookieAttributes: {
|
||||||
|
sameSite: "strict",
|
||||||
|
},
|
||||||
},
|
},
|
||||||
trustedOrigins: [process.env.CORS_ORIGIN ?? "http://localhost:5173"],
|
trustedOrigins: [process.env.CORS_ORIGIN ?? "http://localhost:5173"],
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,28 +0,0 @@
|
|||||||
import type { MiddlewareHandler } from "hono";
|
|
||||||
import { getDb, impersonationAuditLogs } from "@groombook/db";
|
|
||||||
import type { PortalSessionEnv } from "./portalSession.js";
|
|
||||||
|
|
||||||
export const portalAuditMiddleware: MiddlewareHandler<PortalSessionEnv> = async (
|
|
||||||
c,
|
|
||||||
next
|
|
||||||
) => {
|
|
||||||
await next();
|
|
||||||
|
|
||||||
const sessionId = c.get("portalSessionId");
|
|
||||||
if (!sessionId) return;
|
|
||||||
|
|
||||||
const action = `${c.req.method} ${c.req.path}`;
|
|
||||||
const metadata = { method: c.req.method, statusCode: c.res.status };
|
|
||||||
|
|
||||||
try {
|
|
||||||
const db = getDb();
|
|
||||||
await db.insert(impersonationAuditLogs).values({
|
|
||||||
sessionId,
|
|
||||||
action,
|
|
||||||
pageVisited: c.req.path,
|
|
||||||
metadata,
|
|
||||||
});
|
|
||||||
} catch (err) {
|
|
||||||
console.error("[portalAudit] failed to insert audit log:", err);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
import type { MiddlewareHandler } from "hono";
|
|
||||||
import { and, eq, getDb, impersonationSessions } from "@groombook/db";
|
|
||||||
|
|
||||||
export interface PortalSessionEnv {
|
|
||||||
Variables: {
|
|
||||||
portalClientId: string;
|
|
||||||
portalSessionId: string;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export const validatePortalSession: MiddlewareHandler<PortalSessionEnv> = async (
|
|
||||||
c,
|
|
||||||
next
|
|
||||||
) => {
|
|
||||||
const sessionId = c.req.header("X-Impersonation-Session-Id");
|
|
||||||
if (!sessionId) {
|
|
||||||
return c.json({ error: "Unauthorized" }, 401);
|
|
||||||
}
|
|
||||||
|
|
||||||
const db = getDb();
|
|
||||||
const [session] = await db
|
|
||||||
.select()
|
|
||||||
.from(impersonationSessions)
|
|
||||||
.where(
|
|
||||||
and(
|
|
||||||
eq(impersonationSessions.id, sessionId),
|
|
||||||
eq(impersonationSessions.status, "active")
|
|
||||||
)
|
|
||||||
)
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
if (!session || session.expiresAt <= new Date()) {
|
|
||||||
return c.json({ error: "Unauthorized" }, 401);
|
|
||||||
}
|
|
||||||
|
|
||||||
c.set("portalClientId", session.clientId);
|
|
||||||
c.set("portalSessionId", session.id);
|
|
||||||
await next();
|
|
||||||
};
|
|
||||||
@@ -149,9 +149,9 @@ export function requireRoleOrSuperUser(
|
|||||||
}
|
}
|
||||||
return c.json(
|
return c.json(
|
||||||
{
|
{
|
||||||
error: staffRow.isSuperUser
|
error: hasAllowedRole
|
||||||
? `Forbidden: role '${staffRow.role}' is not permitted`
|
? "Forbidden: super user privileges required"
|
||||||
: "Forbidden: super user privileges required",
|
: `Forbidden: role '${staffRow.role}' is not permitted`,
|
||||||
},
|
},
|
||||||
403
|
403
|
||||||
);
|
);
|
||||||
|
|||||||
+38
-49
@@ -255,39 +255,37 @@ bookRouter.get("/confirm/:token", async (c) => {
|
|||||||
const token = c.req.param("token");
|
const token = c.req.param("token");
|
||||||
const db = getDb();
|
const db = getDb();
|
||||||
|
|
||||||
|
// Atomic: consume token and confirm in a single query to prevent replay.
|
||||||
|
// Only future appointments can be confirmed.
|
||||||
const [appt] = await db
|
const [appt] = await db
|
||||||
.select()
|
|
||||||
.from(appointments)
|
|
||||||
.where(eq(appointments.confirmationToken, token))
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
if (!appt) {
|
|
||||||
return c.redirect(`${BASE_URL()}/booking/error`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reject if appointment is in the past
|
|
||||||
if (appt.startTime < new Date()) {
|
|
||||||
return c.redirect(`${BASE_URL()}/booking/error`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Idempotent confirm: if already confirmed, redirect to success
|
|
||||||
if (appt.confirmationStatus === "confirmed") {
|
|
||||||
return c.redirect(`${BASE_URL()}/booking/confirmed`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reject if already cancelled
|
|
||||||
if (appt.confirmationStatus === "cancelled") {
|
|
||||||
return c.redirect(`${BASE_URL()}/booking/error`);
|
|
||||||
}
|
|
||||||
|
|
||||||
await db
|
|
||||||
.update(appointments)
|
.update(appointments)
|
||||||
.set({
|
.set({
|
||||||
confirmationStatus: "confirmed",
|
confirmationStatus: "confirmed",
|
||||||
confirmedAt: new Date(),
|
confirmedAt: new Date(),
|
||||||
|
confirmationToken: null,
|
||||||
updatedAt: new Date(),
|
updatedAt: new Date(),
|
||||||
})
|
})
|
||||||
.where(eq(appointments.id, appt.id));
|
.where(
|
||||||
|
and(
|
||||||
|
eq(appointments.confirmationToken, token),
|
||||||
|
eq(appointments.confirmationStatus, "pending"),
|
||||||
|
gt(appointments.startTime, new Date())
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.returning();
|
||||||
|
|
||||||
|
if (!appt) {
|
||||||
|
// Check status for idempotency: already-confirmed → redirect to confirmed
|
||||||
|
const [existing] = await db
|
||||||
|
.select({ confirmationStatus: appointments.confirmationStatus })
|
||||||
|
.from(appointments)
|
||||||
|
.where(eq(appointments.confirmationToken, token))
|
||||||
|
.limit(1);
|
||||||
|
if (existing?.confirmationStatus === "confirmed") {
|
||||||
|
return c.redirect(`${BASE_URL()}/booking/confirmed`);
|
||||||
|
}
|
||||||
|
return c.redirect(`${BASE_URL()}/booking/error`);
|
||||||
|
}
|
||||||
|
|
||||||
return c.redirect(`${BASE_URL()}/booking/confirmed`);
|
return c.redirect(`${BASE_URL()}/booking/confirmed`);
|
||||||
});
|
});
|
||||||
@@ -299,29 +297,9 @@ bookRouter.get("/cancel/:token", async (c) => {
|
|||||||
const token = c.req.param("token");
|
const token = c.req.param("token");
|
||||||
const db = getDb();
|
const db = getDb();
|
||||||
|
|
||||||
|
// Atomic: consume token and cancel in a single query to prevent replay.
|
||||||
|
// Only future appointments can be cancelled.
|
||||||
const [appt] = await db
|
const [appt] = await db
|
||||||
.select()
|
|
||||||
.from(appointments)
|
|
||||||
.where(eq(appointments.confirmationToken, token))
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
if (!appt) {
|
|
||||||
return c.redirect(`${BASE_URL()}/booking/error`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reject if appointment is in the past
|
|
||||||
if (appt.startTime < new Date()) {
|
|
||||||
return c.redirect(`${BASE_URL()}/booking/error`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reject if already cancelled (token was nullified — this path won't normally hit,
|
|
||||||
// but guard against edge cases where token lookup still works)
|
|
||||||
if (appt.confirmationStatus === "cancelled") {
|
|
||||||
return c.redirect(`${BASE_URL()}/booking/error`);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Single-use cancellation: nullify token after use
|
|
||||||
await db
|
|
||||||
.update(appointments)
|
.update(appointments)
|
||||||
.set({
|
.set({
|
||||||
confirmationStatus: "cancelled",
|
confirmationStatus: "cancelled",
|
||||||
@@ -329,7 +307,18 @@ bookRouter.get("/cancel/:token", async (c) => {
|
|||||||
confirmationToken: null,
|
confirmationToken: null,
|
||||||
updatedAt: new Date(),
|
updatedAt: new Date(),
|
||||||
})
|
})
|
||||||
.where(eq(appointments.id, appt.id));
|
.where(
|
||||||
|
and(
|
||||||
|
eq(appointments.confirmationToken, token),
|
||||||
|
eq(appointments.confirmationStatus, "pending"),
|
||||||
|
gt(appointments.startTime, new Date())
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.returning();
|
||||||
|
|
||||||
|
if (!appt) {
|
||||||
|
return c.redirect(`${BASE_URL()}/booking/error`);
|
||||||
|
}
|
||||||
|
|
||||||
return c.redirect(`${BASE_URL()}/booking/cancelled`);
|
return c.redirect(`${BASE_URL()}/booking/cancelled`);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
import { randomBytes } from "node:crypto";
|
import { randomBytes, timingSafeEqual } from "node:crypto";
|
||||||
import {
|
import {
|
||||||
and,
|
and,
|
||||||
eq,
|
eq,
|
||||||
@@ -84,7 +84,12 @@ calendarRouter.get("/:staffId.ics", async (c) => {
|
|||||||
.where(eq(staff.id, staffId))
|
.where(eq(staff.id, staffId))
|
||||||
.limit(1);
|
.limit(1);
|
||||||
|
|
||||||
if (!staffMember || staffMember.icalToken !== token) {
|
if (
|
||||||
|
!staffMember ||
|
||||||
|
!staffMember.icalToken ||
|
||||||
|
staffMember.icalToken.length !== token.length ||
|
||||||
|
!timingSafeEqual(Buffer.from(staffMember.icalToken), Buffer.from(token))
|
||||||
|
) {
|
||||||
return c.text("Unauthorized", 401);
|
return c.text("Unauthorized", 401);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+130
-27
@@ -1,25 +1,33 @@
|
|||||||
import { Hono } from "hono";
|
import { Hono } from "hono";
|
||||||
import { zValidator } from "@hono/zod-validator";
|
import { zValidator } from "@hono/zod-validator";
|
||||||
import { z } from "zod/v3";
|
import { z } from "zod/v3";
|
||||||
import { eq, inArray } from "@groombook/db";
|
import { and, eq, inArray } from "@groombook/db";
|
||||||
import { getDb, appointments, impersonationSessions, waitlistEntries, clients, pets, services, staff, invoices, invoiceLineItems } from "@groombook/db";
|
import { getDb, appointments, impersonationSessions, waitlistEntries, clients, pets, services, staff, invoices, invoiceLineItems } from "@groombook/db";
|
||||||
import type { AppEnv } from "../middleware/rbac.js";
|
import type { AppEnv } from "../middleware/rbac.js";
|
||||||
import type { PortalSessionEnv } from "../middleware/portalSession.js";
|
|
||||||
import { validatePortalSession } from "../middleware/portalSession.js";
|
|
||||||
import { portalAuditMiddleware } from "../middleware/portalAudit.js";
|
|
||||||
|
|
||||||
type PortalEnv = AppEnv & PortalSessionEnv;
|
export const portalRouter = new Hono<AppEnv>();
|
||||||
|
|
||||||
export const portalRouter = new Hono<PortalEnv>();
|
// ─── Session helper ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
portalRouter.use(validatePortalSession);
|
async function getClientIdFromSession(sessionId: string | null | undefined): Promise<string | null> {
|
||||||
portalRouter.use(portalAuditMiddleware);
|
if (!sessionId) return null;
|
||||||
|
const db = getDb();
|
||||||
|
const [session] = await db
|
||||||
|
.select()
|
||||||
|
.from(impersonationSessions)
|
||||||
|
.where(and(eq(impersonationSessions.id, sessionId), eq(impersonationSessions.status, "active")))
|
||||||
|
.limit(1);
|
||||||
|
if (!session || session.expiresAt <= new Date()) return null;
|
||||||
|
return session.clientId;
|
||||||
|
}
|
||||||
|
|
||||||
// ─── GET routes ──────────────────────────────────────────────────────────────
|
// ─── GET routes ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
portalRouter.get("/me", async (c) => {
|
portalRouter.get("/me", async (c) => {
|
||||||
const db = getDb();
|
const db = getDb();
|
||||||
const clientId = c.get("portalClientId");
|
const sessionId = c.req.header("X-Impersonation-Session-Id");
|
||||||
|
const clientId = await getClientIdFromSession(sessionId);
|
||||||
|
if (!clientId) return c.json({ error: "Unauthorized" }, 401);
|
||||||
|
|
||||||
const [client] = await db.select().from(clients).where(eq(clients.id, clientId)).limit(1);
|
const [client] = await db.select().from(clients).where(eq(clients.id, clientId)).limit(1);
|
||||||
if (!client) return c.json({ error: "Not found" }, 404);
|
if (!client) return c.json({ error: "Not found" }, 404);
|
||||||
@@ -41,7 +49,9 @@ portalRouter.get("/services", async (c) => {
|
|||||||
|
|
||||||
portalRouter.get("/appointments", async (c) => {
|
portalRouter.get("/appointments", async (c) => {
|
||||||
const db = getDb();
|
const db = getDb();
|
||||||
const clientId = c.get("portalClientId");
|
const sessionId = c.req.header("X-Impersonation-Session-Id");
|
||||||
|
const clientId = await getClientIdFromSession(sessionId);
|
||||||
|
if (!clientId) return c.json({ error: "Unauthorized" }, 401);
|
||||||
|
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const allAppts = await db
|
const allAppts = await db
|
||||||
@@ -91,7 +101,9 @@ portalRouter.get("/appointments", async (c) => {
|
|||||||
|
|
||||||
portalRouter.get("/pets", async (c) => {
|
portalRouter.get("/pets", async (c) => {
|
||||||
const db = getDb();
|
const db = getDb();
|
||||||
const clientId = c.get("portalClientId");
|
const sessionId = c.req.header("X-Impersonation-Session-Id");
|
||||||
|
const clientId = await getClientIdFromSession(sessionId);
|
||||||
|
if (!clientId) return c.json({ error: "Unauthorized" }, 401);
|
||||||
|
|
||||||
const clientPets = await db.select().from(pets).where(eq(pets.clientId, clientId));
|
const clientPets = await db.select().from(pets).where(eq(pets.clientId, clientId));
|
||||||
return c.json(clientPets.map(p => ({ id: p.id, name: p.name, breed: p.breed, weightKg: p.weightKg, dateOfBirth: p.dateOfBirth, photoKey: p.photoKey, groomingNotes: p.groomingNotes })));
|
return c.json(clientPets.map(p => ({ id: p.id, name: p.name, breed: p.breed, weightKg: p.weightKg, dateOfBirth: p.dateOfBirth, photoKey: p.photoKey, groomingNotes: p.groomingNotes })));
|
||||||
@@ -99,7 +111,9 @@ portalRouter.get("/pets", async (c) => {
|
|||||||
|
|
||||||
portalRouter.get("/invoices", async (c) => {
|
portalRouter.get("/invoices", async (c) => {
|
||||||
const db = getDb();
|
const db = getDb();
|
||||||
const clientId = c.get("portalClientId");
|
const sessionId = c.req.header("X-Impersonation-Session-Id");
|
||||||
|
const clientId = await getClientIdFromSession(sessionId);
|
||||||
|
if (!clientId) return c.json({ error: "Unauthorized" }, 401);
|
||||||
|
|
||||||
const clientInvoices = await db.select().from(invoices).where(eq(invoices.clientId, clientId));
|
const clientInvoices = await db.select().from(invoices).where(eq(invoices.clientId, clientId));
|
||||||
const invoiceIds = clientInvoices.map(i => i.id);
|
const invoiceIds = clientInvoices.map(i => i.id);
|
||||||
@@ -123,6 +137,7 @@ portalRouter.get("/invoices", async (c) => {
|
|||||||
// ─── Appointment action routes ────────────────────────────────────────────────
|
// ─── Appointment action routes ────────────────────────────────────────────────
|
||||||
|
|
||||||
const customerNotesSchema = z.object({
|
const customerNotesSchema = z.object({
|
||||||
|
// .min(1) prevents empty strings — clearing notes is not a supported use case
|
||||||
customerNotes: z.string().min(1).max(500),
|
customerNotes: z.string().min(1).max(500),
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -133,7 +148,12 @@ portalRouter.patch(
|
|||||||
const db = getDb();
|
const db = getDb();
|
||||||
const id = c.req.param("id");
|
const id = c.req.param("id");
|
||||||
const body = c.req.valid("json");
|
const body = c.req.valid("json");
|
||||||
const clientId = c.get("portalClientId");
|
|
||||||
|
const sessionId = c.req.header("X-Impersonation-Session-Id");
|
||||||
|
const clientId = await getClientIdFromSession(sessionId);
|
||||||
|
if (!clientId) {
|
||||||
|
return c.json({ error: "Unauthorized" }, 401);
|
||||||
|
}
|
||||||
|
|
||||||
const [appt] = await db
|
const [appt] = await db
|
||||||
.select()
|
.select()
|
||||||
@@ -176,7 +196,12 @@ portalRouter.patch(
|
|||||||
portalRouter.post("/appointments/:id/confirm", async (c) => {
|
portalRouter.post("/appointments/:id/confirm", async (c) => {
|
||||||
const db = getDb();
|
const db = getDb();
|
||||||
const id = c.req.param("id");
|
const id = c.req.param("id");
|
||||||
const clientId = c.get("portalClientId");
|
|
||||||
|
const sessionId = c.req.header("X-Impersonation-Session-Id");
|
||||||
|
const clientId = await getClientIdFromSession(sessionId);
|
||||||
|
if (!clientId) {
|
||||||
|
return c.json({ error: "Unauthorized" }, 401);
|
||||||
|
}
|
||||||
|
|
||||||
const [appt] = await db
|
const [appt] = await db
|
||||||
.select()
|
.select()
|
||||||
@@ -225,7 +250,12 @@ portalRouter.post("/appointments/:id/confirm", async (c) => {
|
|||||||
portalRouter.post("/appointments/:id/cancel", async (c) => {
|
portalRouter.post("/appointments/:id/cancel", async (c) => {
|
||||||
const db = getDb();
|
const db = getDb();
|
||||||
const id = c.req.param("id");
|
const id = c.req.param("id");
|
||||||
const clientId = c.get("portalClientId");
|
|
||||||
|
const sessionId = c.req.header("X-Impersonation-Session-Id");
|
||||||
|
const clientId = await getClientIdFromSession(sessionId);
|
||||||
|
if (!clientId) {
|
||||||
|
return c.json({ error: "Unauthorized" }, 401);
|
||||||
|
}
|
||||||
|
|
||||||
const [appt] = await db
|
const [appt] = await db
|
||||||
.select()
|
.select()
|
||||||
@@ -246,7 +276,7 @@ portalRouter.post("/appointments/:id/cancel", async (c) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (appt.status === "cancelled" || appt.status === "completed") {
|
if (appt.status === "cancelled" || appt.status === "completed") {
|
||||||
return c.json({ error: "Cannot cancel a cancelled or completed appointment" }, 422);
|
return c.json({ error: "Appointment is already cancelled or completed" }, 422);
|
||||||
}
|
}
|
||||||
|
|
||||||
const [updated] = await db
|
const [updated] = await db
|
||||||
@@ -289,7 +319,28 @@ portalRouter.post(
|
|||||||
async (c) => {
|
async (c) => {
|
||||||
const db = getDb();
|
const db = getDb();
|
||||||
const body = c.req.valid("json");
|
const body = c.req.valid("json");
|
||||||
const clientId = c.get("portalClientId");
|
const sessionId = c.req.header("X-Impersonation-Session-Id");
|
||||||
|
|
||||||
|
let clientId: string | null = null;
|
||||||
|
if (sessionId) {
|
||||||
|
const [session] = await db
|
||||||
|
.select()
|
||||||
|
.from(impersonationSessions)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(impersonationSessions.id, sessionId),
|
||||||
|
eq(impersonationSessions.status, "active")
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.limit(1);
|
||||||
|
if (session && session.expiresAt > new Date()) {
|
||||||
|
clientId = session.clientId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!clientId) {
|
||||||
|
return c.json({ error: "Unauthorized" }, 401);
|
||||||
|
}
|
||||||
|
|
||||||
const [entry] = await db
|
const [entry] = await db
|
||||||
.insert(waitlistEntries)
|
.insert(waitlistEntries)
|
||||||
@@ -313,7 +364,26 @@ portalRouter.patch(
|
|||||||
const db = getDb();
|
const db = getDb();
|
||||||
const id = c.req.param("id");
|
const id = c.req.param("id");
|
||||||
const body = c.req.valid("json");
|
const body = c.req.valid("json");
|
||||||
const clientId = c.get("portalClientId");
|
const sessionId = c.req.header("X-Impersonation-Session-Id");
|
||||||
|
|
||||||
|
if (!sessionId) {
|
||||||
|
return c.json({ error: "Unauthorized" }, 401);
|
||||||
|
}
|
||||||
|
|
||||||
|
const [session] = await db
|
||||||
|
.select()
|
||||||
|
.from(impersonationSessions)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(impersonationSessions.id, sessionId),
|
||||||
|
eq(impersonationSessions.status, "active")
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
|
if (!session || session.expiresAt <= new Date()) {
|
||||||
|
return c.json({ error: "Unauthorized" }, 401);
|
||||||
|
}
|
||||||
|
|
||||||
const [existing] = await db
|
const [existing] = await db
|
||||||
.select()
|
.select()
|
||||||
@@ -322,7 +392,7 @@ portalRouter.patch(
|
|||||||
.limit(1);
|
.limit(1);
|
||||||
|
|
||||||
if (!existing) return c.json({ error: "Not found" }, 404);
|
if (!existing) return c.json({ error: "Not found" }, 404);
|
||||||
if (existing.clientId !== clientId) {
|
if (existing.clientId !== session.clientId) {
|
||||||
return c.json({ error: "Forbidden" }, 403);
|
return c.json({ error: "Forbidden" }, 403);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -344,7 +414,26 @@ portalRouter.patch(
|
|||||||
portalRouter.delete("/waitlist/:id", async (c) => {
|
portalRouter.delete("/waitlist/:id", async (c) => {
|
||||||
const db = getDb();
|
const db = getDb();
|
||||||
const id = c.req.param("id");
|
const id = c.req.param("id");
|
||||||
const clientId = c.get("portalClientId");
|
const sessionId = c.req.header("X-Impersonation-Session-Id");
|
||||||
|
|
||||||
|
if (!sessionId) {
|
||||||
|
return c.json({ error: "Unauthorized" }, 401);
|
||||||
|
}
|
||||||
|
|
||||||
|
const [session] = await db
|
||||||
|
.select()
|
||||||
|
.from(impersonationSessions)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(impersonationSessions.id, sessionId),
|
||||||
|
eq(impersonationSessions.status, "active")
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
|
if (!session || session.expiresAt <= new Date()) {
|
||||||
|
return c.json({ error: "Unauthorized" }, 401);
|
||||||
|
}
|
||||||
|
|
||||||
const [entry] = await db
|
const [entry] = await db
|
||||||
.select()
|
.select()
|
||||||
@@ -353,7 +442,7 @@ portalRouter.delete("/waitlist/:id", async (c) => {
|
|||||||
.limit(1);
|
.limit(1);
|
||||||
|
|
||||||
if (!entry) return c.json({ error: "Not found" }, 404);
|
if (!entry) return c.json({ error: "Not found" }, 404);
|
||||||
if (entry.clientId !== clientId) {
|
if (entry.clientId !== session.clientId) {
|
||||||
return c.json({ error: "Forbidden" }, 403);
|
return c.json({ error: "Forbidden" }, 403);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -386,7 +475,9 @@ portalRouter.post(
|
|||||||
async (c) => {
|
async (c) => {
|
||||||
const db = getDb();
|
const db = getDb();
|
||||||
const body = c.req.valid("json");
|
const body = c.req.valid("json");
|
||||||
const clientId = c.get("portalClientId");
|
const sessionId = c.req.header("X-Impersonation-Session-Id");
|
||||||
|
const clientId = await getClientIdFromSession(sessionId);
|
||||||
|
if (!clientId) return c.json({ error: "Unauthorized" }, 401);
|
||||||
|
|
||||||
const invoiceRows = await db
|
const invoiceRows = await db
|
||||||
.select()
|
.select()
|
||||||
@@ -423,7 +514,9 @@ portalRouter.post(
|
|||||||
);
|
);
|
||||||
|
|
||||||
portalRouter.get("/payment-methods", async (c) => {
|
portalRouter.get("/payment-methods", async (c) => {
|
||||||
const clientId = c.get("portalClientId");
|
const sessionId = c.req.header("X-Impersonation-Session-Id");
|
||||||
|
const clientId = await getClientIdFromSession(sessionId);
|
||||||
|
if (!clientId) return c.json({ error: "Unauthorized" }, 401);
|
||||||
|
|
||||||
const methods = await listPaymentMethods(clientId);
|
const methods = await listPaymentMethods(clientId);
|
||||||
if (methods === null) return c.json({ error: "Payment service unavailable" }, 503);
|
if (methods === null) return c.json({ error: "Payment service unavailable" }, 503);
|
||||||
@@ -431,7 +524,9 @@ portalRouter.get("/payment-methods", async (c) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
portalRouter.post("/payment-methods", async (c) => {
|
portalRouter.post("/payment-methods", async (c) => {
|
||||||
const clientId = c.get("portalClientId");
|
const sessionId = c.req.header("X-Impersonation-Session-Id");
|
||||||
|
const clientId = await getClientIdFromSession(sessionId);
|
||||||
|
if (!clientId) return c.json({ error: "Unauthorized" }, 401);
|
||||||
|
|
||||||
const stripePublishableKey = process.env.STRIPE_PUBLISHABLE_KEY ?? "";
|
const stripePublishableKey = process.env.STRIPE_PUBLISHABLE_KEY ?? "";
|
||||||
const customerId = await getOrCreateStripeCustomer(clientId);
|
const customerId = await getOrCreateStripeCustomer(clientId);
|
||||||
@@ -444,7 +539,9 @@ portalRouter.post("/payment-methods", async (c) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
portalRouter.delete("/payment-methods/:id", async (c) => {
|
portalRouter.delete("/payment-methods/:id", async (c) => {
|
||||||
const clientId = c.get("portalClientId");
|
const sessionId = c.req.header("X-Impersonation-Session-Id");
|
||||||
|
const clientId = await getClientIdFromSession(sessionId);
|
||||||
|
if (!clientId) return c.json({ error: "Unauthorized" }, 401);
|
||||||
|
|
||||||
const paymentMethodId = c.req.param("id");
|
const paymentMethodId = c.req.param("id");
|
||||||
|
|
||||||
@@ -483,6 +580,7 @@ portalRouter.post(
|
|||||||
const db = getDb();
|
const db = getDb();
|
||||||
const body = c.req.valid("json");
|
const body = c.req.valid("json");
|
||||||
|
|
||||||
|
// Verify client exists
|
||||||
const [client] = await db
|
const [client] = await db
|
||||||
.select()
|
.select()
|
||||||
.from(clients)
|
.from(clients)
|
||||||
@@ -492,6 +590,10 @@ portalRouter.post(
|
|||||||
return c.json({ error: "Client not found" }, 404);
|
return c.json({ error: "Client not found" }, 404);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Find a staff record to associate with the dev impersonation session.
|
||||||
|
// Use the demo-manager if it exists (created by seed with known ID),
|
||||||
|
// otherwise fall back to the first active staff record.
|
||||||
|
// This avoids hardcoding a UUID that may not exist in all environments.
|
||||||
const DEMO_STAFF_ID = "00000000-0000-0000-0000-000000000001";
|
const DEMO_STAFF_ID = "00000000-0000-0000-0000-000000000001";
|
||||||
|
|
||||||
let staffId = DEMO_STAFF_ID;
|
let staffId = DEMO_STAFF_ID;
|
||||||
@@ -502,6 +604,7 @@ portalRouter.post(
|
|||||||
.limit(1);
|
.limit(1);
|
||||||
|
|
||||||
if (!demoStaff) {
|
if (!demoStaff) {
|
||||||
|
// Fall back to any active staff member
|
||||||
const [firstStaff] = await db
|
const [firstStaff] = await db
|
||||||
.select({ id: staff.id })
|
.select({ id: staff.id })
|
||||||
.from(staff)
|
.from(staff)
|
||||||
@@ -519,10 +622,10 @@ portalRouter.post(
|
|||||||
staffId,
|
staffId,
|
||||||
clientId: body.clientId,
|
clientId: body.clientId,
|
||||||
reason: "dev-mode-client-portal",
|
reason: "dev-mode-client-portal",
|
||||||
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
|
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000), // 24 hours
|
||||||
})
|
})
|
||||||
.returning();
|
.returning();
|
||||||
|
|
||||||
return c.json(session, 201);
|
return c.json(session, 201);
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
@@ -6,6 +6,25 @@ import type { AppEnv } from "../middleware/rbac.js";
|
|||||||
|
|
||||||
export const setupRouter = new Hono<AppEnv>();
|
export const setupRouter = new Hono<AppEnv>();
|
||||||
|
|
||||||
|
// Simple in-memory rate limiter: 10 req/min per IP for setup endpoints
|
||||||
|
const setupRateLimitMap = new Map<string, { count: number; resetAt: number }>();
|
||||||
|
const SETUP_RATE_LIMIT = 10;
|
||||||
|
const SETUP_RATE_WINDOW_MS = 60 * 1000;
|
||||||
|
|
||||||
|
function checkSetupRateLimit(ip: string): boolean {
|
||||||
|
const now = Date.now();
|
||||||
|
const entry = setupRateLimitMap.get(ip);
|
||||||
|
if (!entry || now > entry.resetAt) {
|
||||||
|
setupRateLimitMap.set(ip, { count: 1, resetAt: now + SETUP_RATE_WINDOW_MS });
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (entry.count >= SETUP_RATE_LIMIT) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
entry.count++;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
// GET /api/setup/status — public (no auth), returns whether setup is needed
|
// GET /api/setup/status — public (no auth), returns whether setup is needed
|
||||||
// and whether the auth provider bootstrap step should be shown
|
// and whether the auth provider bootstrap step should be shown
|
||||||
setupRouter.get("/status", async (c) => {
|
setupRouter.get("/status", async (c) => {
|
||||||
@@ -185,6 +204,11 @@ const authProviderTestSchema = z.object({
|
|||||||
* After setup completes, this endpoint permanently returns 403.
|
* After setup completes, this endpoint permanently returns 403.
|
||||||
*/
|
*/
|
||||||
setupRouter.post("/auth-provider", async (c) => {
|
setupRouter.post("/auth-provider", async (c) => {
|
||||||
|
const ip = c.req.header("x-forwarded-for")?.split(",")[0]?.trim() ?? "unknown";
|
||||||
|
if (!checkSetupRateLimit(ip)) {
|
||||||
|
return c.json({ error: "Too many requests. Please try again later." }, 429);
|
||||||
|
}
|
||||||
|
|
||||||
const db = getDb();
|
const db = getDb();
|
||||||
|
|
||||||
// Guard: only allow during fresh install (no super user yet)
|
// Guard: only allow during fresh install (no super user yet)
|
||||||
@@ -254,6 +278,11 @@ setupRouter.post("/auth-provider", async (c) => {
|
|||||||
* Only available when needsSetup is true (no super user = fresh install).
|
* Only available when needsSetup is true (no super user = fresh install).
|
||||||
*/
|
*/
|
||||||
setupRouter.post("/auth-provider/test", async (c) => {
|
setupRouter.post("/auth-provider/test", async (c) => {
|
||||||
|
const ip = c.req.header("x-forwarded-for")?.split(",")[0]?.trim() ?? "unknown";
|
||||||
|
if (!checkSetupRateLimit(ip)) {
|
||||||
|
return c.json({ ok: false, error: "Too many requests. Please try again later." }, 429);
|
||||||
|
}
|
||||||
|
|
||||||
const db = getDb();
|
const db = getDb();
|
||||||
|
|
||||||
// Guard: only allow during fresh install (no super user yet)
|
// Guard: only allow during fresh install (no super user yet)
|
||||||
|
|||||||
@@ -3,10 +3,22 @@ server {
|
|||||||
root /usr/share/nginx/html;
|
root /usr/share/nginx/html;
|
||||||
index index.html;
|
index index.html;
|
||||||
|
|
||||||
|
# Security headers
|
||||||
|
add_header X-Content-Type-Options "nosniff" always;
|
||||||
|
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||||
|
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||||
|
add_header X-XSS-Protection "1; mode=block" always;
|
||||||
|
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
|
||||||
|
|
||||||
# Cache static assets
|
# Cache static assets
|
||||||
location ~* \.(js|css|png|svg|ico|woff2)$ {
|
location ~* \.(js|css|png|svg|ico|woff2)$ {
|
||||||
expires 1y;
|
expires 1y;
|
||||||
add_header Cache-Control "public, immutable";
|
add_header Cache-Control "public, immutable";
|
||||||
|
add_header X-Content-Type-Options "nosniff" always;
|
||||||
|
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||||
|
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||||
|
add_header X-XSS-Protection "1; mode=block" always;
|
||||||
|
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
|
||||||
}
|
}
|
||||||
|
|
||||||
# Proxy API calls to the API service
|
# Proxy API calls to the API service
|
||||||
|
|||||||
Reference in New Issue
Block a user