Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
import { z } from "zod";
import { getConfig } from "@app/lib/config/env";
import { BadRequestError, ForbiddenRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { matchesAllowedEmailDomain, normalizeEmail } from "@app/lib/validator";
import { PasswordPolicySchema } from "@app/lib/validator/password-policy";
import { authRateLimit, smtpRateLimit } from "@app/server/config/rateLimiter";
import { addAuthOriginDomainCookie } from "@app/server/lib/cookie";
import { GenericResourceNameSchema } from "@app/server/lib/schemas";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { CompleteAccountType } from "@app/services/auth/auth-signup-type";
import { AuthMode } from "@app/services/auth/auth-type";
import { getServerCfg } from "@app/services/super-admin/super-admin-service";
import { PostHogEventTypes, SignupAttributionType, SignupSource } from "@app/services/telemetry/telemetry-types";
import { SanitizedUserSchema } from "../sanitizedSchemas";
export const registerSignupRouter = async (server: FastifyZodProvider) => {
server.route({
url: "/email/signup",
method: "POST",
config: {
rateLimit: smtpRateLimit({
keyGenerator: (req) => {
const email = (req.body as { email?: string })?.email;
return email ? normalizeEmail(email).substring(0, 100) : req.realIp;
}
})
},
schema: {
operationId: "beginEmailSignupV3",
body: z.object({
email: z.string().trim().email().max(255),
captchaToken: z.string().trim().max(5000).optional()
}),
response: {
200: z.object({
message: z.string(),
cooldownSeconds: z.number()
})
}
},
handler: async (req) => {
const { email } = req.body;
const serverCfg = await getServerCfg();
if (!serverCfg.allowSignUp) {
throw new ForbiddenRequestError({
message: "Signup's are disabled"
});
}
if (serverCfg?.allowedSignUpDomain) {
const domain = email.split("@")[1];
if (!matchesAllowedEmailDomain(email, serverCfg.allowedSignUpDomain)) {
throw new ForbiddenRequestError({
message: `Email with a domain (@${domain}) is not supported`
});
}
}
const { cooldownSeconds } = await server.services.signup.beginEmailSignupProcess({
email,
ip: req.realIp,
captchaToken: req.body.captchaToken
});
return { message: `Sent an email verification code to ${email}`, cooldownSeconds };
}
});
server.route({
url: "/email/verify",
method: "POST",
config: {
rateLimit: smtpRateLimit({
keyGenerator: (req) => {
const email = (req.body as { email?: string })?.email;
return email ? normalizeEmail(email).substring(0, 100) : req.realIp;
}
})
},
schema: {
operationId: "verifyEmailSignupV3",
body: z.object({
email: z.string().trim().email().max(255),
code: z.string().trim().length(6)
}),
response: {
200: z.object({
message: z.string(),
token: z.string(),
user: SanitizedUserSchema
})
}
},
handler: async (req) => {
const serverCfg = await getServerCfg();
if (!serverCfg.allowSignUp) {
throw new ForbiddenRequestError({
message: "Signup's are disabled"
});
}
const { token, user } = await server.services.signup.verifyEmailSignup(req.body.email, req.body.code);
return { message: "Successfully verified email", token, user };
}
});
server.route({
url: "/complete-account",
method: "POST",
config: {
rateLimit: authRateLimit
},
schema: {
operationId: "completeAccountSignupV3",
body: z.discriminatedUnion("type", [
z.object({
type: z.literal(CompleteAccountType.Email),
email: z.string().trim(),
firstName: z.string().trim(),
lastName: z.string().trim().optional(),
attributionSource: z.string().trim().optional(),
password: PasswordPolicySchema,
organizationName: GenericResourceNameSchema.optional(),
hubspotUtk: z.string().trim().max(512).optional()
}),
z.object({
type: z.literal(CompleteAccountType.Alias),
code: z.string().trim(),
hubspotUtk: z.string().trim().max(512).optional()
})
]),
response: {
200: z.object({
message: z.string(),
user: SanitizedUserSchema,
token: z.string()
})
}
},
handler: async (req, res) => {
const userAgent = req.headers["user-agent"];
if (!userAgent) throw new BadRequestError({ message: "User agent header is required" });
const appCfg = getConfig();
const { user, accessToken, refreshToken, authMethod, organizationId, invitingOrgId, isInvitedUser } =
await server.services.signup.completeAccount({
...req.body,
ip: req.realIp,
userAgent,
authorization: req.headers.authorization as string
});
if (user.email) {
void server.services.telemetry.sendLoopsEvent(user.email, user.firstName || "", user.lastName || "");
void server.services.telemetry.sendHubSpotSignupEvent(
user.email,
isInvitedUser ? "invite" : authMethod,
user.firstName || "",
user.lastName || "",
req.body.hubspotUtk
);
}
const bodyAttributionSource = "attributionSource" in req.body ? req.body.attributionSource : undefined;
let attributionType: SignupAttributionType | undefined;
if (isInvitedUser) {
attributionType = SignupAttributionType.SystemDerived;
} else if (bodyAttributionSource) {
attributionType = SignupAttributionType.UserProvided;
}
// Invited signups create no org of their own, so fall back to the inviting org. The
// OrganizationCreated event below stays on `organizationId`, which is only set when one was created.
const signupOrganizationId = organizationId ?? invitingOrgId;
void server.services.telemetry.sendPostHogEvents({
event: PostHogEventTypes.UserSignedUp,
distinctId: user.username ?? "",
...(signupOrganizationId ? { organizationId: signupOrganizationId } : {}),
properties: {
username: user.username,
email: user.email ?? "",
attributionSource: isInvitedUser ? "Team Invite" : bodyAttributionSource,
...(attributionType ? { attributionType } : {}),
signupSource: isInvitedUser ? SignupSource.TeamInvite : SignupSource.SelfServe,
signupMethod: isInvitedUser ? "invite" : authMethod
}
});
if (organizationId) {
void server.services.telemetry.sendPostHogEvents({
event: PostHogEventTypes.OrganizationCreated,
distinctId: user.username ?? "",
organizationId,
properties: {
name: "organizationName" in req.body ? (req.body.organizationName as string) : ""
}
});
}
const signupDistinctId = user.username ?? user.email ?? "";
if (signupDistinctId) {
void server.services.telemetry.identifyUser(
signupDistinctId,
{
email: user.email ?? undefined,
username: user.username,
userId: user.id,
firstName: user.firstName ?? undefined,
lastName: user.lastName ?? undefined,
isEmailVerified: user.isEmailVerified ?? undefined,
isMfaEnabled: user.isMfaEnabled ?? undefined,
superAdmin: user.superAdmin ?? undefined
},
{ skipDedup: true }
);
}
void res.setCookie("jid", refreshToken, {
httpOnly: true,
path: "/api",
sameSite: "strict",
secure: appCfg.HTTPS_ENABLED
});
addAuthOriginDomainCookie(res);
return { message: "Successfully set up account", user, token: accessToken };
}
});
server.route({
url: "/onboarding",
method: "POST",
config: {
rateLimit: authRateLimit
},
schema: {
operationId: "recordSignupOnboardingV3",
body: z.object({
selectedProduct: z
.enum(["secret-manager", "cert-manager", "kms", "secret-scanning", "pam", "agent-vault", "exploring"])
.optional(),
// An empty array means "just exploring".
selectedProducts: z
.enum(["secret-manager", "cert-manager", "kms", "secret-scanning", "pam", "agent-vault"])
.array()
.max(6)
.optional(),
launchDestination: z
.enum([
"secret-manager",
"cert-manager",
"kms",
"secret-scanning",
"pam",
"agent-vault",
"organization-overview"
])
.optional(),
attributionSource: z.string().trim().max(512).optional()
}),
response: {
200: z.object({
message: z.string()
})
}
},
onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
const distinctId = getTelemetryDistinctId(req);
const organizationId = req.permission.orgId;
// Persisted for SQL analytics alongside the PostHog events; a DB failure must not
// take the telemetry down with it.
if (organizationId) {
try {
await server.services.signup.recordOnboardingResponse({
userId: req.permission.id,
orgId: organizationId,
selectedProducts: req.body.selectedProducts,
launchDestination: req.body.launchDestination,
attributionSource: req.body.attributionSource
});
} catch (err) {
logger.error(err, "Failed to record signup onboarding response");
}
}
if (req.body.selectedProduct) {
void server.services.telemetry.sendPostHogEvents({
event: PostHogEventTypes.SignupProductSelected,
distinctId,
...(organizationId ? { organizationId } : {}),
properties: {
product: req.body.selectedProduct
}
});
}
if (req.body.selectedProducts) {
const { selectedProducts } = req.body;
const isExploring = selectedProducts.length === 0;
void server.services.telemetry.sendPostHogEvents({
event: PostHogEventTypes.SignupProductsSubmitted,
distinctId,
...(organizationId ? { organizationId } : {}),
properties: {
products: selectedProducts,
productCount: selectedProducts.length,
isExploring,
$set_once: {
signupProducts: selectedProducts,
signupProductCount: selectedProducts.length,
signupIsExploring: isExploring
}
}
});
}
if (req.body.launchDestination) {
void server.services.telemetry.sendPostHogEvents({
event: PostHogEventTypes.SignupLaunchDestinationSelected,
distinctId,
...(organizationId ? { organizationId } : {}),
properties: {
launchDestination: req.body.launchDestination
}
});
}
if (req.body.attributionSource) {
void server.services.telemetry.sendPostHogEvents({
event: PostHogEventTypes.SignupAttributionProvided,
distinctId,
...(organizationId ? { organizationId } : {}),
properties: {
attributionSource: req.body.attributionSource,
attributionType: SignupAttributionType.UserProvided
}
});
}
return { message: "Onboarding response recorded" };
}
});
};