Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
+142
@@ -0,0 +1,142 @@
|
||||
// AK-P14b (P14 email marketing) — signed HMAC tokens for campaign unsubscribe
|
||||
// (one-click / List-Unsubscribe) and double-opt-in confirmation.
|
||||
//
|
||||
// Mirrors @hivegrid/email-sequences/unsubscribe-token but scoped to the typed
|
||||
// CRM Kontakt (tenantId + kontaktId + optional campaignId), not EmailSequenceRun.
|
||||
// The token IS the authentication boundary for the public routes (no session),
|
||||
// so the same secret signs (send-engine S3) and verifies (public routes S4).
|
||||
// Secret is injectable for tests (default: process.env.MARKETING_TOKEN_SECRET).
|
||||
|
||||
import { createHmac, timingSafeEqual } from "node:crypto";
|
||||
|
||||
type EnvRecord = Record<string, string | undefined>;
|
||||
|
||||
export type MarketingTokenPurpose = "unsub" | "optin";
|
||||
|
||||
export interface MarketingTokenPayload {
|
||||
/** "unsub" = unsubscribe link; "optin" = double-opt-in confirmation. */
|
||||
purpose: MarketingTokenPurpose;
|
||||
tenantId: string;
|
||||
kontaktId: string;
|
||||
/** Set for a campaign-scoped unsubscribe; null otherwise. */
|
||||
campaignId: string | null;
|
||||
/** Issued-at unix seconds (diagnostics only). */
|
||||
iat: number;
|
||||
}
|
||||
|
||||
export interface SignMarketingTokenInput {
|
||||
purpose: MarketingTokenPurpose;
|
||||
tenantId: string;
|
||||
kontaktId: string;
|
||||
campaignId?: string | null;
|
||||
now?: () => Date;
|
||||
secret?: string;
|
||||
env?: EnvRecord;
|
||||
}
|
||||
|
||||
export interface VerifyMarketingTokenOptions {
|
||||
secret?: string;
|
||||
env?: EnvRecord;
|
||||
/** When set, the token must carry this purpose or verification fails. */
|
||||
expectedPurpose?: MarketingTokenPurpose;
|
||||
}
|
||||
|
||||
export class MarketingTokenSecretMissingError extends Error {
|
||||
override readonly name = "MarketingTokenSecretMissingError";
|
||||
constructor() {
|
||||
super("MARKETING_TOKEN_SECRET env var is not set; cannot sign or verify marketing tokens.");
|
||||
}
|
||||
}
|
||||
|
||||
const TOKEN_VERSION = "m1";
|
||||
const MIN_SECRET_BYTES = 32;
|
||||
|
||||
function getSecret(override?: string, env?: EnvRecord): Buffer {
|
||||
const raw = override ?? env?.MARKETING_TOKEN_SECRET ?? env?.LEAD_CONVERSION_SECRET;
|
||||
if (!raw || raw.length < MIN_SECRET_BYTES) throw new MarketingTokenSecretMissingError();
|
||||
return Buffer.from(raw, "utf8");
|
||||
}
|
||||
|
||||
function b64uEncode(input: Buffer | string): string {
|
||||
const buf = Buffer.isBuffer(input) ? input : Buffer.from(input, "utf8");
|
||||
return buf.toString("base64url");
|
||||
}
|
||||
|
||||
function b64uDecode(input: string): Buffer | null {
|
||||
if (!/^[A-Za-z0-9_-]+$/u.test(input)) return null;
|
||||
try {
|
||||
return Buffer.from(input, "base64url");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function nowSec(now?: () => Date): number {
|
||||
return Math.floor((now ? now() : new Date()).getTime() / 1000);
|
||||
}
|
||||
|
||||
export function signMarketingToken(input: SignMarketingTokenInput): string {
|
||||
if (!input.tenantId || !input.kontaktId) {
|
||||
throw new TypeError("signMarketingToken: tenantId and kontaktId required");
|
||||
}
|
||||
const secret = getSecret(input.secret, input.env);
|
||||
const payload: MarketingTokenPayload = {
|
||||
purpose: input.purpose,
|
||||
tenantId: input.tenantId,
|
||||
kontaktId: input.kontaktId,
|
||||
campaignId: input.campaignId ?? null,
|
||||
iat: nowSec(input.now),
|
||||
};
|
||||
const payloadB64 = b64uEncode(JSON.stringify(payload));
|
||||
const sig = createHmac("sha256", secret).update(`${TOKEN_VERSION}.${payloadB64}`).digest();
|
||||
return `${TOKEN_VERSION}.${payloadB64}.${b64uEncode(sig)}`;
|
||||
}
|
||||
|
||||
export function verifyMarketingToken(token: string | null | undefined, options: VerifyMarketingTokenOptions = {}): MarketingTokenPayload | null {
|
||||
if (!token || typeof token !== "string") return null;
|
||||
const parts = token.split(".");
|
||||
if (parts.length !== 3) return null;
|
||||
const [version, payloadB64, sigB64] = parts;
|
||||
if (version !== TOKEN_VERSION) return null;
|
||||
let secret: Buffer;
|
||||
try {
|
||||
secret = getSecret(options.secret, options.env);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const expected = createHmac("sha256", secret).update(`${version}.${payloadB64}`).digest();
|
||||
const actual = b64uDecode(sigB64);
|
||||
if (!actual || actual.length !== expected.length) return null;
|
||||
if (!timingSafeEqual(actual, expected)) return null;
|
||||
const payloadBuf = b64uDecode(payloadB64);
|
||||
if (!payloadBuf) return null;
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(payloadBuf.toString("utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!parsed || typeof parsed !== "object") return null;
|
||||
const rec = parsed as Record<string, unknown>;
|
||||
const purpose = rec.purpose;
|
||||
if (purpose !== "unsub" && purpose !== "optin") return null;
|
||||
if (options.expectedPurpose && purpose !== options.expectedPurpose) return null;
|
||||
if (typeof rec.tenantId !== "string" || rec.tenantId.length === 0) return null;
|
||||
if (typeof rec.kontaktId !== "string" || rec.kontaktId.length === 0) return null;
|
||||
return {
|
||||
purpose,
|
||||
tenantId: rec.tenantId,
|
||||
kontaktId: rec.kontaktId,
|
||||
campaignId: typeof rec.campaignId === "string" ? rec.campaignId : null,
|
||||
iat: typeof rec.iat === "number" ? rec.iat : 0,
|
||||
};
|
||||
}
|
||||
|
||||
/** Convenience: the default (env) secret used by sign helpers in tests. */
|
||||
export function signWithEnv(input: Omit<SignMarketingTokenInput, "env">): string {
|
||||
return signMarketingToken({ env: process.env, ...input });
|
||||
}
|
||||
|
||||
export function verifyWithEnv(token: string | null | undefined, options: Omit<VerifyMarketingTokenOptions, "env"> = {}): MarketingTokenPayload | null {
|
||||
return verifyMarketingToken(token, { env: process.env, ...options });
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { MarketingTokenSecretMissingError, signMarketingToken, verifyMarketingToken } from "./marketingToken.server";
|
||||
|
||||
const SECRET = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
|
||||
describe("marketingToken", () => {
|
||||
it("signs and verifies a round-trip unsubscribe token", () => {
|
||||
const token = signMarketingToken({ purpose: "unsub", tenantId: "t1", kontaktId: "k1", campaignId: "c1", secret: SECRET });
|
||||
const payload = verifyMarketingToken(token, { secret: SECRET });
|
||||
expect(payload).toMatchObject({ purpose: "unsub", tenantId: "t1", kontaktId: "k1", campaignId: "c1" });
|
||||
});
|
||||
|
||||
it("verifies an opt-in token and enforces expectedPurpose", () => {
|
||||
const token = signMarketingToken({ purpose: "optin", tenantId: "t1", kontaktId: "k1", secret: SECRET });
|
||||
expect(verifyMarketingToken(token, { secret: SECRET, expectedPurpose: "optin" })?.kontaktId).toBe("k1");
|
||||
expect(verifyMarketingToken(token, { secret: SECRET, expectedPurpose: "unsub" })).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects a tampered payload", () => {
|
||||
const token = signMarketingToken({ purpose: "unsub", tenantId: "t1", kontaktId: "k1", secret: SECRET });
|
||||
const [v, , sig] = token.split(".");
|
||||
const forged = `${v}.${Buffer.from(JSON.stringify({ purpose: "unsub", tenantId: "t1", kontaktId: "EVIL", campaignId: null, iat: 1 })).toString("base64url")}.${sig}`;
|
||||
expect(verifyMarketingToken(forged, { secret: SECRET })).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects a wrong-secret signature and malformed tokens", () => {
|
||||
const token = signMarketingToken({ purpose: "unsub", tenantId: "t1", kontaktId: "k1", secret: SECRET });
|
||||
expect(verifyMarketingToken(token, { secret: "x".repeat(64) })).toBeNull();
|
||||
expect(verifyMarketingToken("garbage", { secret: SECRET })).toBeNull();
|
||||
expect(verifyMarketingToken("", { secret: SECRET })).toBeNull();
|
||||
});
|
||||
|
||||
it("throws when the secret is missing/too short on sign", () => {
|
||||
expect(() => signMarketingToken({ purpose: "unsub", tenantId: "t1", kontaktId: "k1", secret: "short" })).toThrow(MarketingTokenSecretMissingError);
|
||||
});
|
||||
});
|
||||
+1
-1
@@ -6,7 +6,7 @@ import {
|
||||
type SignUnsubscribeTokenInput,
|
||||
type UnsubscribeTokenPayload,
|
||||
type VerifyUnsubscribeTokenOptions,
|
||||
} from "@toolctrl/email-sequences/unsubscribe-token";
|
||||
} from "@hivegrid/email-sequences/unsubscribe-token";
|
||||
|
||||
export { UnsubscribeTokenSecretMissingError };
|
||||
export type { SignUnsubscribeTokenInput, UnsubscribeTokenPayload, VerifyUnsubscribeTokenOptions };
|
||||
|
||||
Reference in new issue
Block a user