Skip to content
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,8 @@ NEXT_PUBLIC_AWS_RUM_IDENTITY_POOL_ID=
PEPE_CACHE_TTL_MINUTES=10
PEPE_CACHE_MAX_ITEMS=500
IPFS_GATEWAY=https://ipfs.io/ipfs/

# SERVER-SIDE CLIENT IDENTIFICATION (for SSR requests)
# Used to sign server-side API requests with HMAC-SHA256
SSR_CLIENT_ID=
SSR_CLIENT_SECRET=
14 changes: 10 additions & 4 deletions .github/workflows/build-upload-deploy-prod.yml
Original file line number Diff line number Diff line change
Expand Up @@ -80,12 +80,18 @@ jobs:
--version-label "${{ env.COMMIT_SHA }}" \
--description "${{ env.COMMIT_MESSAGE }}"

- name: Deploy new Version to ElasticBeanstalk
- name: Deploy new Version to ElasticBeanstalk with Runtime Environment Variables
env:
SSR_CLIENT_ID: ${{ secrets.SSR_CLIENT_ID }}
SSR_CLIENT_SECRET: ${{ secrets.SSR_CLIENT_SECRET }}
run: |
aws elasticbeanstalk update-environment \
--application-name "${{ env.BEANSTALK_APP_NAME }}" \
--environment-name "${{ env.BEANSTALK_ENV_NAME }}" \
--version-label "${{ env.COMMIT_SHA }}"
--application-name "${{ env.BEANSTALK_APP_NAME }}" \
--environment-name "${{ env.BEANSTALK_ENV_NAME }}" \
--version-label "${{ env.COMMIT_SHA }}" \
--option-settings \
"Namespace=aws:elasticbeanstalk:application:environment,OptionName=SSR_CLIENT_ID,Value=${SSR_CLIENT_ID}" \
"Namespace=aws:elasticbeanstalk:application:environment,OptionName=SSR_CLIENT_SECRET,Value=${SSR_CLIENT_SECRET}"

- name: Check Elastic Beanstalk health and readiness (120s warmup then 20 retries with 60s delay)
run: |
Expand Down
14 changes: 12 additions & 2 deletions __tests__/services/common-api.more.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ describe("commonApi utility methods", () => {
it("commonApiPut posts JSON body", async () => {
(global.fetch as jest.Mock).mockResolvedValue({
ok: true,
status: 200,
json: async () => ({ ok: 1 }),
headers: new Headers({ "content-type": "application/json" }),
});
const res = await commonApiPut({ endpoint: "e", body: { a: 1 } });
expect(res).toEqual({ ok: 1 });
Expand All @@ -39,9 +41,11 @@ describe("commonApi utility methods", () => {
});

it("commonApiDeleteWithBody deletes with body", async () => {
(global.fetch as jest.Mock).mockResolvedValue({
(globalThis.fetch as jest.Mock).mockResolvedValue({
ok: true,
status: 200,
json: async () => ({ r: 2 }),
headers: new Headers({ "content-type": "application/json" }),
});
const res = await commonApiDeleteWithBody({
endpoint: "del",
Expand All @@ -63,7 +67,11 @@ describe("commonApi utility methods", () => {
});

it("commonApiDelete sends DELETE request", async () => {
(global.fetch as jest.Mock).mockResolvedValue({ ok: true });
(global.fetch as jest.Mock).mockResolvedValue({
ok: true,
status: 200,
headers: new Headers(),
});
Comment thread
prxt6529 marked this conversation as resolved.
await commonApiDelete({ endpoint: "x" });
expect(globalThis.fetch).toHaveBeenCalledWith(
"https://api.test.6529.io/api/x",
Expand All @@ -82,7 +90,9 @@ describe("commonApi utility methods", () => {
const form = new FormData();
(global.fetch as jest.Mock).mockResolvedValue({
ok: true,
status: 200,
json: async () => ({ res: 3 }),
headers: new Headers({ "content-type": "application/json" }),
});
const { commonApiPostForm } = await import("@/services/api/common-api");
const result = await commonApiPostForm({ endpoint: "f", body: form });
Expand Down
1 change: 1 addition & 0 deletions app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export const fetchCache = "force-no-store";

import "@/lib/fetch/ssrFetch";
import "@/components/drops/create/lexical/lexical.styles.scss";
import "@/styles/Home.module.scss";
import "@/styles/seize-bootstrap.scss";
Expand Down
8 changes: 8 additions & 0 deletions config/serverEnv.schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { z } from "zod";

export const serverEnvSchema = z.object({
SSR_CLIENT_ID: z.string().min(1, "SSR_CLIENT_ID is required"),
SSR_CLIENT_SECRET: z.string().min(1, "SSR_CLIENT_SECRET is required"),
});

export type ServerEnv = z.infer<typeof serverEnvSchema>;
35 changes: 35 additions & 0 deletions config/serverEnv.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { serverEnvSchema, type ServerEnv } from "./serverEnv.schema";

if (globalThis.window !== undefined) {
throw new TypeError("serverEnv can only be accessed on the server side");
}

const getServerEnv = (): ServerEnv | null => {
if (typeof process === "undefined" || !process.env) {
return null;
}

const raw = {
SSR_CLIENT_ID: process.env.SSR_CLIENT_ID,
SSR_CLIENT_SECRET: process.env.SSR_CLIENT_SECRET,
};

const parsed = serverEnvSchema.safeParse(raw);
if (!parsed.success) {
return null;
}

return parsed.data;
};

export const getServerEnvOrThrow = (): ServerEnv => {
const env = getServerEnv();
if (!env) {
throw new Error(
"SSR_CLIENT_ID and SSR_CLIENT_SECRET must be set as runtime environment variables"
);
}
return env;
};

export const serverEnv: ServerEnv | null = getServerEnv();
1 change: 1 addition & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ export default defineConfig([globalIgnores([
"scripts/**",
"**/next.config.*",
"config/env.ts",
"config/serverEnv.ts",
"__tests__/config/env.base-endpoint.test.ts",
"**/playwright.config.ts",
"tests/**",
Expand Down
101 changes: 101 additions & 0 deletions helpers/server-signature.helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { createHmac } from "node:crypto";

/**
* Generates a client signature for server-side authentication.
*
* The signature scheme uses HMAC-SHA256 to create a cryptographic signature
* from a payload containing the client ID, timestamp, HTTP method, and path.
* The timestamp is used to prevent replay attacks within a configurable time window
* (typically 300 seconds / 5 minutes). The signature must match exactly on both
* client and server for authentication to succeed.
*
* @param clientId - The client identifier (must be a non-empty string)
* @param secret - The shared secret key for HMAC signing (must be a non-empty string)
* @param method - The HTTP method (will be normalized to uppercase, must be non-empty)
* @param path - The request path including query string if present (pathname + search, e.g., '/api/users?page=1'; must be non-empty)
* @param timestamp - Optional Unix timestamp in seconds. If not provided, uses current time.
* @returns An object containing the clientId, timestamp, and generated signature
* @throws {TypeError} If called in a browser environment or if any required parameter is invalid
*
* @example
* ```ts
* const { signature } = generateClientSignature(
* 'my-client-id',
* 'my-secret',
* 'POST',
* '/api/users?page=1'
* );
* ```
*/
export function generateClientSignature(
clientId: string,
secret: string,
method: string,
path: string,
timestamp?: number
): { clientId: string; timestamp: number; signature: string } {
if (globalThis.window !== undefined) {
throw new TypeError(
"generateClientSignature can only be used on the server side"
);
}

if (typeof clientId !== "string" || clientId.trim().length === 0) {
throw new TypeError(
"generateClientSignature: clientId must be a non-empty string"
);
}

if (typeof secret !== "string" || secret.trim().length === 0) {
throw new TypeError(
"generateClientSignature: secret must be a non-empty string"
);
}

if (typeof method !== "string" || method.trim().length === 0) {
throw new TypeError(
"generateClientSignature: method must be a non-empty string"
);
}

if (typeof path !== "string" || path.trim().length === 0) {
throw new TypeError(
"generateClientSignature: path must be a non-empty string"
);
}

const normalizedMethod = method.toUpperCase();
const ts = timestamp ?? Math.floor(Date.now() / 1000);
const payload = `${clientId}\n${ts}\n${normalizedMethod}\n${path}`;
const signature = createHmac("sha256", secret).update(payload).digest("hex");

return {
clientId,
timestamp: ts,
signature,
};
}
Comment thread
prxt6529 marked this conversation as resolved.

export function generateWafSignature(clientId: string, secret: string): string {
if (globalThis.window !== undefined) {
throw new TypeError(
"generateWafSignature can only be used on the server side"
);
}

if (typeof clientId !== "string" || clientId.trim().length === 0) {
throw new TypeError(
"generateWafSignature: clientId must be a non-empty string"
);
}

if (typeof secret !== "string" || secret.trim().length === 0) {
throw new TypeError(
"generateWafSignature: secret must be a non-empty string"
);
}

const signature = createHmac("sha256", secret).update(clientId).digest("hex");

return signature;
Comment thread
prxt6529 marked this conversation as resolved.
}
130 changes: 130 additions & 0 deletions lib/fetch/ssrFetch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import { publicEnv } from "@/config/env";
import { getServerEnvOrThrow } from "@/config/serverEnv";
import {
generateClientSignature,
generateWafSignature,
} from "@/helpers/server-signature.helpers";
import { getAppCommonHeaders } from "@/helpers/server.app.helpers";

const getOriginalFetch = (): typeof fetch => {
if (globalThis.fetch === undefined) {
throw new TypeError(
"fetch not available in current runtime. This module requires a fetch implementation."
);
}
if (typeof globalThis.fetch !== "function") {
throw new TypeError(
"fetch is not a function in current runtime. Expected a function but got a different type."
);
}
return globalThis.fetch;
};

const originalFetch = getOriginalFetch();

const isApiRequest = (url: string | URL): boolean => {
const urlString = typeof url === "string" ? url : url.toString();
try {
const parsedUrl = new URL(urlString, publicEnv.API_ENDPOINT);
return parsedUrl.origin === new URL(publicEnv.API_ENDPOINT).origin;
} catch {
return false;
}
};

const extractPathFromUrl = (url: string | URL, baseUrl: string): string => {
const urlString = typeof url === "string" ? url : url.toString();
try {
const parsedUrl = new URL(urlString, baseUrl);
return parsedUrl.pathname + parsedUrl.search;
} catch {
return "";
}
};

const enhancedFetch: typeof fetch = async (
input: RequestInfo | URL,
init?: RequestInit
): Promise<Response> => {
if (globalThis.window !== undefined) {
return originalFetch(input, init);
}

let url: string;
if (typeof input === "string") {
url = input;
} else if (input instanceof URL) {
url = input.toString();
} else {
url = input.url;
}

if (!isApiRequest(url)) {
return originalFetch(input, init);
}

let clientId: string;
let clientSecret: string;

try {
const env = getServerEnvOrThrow();
clientId = env.SSR_CLIENT_ID;
clientSecret = env.SSR_CLIENT_SECRET;
} catch {
return originalFetch(input, init);
}
Comment thread
prxt6529 marked this conversation as resolved.
Outdated

const method = (
init?.method ??
(input instanceof Request ? input.method : undefined) ??
"GET"
).toUpperCase();
const path = extractPathFromUrl(url, publicEnv.API_ENDPOINT);

if (!path) {
return originalFetch(input, init);
}

const signatureData = generateClientSignature(
clientId,
clientSecret,
method,
path
);

const wafSignature = generateWafSignature(clientId, clientSecret);

const baseHeaders = input instanceof Request ? input.headers : undefined;
const enhancedHeaders = new Headers(baseHeaders);
if (init?.headers) {
new Headers(init.headers).forEach((value, key) => {
enhancedHeaders.set(key, value);
});
}

enhancedHeaders.set("x-6529-internal-id", signatureData.clientId);
enhancedHeaders.set("x-6529-internal-signature", signatureData.signature);
enhancedHeaders.set(
"x-6529-internal-timestamp",
signatureData.timestamp.toString()
);
enhancedHeaders.set("x-6529-internal-waf-signature", wafSignature);

try {
const appHeaders = await getAppCommonHeaders();
Object.entries(appHeaders).forEach(([key, value]) => {
enhancedHeaders.set(key, value);
});
} catch {}

return originalFetch(input, {
...init,
headers: enhancedHeaders,
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
};

if (globalThis.window === undefined) {
globalThis.fetch = enhancedFetch;
}

export { enhancedFetch as ssrFetch };
Loading
Loading