33 lines
1.6 KiB
TypeScript
33 lines
1.6 KiB
TypeScript
import { createHash } from "node:crypto";
|
|
|
|
const SIGNUP_CREATION_REQUEST_KEY_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
|
|
export function isSignupCreationRequestKey(value: string): boolean {
|
|
return SIGNUP_CREATION_REQUEST_KEY_PATTERN.test(value);
|
|
}
|
|
|
|
/**
|
|
* Binds tenant creation to the immutable persisted registration identity.
|
|
* Resends rotate the verification token, but they must never rotate the
|
|
* bootstrap identity: an already-committed bootstrap must remain replayable
|
|
* after a concurrent resend wins the token-consumption CAS.
|
|
*/
|
|
export function deriveVerificationCreationRequestKey(registrationId: string): string {
|
|
return deriveBoundCreationRequestKey("signup-verification-creation-request:v2", registrationId);
|
|
}
|
|
|
|
/** Stable next key for resend response-loss recovery and double-click races. */
|
|
export function deriveResendCreationRequestKey(registrationId: string, previousVerificationToken: string): string {
|
|
return deriveBoundCreationRequestKey("signup-verification-resend-request:v1", registrationId, previousVerificationToken);
|
|
}
|
|
|
|
function deriveBoundCreationRequestKey(domain: string, ...parts: string[]): string {
|
|
const digest = createHash("sha256").update(domain);
|
|
for (const part of parts) digest.update("\0").update(part.trim());
|
|
const bytes = digest.digest().subarray(0, 16);
|
|
bytes[6] = (bytes[6]! & 0x0f) | 0x40;
|
|
bytes[8] = (bytes[8]! & 0x3f) | 0x80;
|
|
const hex = Buffer.from(bytes).toString("hex");
|
|
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
}
|