Initial local backup snapshot

This commit is contained in:
Selecta Keke 2026-06-24 00:02:55 -03:00
commit acd9e14ba5
367 changed files with 118038 additions and 0 deletions

962
server/_core/auth.ts Normal file
View file

@ -0,0 +1,962 @@
import { COOKIE_NAME, ONE_YEAR_MS } from "@shared/const";
import { ForbiddenError } from "@shared/_core/errors";
import { SignJWT, jwtVerify } from "jose";
import * as crypto from "node:crypto";
import { promisify } from "node:util";
import { parse as parseCookieHeader } from "cookie";
import type { Request, Response } from "express";
import type { User } from "../../drizzle/schema";
import * as db from "../db";
import { ENV } from "./env";
import { getSessionCookieOptions } from "./cookies";
import { canSendOperationalEmails, sendOperationalEmail } from "../mailer";
const scryptAsync = promisify(crypto.scrypt);
const argon2Async =
typeof (crypto as any).argon2 === "function"
? promisify((crypto as any).argon2)
: null;
const KEY_LENGTH = 64;
const LOGIN_FAILURE_LIMIT = 5;
const LOGIN_LOCK_DURATION_MS = 15 * 60 * 1000;
const MFA_CODE_TTL_MS = 10 * 60 * 1000;
const MFA_CODE_ATTEMPT_LIMIT = 5;
const RETENTION_REPORT_SETTING_KEY = "retention.lastReport";
const SYSTEM_ACTOR_USER_ID = 0;
const INTERNAL_MFA_POLICY = {
super_admin: {
required: true,
preferredMethod: "authenticator_app",
enforcedMethod: "authenticator_app",
emailFallbackAllowed: false,
phaseLabel: "Phase 2 cible",
},
admin: {
required: true,
preferredMethod: "authenticator_app",
enforcedMethod: "authenticator_app",
emailFallbackAllowed: false,
phaseLabel: "Phase 2 active",
},
directrice: {
required: true,
preferredMethod: "authenticator_app",
enforcedMethod: "authenticator_app",
emailFallbackAllowed: false,
phaseLabel: "Phase 2 active",
},
accueil: {
required: true,
preferredMethod: "authenticator_app",
enforcedMethod: null,
emailFallbackAllowed: true,
phaseLabel: "Phase 1 active",
},
service_terrain: {
required: true,
preferredMethod: "authenticator_app",
enforcedMethod: null,
emailFallbackAllowed: true,
phaseLabel: "Phase 1 active",
},
logistique_controle: {
required: true,
preferredMethod: "authenticator_app",
enforcedMethod: null,
emailFallbackAllowed: true,
phaseLabel: "Phase 1 active",
},
} as const;
class AccountLockedError extends Error {
constructor(public lockedUntil: Date) {
super(`Compte temporairement verrouillé jusqu'au ${lockedUntil.toLocaleTimeString("fr-FR", {
hour: "2-digit",
minute: "2-digit",
})}.`);
}
}
class MfaChallengeRequiredError extends Error {
constructor(
public challengeType: "email" | "totp",
public challengeToken: string,
public expiresAt: Date,
public maskedEmail?: string,
) {
super("Code de verification requis");
}
}
type JwtPayload = {
userId: number;
openId: string;
};
type BootstrapUserConfig = {
email: string;
password: string;
name?: string;
role?: User["role"];
};
function createBootstrapUser(config: BootstrapUserConfig, index: number): User {
const email = normalizeEmail(config.email);
const now = new Date();
return {
id: index + 1,
openId: email,
name: config.name ?? email.split("@")[0] ?? "Utilisateur",
email,
passwordHash: null,
loginMethod: "bootstrap_jwt",
role: config.role ?? "admin",
canManageLogistics: config.role === "super_admin",
delegatedSalleSignerUserId: null,
privacyConsentVersion: null,
privacyConsentAcceptedAt: null,
privacyConsentContext: null,
failedLoginAttempts: 0,
lockedUntil: null,
mfaEnabled: false,
mfaMethod: null,
mfaChallengeToken: null,
mfaCodeHash: null,
mfaCodeExpiresAt: null,
mfaCodeAttempts: 0,
mfaTotpSecretEncrypted: null,
mfaTotpPendingSecretEncrypted: null,
deletionRequestedAt: null,
purgeScheduledAt: null,
purgedAt: null,
legalHold: false,
legalHoldReason: null,
isActive: true,
createdAt: now,
updatedAt: now,
lastSignedIn: now,
};
}
function getBootstrapUserConfigs(): BootstrapUserConfig[] {
const users: BootstrapUserConfig[] = [];
if (ENV.bootstrapUsers) {
try {
const parsed = JSON.parse(ENV.bootstrapUsers) as BootstrapUserConfig[];
if (Array.isArray(parsed)) {
users.push(...parsed);
}
} catch (error) {
console.error("[Auth] BOOTSTRAP_USERS is not valid JSON", error);
}
}
if (ENV.bootstrapAdminEmail && ENV.bootstrapAdminPassword) {
users.push({
email: ENV.bootstrapAdminEmail,
password: ENV.bootstrapAdminPassword,
name: ENV.bootstrapAdminName,
role: "super_admin",
});
}
return users;
}
function getBootstrapUsers(): User[] {
return getBootstrapUserConfigs().map((config, index) =>
createBootstrapUser(config, index)
);
}
function findBootstrapUserByCredentials(input: { email: string; password: string }) {
const email = normalizeEmail(input.email);
const configs = getBootstrapUserConfigs();
const index = configs.findIndex(
config => normalizeEmail(config.email) === email && config.password === input.password
);
if (index === -1) return null;
return createBootstrapUser(configs[index], index);
}
function findBootstrapUserByOpenId(openId: string) {
return getBootstrapUsers().find(user => user.openId === openId) ?? null;
}
function getJwtSecret() {
const secret = ENV.cookieSecret;
if (!secret && ENV.isProduction) {
throw new Error("JWT_SECRET is required in production");
}
return new TextEncoder().encode(secret || "local-dev-secret-change-me");
}
function normalizeEmail(email: string) {
return email.trim().toLowerCase();
}
async function ensureConfiguredOwnerPrivileges(user: User): Promise<User> {
if (!user.email || !ENV.adminEmail) return user;
const isConfiguredOwner = normalizeEmail(user.email) === normalizeEmail(ENV.adminEmail);
if (!isConfiguredOwner) return user;
if (user.role === "super_admin" && user.canManageLogistics) {
return user;
}
await db.updateUser(user.id, {
role: "super_admin",
canManageLogistics: true,
});
return {
...user,
role: "super_admin",
canManageLogistics: true,
};
}
function parseCookies(cookieHeader: string | undefined) {
if (!cookieHeader) return new Map<string, string>();
return new Map(Object.entries(parseCookieHeader(cookieHeader)));
}
function hashOtpCode(code: string) {
return crypto.createHash("sha256").update(code).digest("hex");
}
function buildSecurityCipherKey() {
return crypto.createHash("sha256")
.update(ENV.cookieSecret || "local-dev-auth-security")
.digest();
}
function encryptSecuritySecret(value: string) {
const iv = crypto.randomBytes(12);
const key = buildSecurityCipherKey();
const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
const encrypted = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
const tag = cipher.getAuthTag();
return `${iv.toString("base64")}.${tag.toString("base64")}.${encrypted.toString("base64")}`;
}
function decryptSecuritySecret(value?: string | null) {
if (!value) return "";
const [ivBase64, tagBase64, encryptedBase64] = value.split(".");
if (!ivBase64 || !tagBase64 || !encryptedBase64) return "";
try {
const key = buildSecurityCipherKey();
const decipher = crypto.createDecipheriv("aes-256-gcm", key, Buffer.from(ivBase64, "base64"));
decipher.setAuthTag(Buffer.from(tagBase64, "base64"));
const decrypted = Buffer.concat([
decipher.update(Buffer.from(encryptedBase64, "base64")),
decipher.final(),
]);
return decrypted.toString("utf8");
} catch {
return "";
}
}
const BASE32_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
function encodeBase32(buffer: Buffer) {
let bits = 0;
let value = 0;
let output = "";
for (let index = 0; index < buffer.length; index += 1) {
const byte = buffer[index]!;
value = (value << 8) | byte;
bits += 8;
while (bits >= 5) {
output += BASE32_ALPHABET[(value >>> (bits - 5)) & 31];
bits -= 5;
}
}
if (bits > 0) {
output += BASE32_ALPHABET[(value << (5 - bits)) & 31];
}
return output;
}
function decodeBase32(input: string) {
const normalized = input.toUpperCase().replace(/=+$/g, "").replace(/[^A-Z2-7]/g, "");
let bits = 0;
let value = 0;
const output: number[] = [];
for (const char of normalized) {
const index = BASE32_ALPHABET.indexOf(char);
if (index === -1) continue;
value = (value << 5) | index;
bits += 5;
if (bits >= 8) {
output.push((value >>> (bits - 8)) & 255);
bits -= 8;
}
}
return Buffer.from(output);
}
function generateTotpSecret() {
return encodeBase32(crypto.randomBytes(20));
}
function buildOtpAuthUrl(email: string, secret: string) {
const label = encodeURIComponent(`Portail Associations:${email}`);
const issuer = encodeURIComponent("Portail Associations");
return `otpauth://totp/${label}?secret=${secret}&issuer=${issuer}&algorithm=SHA1&digits=6&period=30`;
}
function generateTotpCode(secret: string, timestamp: number) {
const key = decodeBase32(secret);
const counter = Math.floor(timestamp / 30_000);
const counterBuffer = Buffer.alloc(8);
counterBuffer.writeBigUInt64BE(BigInt(counter));
const hmac = crypto.createHmac("sha1", key).update(counterBuffer).digest();
const offset = hmac[hmac.length - 1] & 0x0f;
const binary = ((hmac[offset] & 0x7f) << 24)
| ((hmac[offset + 1] & 0xff) << 16)
| ((hmac[offset + 2] & 0xff) << 8)
| (hmac[offset + 3] & 0xff);
return String(binary % 1_000_000).padStart(6, "0");
}
function verifyTotpCode(secret: string, code: string) {
const trimmedCode = code.trim();
const now = Date.now();
for (const drift of [-30_000, 0, 30_000]) {
if (generateTotpCode(secret, now + drift) === trimmedCode) {
return true;
}
}
return false;
}
function maskEmail(email: string) {
const [localPart, domain = ""] = email.split("@");
if (!localPart) return email;
const visibleStart = localPart.slice(0, 2);
const visibleEnd = localPart.length > 4 ? localPart.slice(-1) : "";
const maskedCore = "*".repeat(Math.max(localPart.length - visibleStart.length - visibleEnd.length, 1));
return `${visibleStart}${maskedCore}${visibleEnd}@${domain}`;
}
function generateOtpCode() {
return String(Math.floor(100000 + Math.random() * 900000));
}
function getPasswordHashAlgorithm(passwordHash: string | null | undefined) {
if (!passwordHash) return null;
const [algorithm] = passwordHash.split(":");
return algorithm || null;
}
export function getInternalMfaPolicy(role: User["role"]) {
return INTERNAL_MFA_POLICY[role as keyof typeof INTERNAL_MFA_POLICY] ?? null;
}
export function isInternalRole(role: User["role"]) {
return Boolean(getInternalMfaPolicy(role));
}
function requiresMfaByRole(user: User) {
return Boolean(getInternalMfaPolicy(user.role)?.required);
}
function requiresTotpByRole(user: User) {
return getInternalMfaPolicy(user.role)?.enforcedMethod === "authenticator_app";
}
function allowsEmailMfaByRole(user: User) {
return getInternalMfaPolicy(user.role)?.emailFallbackAllowed !== false;
}
function getEffectiveMfaMethod(user: User): "email" | "totp" | null {
const hasTotp = Boolean(user.mfaMethod === "authenticator_app" && user.mfaTotpSecretEncrypted);
if (hasTotp) return "totp";
if ((user.mfaEnabled || requiresMfaByRole(user)) && user.email && allowsEmailMfaByRole(user)) return "email";
return null;
}
async function hashPassword(password: string) {
if (!argon2Async) {
const salt = crypto.randomBytes(16).toString("hex");
const derivedKey = (await scryptAsync(password, salt, KEY_LENGTH)) as Buffer;
return `scrypt:${salt}:${derivedKey.toString("hex")}`;
}
const nonce = crypto.randomBytes(16);
const derivedKey = (await argon2Async("argon2id", {
message: Buffer.from(password),
nonce,
parallelism: 1,
tagLength: 32,
memory: 65536,
passes: 3,
})) as Buffer;
return `argon2id:${nonce.toString("base64url")}:${derivedKey.toString("base64url")}`;
}
export async function hashLocalPassword(password: string) {
return hashPassword(password);
}
async function verifyPassword(password: string, passwordHash: string | null | undefined) {
if (!passwordHash) return false;
const [algorithm, salt, key] = passwordHash.split(":");
if (algorithm === "argon2id" && salt && key && argon2Async) {
const nonce = Buffer.from(salt, "base64url");
const expected = Buffer.from(key, "base64url");
const derivedKey = (await argon2Async("argon2id", {
message: Buffer.from(password),
nonce,
parallelism: 1,
tagLength: expected.length,
memory: 65536,
passes: 3,
})) as Buffer;
return derivedKey.length === expected.length && crypto.timingSafeEqual(derivedKey, expected);
}
if (algorithm !== "scrypt" || !salt || !key) return false;
const storedKey = Buffer.from(key, "hex");
const derivedKey = (await scryptAsync(password, salt, storedKey.length)) as Buffer;
if (storedKey.length !== derivedKey.length) return false;
return crypto.timingSafeEqual(storedKey, derivedKey);
}
async function resetLoginSecurityState(userId: number) {
await db.updateUser(userId, {
failedLoginAttempts: 0,
lockedUntil: null,
});
}
async function registerLoginFailure(user: User) {
const nextAttempts = (user.failedLoginAttempts || 0) + 1;
const lockNow = nextAttempts >= LOGIN_FAILURE_LIMIT;
await db.updateUser(user.id, {
failedLoginAttempts: lockNow ? 0 : nextAttempts,
lockedUntil: lockNow ? new Date(Date.now() + LOGIN_LOCK_DURATION_MS) : null,
});
}
function assertUserNotLocked(user: User) {
if (user.lockedUntil && new Date(user.lockedUntil) > new Date()) {
throw new AccountLockedError(new Date(user.lockedUntil));
}
}
async function sendLoginMfaChallenge(user: User) {
if (requiresTotpByRole(user) && !user.mfaTotpSecretEncrypted) {
throw new Error("Ce rôle interne doit utiliser l'application Authenticator. Faites initialiser le compte avant la prochaine connexion.");
}
const effectiveMethod = getEffectiveMfaMethod(user);
if (effectiveMethod === "totp") {
const challengeToken = crypto.randomBytes(24).toString("base64url");
const expiresAt = new Date(Date.now() + MFA_CODE_TTL_MS);
await db.updateUser(user.id, {
mfaChallengeToken: challengeToken,
mfaCodeHash: null,
mfaCodeExpiresAt: expiresAt,
mfaCodeAttempts: 0,
});
return new MfaChallengeRequiredError("totp", challengeToken, expiresAt);
}
if (!user.email) {
throw new Error("Ce compte ne dispose pas d'une adresse email exploitable pour le MFA.");
}
const mailReady = await canSendOperationalEmails();
if (!mailReady) {
throw new Error("Le MFA par email ne peut pas etre active tant que le SMTP n'est pas configure.");
}
const code = generateOtpCode();
const expiresAt = new Date(Date.now() + MFA_CODE_TTL_MS);
const challengeToken = crypto.randomBytes(24).toString("base64url");
await db.updateUser(user.id, {
mfaChallengeToken: challengeToken,
mfaCodeHash: hashOtpCode(code),
mfaCodeExpiresAt: expiresAt,
mfaCodeAttempts: 0,
});
await sendOperationalEmail({
to: [user.email],
subject: "Code de verification - Portail Associations",
text: `Votre code de verification est ${code}. Il expire dans 10 minutes.`,
html: `
<div style="font-family: Arial, sans-serif; line-height: 1.5; color: #161616;">
<h2>Code de verification</h2>
<p>Utilisez ce code pour finaliser votre connexion au Portail Associations :</p>
<p style="font-size: 28px; font-weight: 700; letter-spacing: 6px;">${code}</p>
<p>Ce code expire dans 10 minutes.</p>
</div>
`,
});
return new MfaChallengeRequiredError("email", challengeToken, expiresAt, maskEmail(user.email));
}
async function signSession(user: User) {
const expiresAt = Math.floor((Date.now() + ONE_YEAR_MS) / 1000);
return new SignJWT({
userId: user.id,
openId: user.openId,
} satisfies JwtPayload)
.setProtectedHeader({ alg: "HS256", typ: "JWT" })
.setSubject(String(user.id))
.setExpirationTime(expiresAt)
.sign(getJwtSecret());
}
async function verifySession(token: string | undefined | null) {
if (!token) return null;
try {
const { payload } = await jwtVerify(token, getJwtSecret(), {
algorithms: ["HS256"],
});
const userId = Number(payload.userId ?? payload.sub);
const openId = typeof payload.openId === "string" ? payload.openId : "";
if (!Number.isInteger(userId) || userId <= 0 || !openId) return null;
return { userId, openId };
} catch {
return null;
}
}
export function setSessionCookie(req: Request, res: Response, token: string) {
res.cookie(COOKIE_NAME, token, {
...getSessionCookieOptions(req),
maxAge: ONE_YEAR_MS,
});
}
export function clearSessionCookie(req: Request, res: Response) {
res.clearCookie(COOKIE_NAME, {
...getSessionCookieOptions(req),
maxAge: -1,
});
}
export async function registerLocalUser(input: {
name: string;
email: string;
password: string;
}) {
const email = normalizeEmail(input.email);
const existing = await db.getUserByEmail(email);
if (existing) {
throw new Error("Un compte existe deja avec cette adresse email");
}
const bootstrapUser = findBootstrapUserByCredentials(input);
if (bootstrapUser) {
return bootstrapUser;
}
const role =
ENV.adminEmail && normalizeEmail(ENV.adminEmail) === email ? "super_admin" : "user";
await db.upsertUser({
openId: email,
name: input.name.trim(),
email,
passwordHash: await hashPassword(input.password),
loginMethod: "local_jwt",
role,
lastSignedIn: new Date(),
});
const user = await db.getUserByEmail(email);
if (!user) throw new Error("Impossible de creer le compte utilisateur");
return user;
}
export async function loginLocalUser(input: { email: string; password: string }) {
const email = normalizeEmail(input.email);
const user = await db.getUserByEmail(email);
if (user) {
assertUserNotLocked(user);
if (!(await verifyPassword(input.password, user.passwordHash))) {
await registerLoginFailure(user);
throw ForbiddenError("Identifiants invalides");
}
await resetLoginSecurityState(user.id);
if (argon2Async && getPasswordHashAlgorithm(user.passwordHash) === "scrypt") {
await db.updateUser(user.id, {
passwordHash: await hashPassword(input.password),
});
}
const refreshedUser = (await db.getUserById(user.id)) ?? user;
if (getEffectiveMfaMethod(refreshedUser)) {
throw await sendLoginMfaChallenge(refreshedUser);
}
await db.upsertUser({
openId: user.openId,
lastSignedIn: new Date(),
});
return ensureConfiguredOwnerPrivileges((await db.getUserById(user.id)) ?? refreshedUser);
}
const bootstrapUser = findBootstrapUserByCredentials(input);
if (bootstrapUser) {
return bootstrapUser;
}
throw ForbiddenError("Identifiants invalides");
}
export async function verifyLocalUserMfa(input: { challengeToken: string; code: string }) {
const user = await db.getUserByMfaChallengeToken(input.challengeToken);
if (!user) {
throw ForbiddenError("Verification invalide ou expirée");
}
const effectiveMethod = getEffectiveMfaMethod(user);
if (!effectiveMethod) {
throw ForbiddenError("Verification invalide ou expirée");
}
if (user.mfaCodeExpiresAt && new Date(user.mfaCodeExpiresAt) < new Date()) {
await db.updateUser(user.id, {
mfaChallengeToken: null,
mfaCodeHash: null,
mfaCodeExpiresAt: null,
mfaCodeAttempts: 0,
});
throw ForbiddenError("Le code de verification a expiré");
}
if ((user.mfaCodeAttempts || 0) >= MFA_CODE_ATTEMPT_LIMIT) {
await db.updateUser(user.id, {
mfaChallengeToken: null,
mfaCodeHash: null,
mfaCodeExpiresAt: null,
mfaCodeAttempts: 0,
lockedUntil: new Date(Date.now() + LOGIN_LOCK_DURATION_MS),
});
throw new AccountLockedError(new Date(Date.now() + LOGIN_LOCK_DURATION_MS));
}
const isValidCode = effectiveMethod === "totp"
? verifyTotpCode(decryptSecuritySecret(user.mfaTotpSecretEncrypted), input.code)
: Boolean(user.mfaCodeHash) && hashOtpCode(input.code.trim()) === user.mfaCodeHash;
if (!isValidCode) {
await db.updateUser(user.id, {
mfaCodeAttempts: (user.mfaCodeAttempts || 0) + 1,
});
throw ForbiddenError("Code de verification incorrect");
}
await db.updateUser(user.id, {
mfaChallengeToken: null,
mfaCodeHash: null,
mfaCodeExpiresAt: null,
mfaCodeAttempts: 0,
lastSignedIn: new Date(),
});
return ensureConfiguredOwnerPrivileges((await db.getUserById(user.id)) ?? user);
}
export async function resendLocalUserMfaChallenge(challengeToken: string) {
const user = await db.getUserByMfaChallengeToken(challengeToken);
if (!user || getEffectiveMfaMethod(user) !== "email") {
throw ForbiddenError("Verification invalide ou expirée");
}
if (!user.email) {
throw ForbiddenError("Adresse email indisponible pour ce compte");
}
const code = generateOtpCode();
const expiresAt = new Date(Date.now() + MFA_CODE_TTL_MS);
await db.updateUser(user.id, {
mfaCodeHash: hashOtpCode(code),
mfaCodeExpiresAt: expiresAt,
mfaCodeAttempts: 0,
});
await sendOperationalEmail({
to: [user.email],
subject: "Nouveau code de verification - Portail Associations",
text: `Votre nouveau code de verification est ${code}. Il expire dans 10 minutes.`,
html: `
<div style="font-family: Arial, sans-serif; line-height: 1.5; color: #161616;">
<h2>Nouveau code de verification</h2>
<p>Utilisez ce code pour finaliser votre connexion au Portail Associations :</p>
<p style="font-size: 28px; font-weight: 700; letter-spacing: 6px;">${code}</p>
<p>Ce code expire dans 10 minutes.</p>
</div>
`,
});
return {
challengeToken,
expiresAt,
maskedEmail: maskEmail(user.email),
};
}
export async function startAuthenticatorSetup(user: User) {
if (user.loginMethod !== "local_jwt" || !user.email) {
throw new Error("Authenticator est disponible uniquement pour les comptes locaux avec email.");
}
const secret = generateTotpSecret();
await db.updateUser(user.id, {
mfaTotpPendingSecretEncrypted: encryptSecuritySecret(secret),
});
return {
manualEntryKey: secret,
otpauthUrl: buildOtpAuthUrl(user.email, secret),
};
}
export async function confirmAuthenticatorSetup(user: User, code: string) {
const freshUser = await db.getUserById(user.id);
if (!freshUser) {
throw new Error("Compte introuvable");
}
const pendingSecret = decryptSecuritySecret(freshUser.mfaTotpPendingSecretEncrypted);
if (!pendingSecret) {
throw new Error("Aucune configuration Authenticator en attente.");
}
if (!verifyTotpCode(pendingSecret, code)) {
throw new Error("Code Authenticator invalide.");
}
await db.updateUser(user.id, {
mfaEnabled: true,
mfaMethod: "authenticator_app",
mfaTotpSecretEncrypted: encryptSecuritySecret(pendingSecret),
mfaTotpPendingSecretEncrypted: null,
});
}
export async function cancelAuthenticatorSetup(user: User) {
await db.updateUser(user.id, {
mfaTotpPendingSecretEncrypted: null,
});
}
export async function scheduleAccountDeletion(user: User) {
if (user.legalHold) {
throw new Error("Ce compte est actuellement place en conservation legale et ne peut pas etre supprime.");
}
const now = new Date();
const purgeAt = new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000);
await db.updateUser(user.id, {
deletionRequestedAt: now,
purgeScheduledAt: purgeAt,
isActive: false,
});
return { deletionRequestedAt: now, purgeScheduledAt: purgeAt };
}
export async function cancelScheduledAccountDeletion(user: User) {
await db.updateUser(user.id, {
deletionRequestedAt: null,
purgeScheduledAt: null,
isActive: true,
});
}
export async function runUserPurgeScheduler() {
const startedAt = new Date();
const dueUsers = await db.getUsersScheduledForPurge();
let purgedUsers = 0;
for (const user of dueUsers) {
const association = await db.getAssociationByUserId(user.id);
if (association) {
await db.updateAssociation(association.id, {
sourceDirectoryEntryId: null,
nomAssociation: `Association supprimée #${association.id}`,
siret: null,
rna: null,
thematique: null,
adresse: null,
codePostal: null,
ville: null,
telephone: null,
emailContact: null,
siteWeb: null,
facebookUrl: null,
instagramUrl: null,
objetAssociation: null,
nomRepresentant: null,
fonctionRepresentant: null,
gouvernance: null,
profileComplete: false,
isActive: false,
});
}
await db.updateUser(user.id, {
openId: `purged:${user.id}:${Date.now()}`,
name: `Compte supprimé #${user.id}`,
email: null,
passwordHash: null,
isActive: false,
mfaEnabled: false,
mfaMethod: null,
mfaChallengeToken: null,
mfaCodeHash: null,
mfaCodeExpiresAt: null,
mfaCodeAttempts: 0,
mfaTotpSecretEncrypted: null,
mfaTotpPendingSecretEncrypted: null,
purgedAt: new Date(),
legalHold: false,
legalHoldReason: null,
});
await db.createAuditLog({
userId: SYSTEM_ACTOR_USER_ID,
action: "data_purge",
entityType: "user",
entityId: user.id,
details: JSON.stringify({
event: "DATA_PURGE",
executedAt: new Date().toISOString(),
status: "SUCCESS",
purgeScheduledAt: user.purgeScheduledAt,
}),
ipAddress: "system",
});
purgedUsers += 1;
}
const allUsers = await db.getAllUsers();
const pendingDeletionCount = allUsers.filter((item) => item.deletionRequestedAt && !item.purgedAt).length;
const purgedTotalCount = allUsers.filter((item) => item.purgedAt).length;
await db.setPortalSetting(
RETENTION_REPORT_SETTING_KEY,
JSON.stringify({
generatedAt: new Date().toISOString(),
startedAt: startedAt.toISOString(),
reportType: "daily-retention-job",
purgedUsers,
pendingDeletionCount,
purgedTotalCount,
}),
"Dernier rapport automatique de retention et purge"
);
return {
generatedAt: new Date().toISOString(),
purgedUsers,
pendingDeletionCount,
purgedTotalCount,
};
}
export function isAccountLockedError(error: unknown): error is AccountLockedError {
return error instanceof AccountLockedError;
}
export function isMfaCodeRequiredError(error: unknown): error is MfaChallengeRequiredError {
return error instanceof MfaChallengeRequiredError;
}
export async function loginOAuthUser(input: {
provider: "google" | "facebook";
providerUserId: string;
email: string;
name?: string | null;
}) {
const email = normalizeEmail(input.email);
const existingByEmail = await db.getUserByEmail(email);
const openId = existingByEmail?.openId || email || `${input.provider}:${input.providerUserId}`;
const role = existingByEmail?.role
?? (ENV.adminEmail && normalizeEmail(ENV.adminEmail) === email ? "super_admin" : "user");
await db.upsertUser({
openId,
name: input.name?.trim() || existingByEmail?.name || email.split("@")[0] || "Utilisateur",
email,
loginMethod: `${input.provider}_oauth`,
role,
lastSignedIn: new Date(),
});
if (existingByEmail) {
return ensureConfiguredOwnerPrivileges((await db.getUserById(existingByEmail.id)) ?? existingByEmail);
}
const user = await db.getUserByOpenId(openId);
if (!user) {
throw new Error("Impossible de finaliser la connexion sociale");
}
return ensureConfiguredOwnerPrivileges(user);
}
export async function createSessionToken(user: User) {
return signSession(user);
}
export async function authenticateRequest(req: Request): Promise<User> {
const cookies = parseCookies(req.headers.cookie);
const session = await verifySession(cookies.get(COOKIE_NAME));
if (!session) {
throw ForbiddenError("Invalid session cookie");
}
const user = await db.getUserById(session.userId);
const userByOpenId = user ? null : await db.getUserByOpenId(session.openId);
const bootstrapUser = findBootstrapUserByOpenId(session.openId);
if (!user && userByOpenId && userByOpenId.isActive) {
return ensureConfiguredOwnerPrivileges(userByOpenId);
}
if (!user && bootstrapUser) {
return bootstrapUser;
}
if (!user || user.openId !== session.openId || !user.isActive) {
throw ForbiddenError("User not found");
}
return ensureConfiguredOwnerPrivileges(user);
}

28
server/_core/context.ts Normal file
View file

@ -0,0 +1,28 @@
import type { CreateExpressContextOptions } from "@trpc/server/adapters/express";
import { authenticateRequest } from "./auth";
import { withEffectiveInternalAccess, type AuthenticatedPortalUser } from "../internalAccess";
export type TrpcContext = {
req: CreateExpressContextOptions["req"];
res: CreateExpressContextOptions["res"];
user: AuthenticatedPortalUser | null;
};
export async function createContext(
opts: CreateExpressContextOptions
): Promise<TrpcContext> {
let user: AuthenticatedPortalUser | null = null;
try {
user = await withEffectiveInternalAccess(await authenticateRequest(opts.req));
} catch (error) {
// Authentication is optional for public procedures.
user = null;
}
return {
req: opts.req,
res: opts.res,
user,
};
}

50
server/_core/cookies.ts Normal file
View file

@ -0,0 +1,50 @@
import type { CookieOptions, Request } from "express";
const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "::1"]);
function isIpAddress(host: string) {
// Basic IPv4 check and IPv6 presence detection.
if (/^\d{1,3}(\.\d{1,3}){3}$/.test(host)) return true;
return host.includes(":");
}
function isSecureRequest(req: Request) {
if (req.protocol === "https") return true;
const forwardedProto = req.headers["x-forwarded-proto"];
if (!forwardedProto) return false;
const protoList = Array.isArray(forwardedProto)
? forwardedProto
: forwardedProto.split(",");
return protoList.some(proto => proto.trim().toLowerCase() === "https");
}
export function getSessionCookieOptions(
req: Request
): Pick<CookieOptions, "domain" | "httpOnly" | "path" | "sameSite" | "secure"> {
// const hostname = req.hostname;
// const shouldSetDomain =
// hostname &&
// !LOCAL_HOSTS.has(hostname) &&
// !isIpAddress(hostname) &&
// hostname !== "127.0.0.1" &&
// hostname !== "::1";
// const domain =
// shouldSetDomain && !hostname.startsWith(".")
// ? `.${hostname}`
// : shouldSetDomain
// ? hostname
// : undefined;
const secure = isSecureRequest(req);
return {
httpOnly: true,
path: "/",
sameSite: secure ? "none" : "lax",
secure,
};
}

64
server/_core/dataApi.ts Normal file
View file

@ -0,0 +1,64 @@
/**
* Quick example (matches curl usage):
* await callDataApi("Youtube/search", {
* query: { gl: "US", hl: "en", q: "manus" },
* })
*/
import { ENV } from "./env";
export type DataApiCallOptions = {
query?: Record<string, unknown>;
body?: Record<string, unknown>;
pathParams?: Record<string, unknown>;
formData?: Record<string, unknown>;
};
export async function callDataApi(
apiId: string,
options: DataApiCallOptions = {}
): Promise<unknown> {
if (!ENV.forgeApiUrl) {
throw new Error("BUILT_IN_FORGE_API_URL is not configured");
}
if (!ENV.forgeApiKey) {
throw new Error("BUILT_IN_FORGE_API_KEY is not configured");
}
// Build the full URL by appending the service path to the base URL
const baseUrl = ENV.forgeApiUrl.endsWith("/") ? ENV.forgeApiUrl : `${ENV.forgeApiUrl}/`;
const fullUrl = new URL("webdevtoken.v1.WebDevService/CallApi", baseUrl).toString();
const response = await fetch(fullUrl, {
method: "POST",
headers: {
accept: "application/json",
"content-type": "application/json",
"connect-protocol-version": "1",
authorization: `Bearer ${ENV.forgeApiKey}`,
},
body: JSON.stringify({
apiId,
query: options.query,
body: options.body,
path_params: options.pathParams,
multipart_form_data: options.formData,
}),
});
if (!response.ok) {
const detail = await response.text().catch(() => "");
throw new Error(
`Data API request failed (${response.status} ${response.statusText})${detail ? `: ${detail}` : ""}`
);
}
const payload = await response.json().catch(() => ({}));
if (payload && typeof payload === "object" && "jsonData" in payload) {
try {
return JSON.parse((payload as Record<string, string>).jsonData ?? "{}");
} catch {
return (payload as Record<string, unknown>).jsonData;
}
}
return payload;
}

30
server/_core/env.ts Normal file
View file

@ -0,0 +1,30 @@
export const ENV = {
cookieSecret: process.env.JWT_SECRET ?? "",
databaseUrl: process.env.DATABASE_URL ?? "",
ownerOpenId: process.env.OWNER_OPEN_ID ?? "",
adminEmail: process.env.ADMIN_EMAIL ?? "",
bootstrapAdminEmail: process.env.BOOTSTRAP_ADMIN_EMAIL ?? "",
bootstrapAdminPassword: process.env.BOOTSTRAP_ADMIN_PASSWORD ?? "",
bootstrapAdminName: process.env.BOOTSTRAP_ADMIN_NAME ?? "Administrateur",
bootstrapUsers: process.env.BOOTSTRAP_USERS ?? "",
isProduction: process.env.NODE_ENV === "production",
forgeApiUrl: process.env.BUILT_IN_FORGE_API_URL ?? "",
forgeApiKey: process.env.BUILT_IN_FORGE_API_KEY ?? "",
smtpProvider: process.env.SMTP_PROVIDER ?? "",
smtpHost: process.env.SMTP_HOST ?? "",
smtpPort: process.env.SMTP_PORT ?? "",
smtpUser: process.env.SMTP_USER ?? "",
smtpPass: process.env.SMTP_PASS ?? "",
smtpFrom: process.env.SMTP_FROM ?? "",
smtpSecure: process.env.SMTP_SECURE ?? "",
smtpRequireTls: process.env.SMTP_REQUIRE_TLS ?? "",
appBaseUrl: process.env.APP_BASE_URL ?? "",
entrepriseApiToken: process.env.ENTREPRISE_API_TOKEN ?? "",
googleClientId: process.env.GOOGLE_CLIENT_ID ?? "",
googleClientSecret: process.env.GOOGLE_CLIENT_SECRET ?? "",
facebookAppId: process.env.FACEBOOK_APP_ID ?? "",
facebookAppSecret: process.env.FACEBOOK_APP_SECRET ?? "",
appReadyDelayMs: Number.parseInt(process.env.APP_READY_DELAY_MS ?? "8000", 10) || 8000,
maintenanceFlagPath: process.env.MAINTENANCE_FLAG_PATH ?? "",
gracefulShutdownTimeoutMs: Number.parseInt(process.env.GRACEFUL_SHUTDOWN_TIMEOUT_MS ?? "20000", 10) || 20000,
};

View file

@ -0,0 +1,92 @@
/**
* Image generation helper using internal ImageService
*
* Example usage:
* const { url: imageUrl } = await generateImage({
* prompt: "A serene landscape with mountains"
* });
*
* For editing:
* const { url: imageUrl } = await generateImage({
* prompt: "Add a rainbow to this landscape",
* originalImages: [{
* url: "https://example.com/original.jpg",
* mimeType: "image/jpeg"
* }]
* });
*/
import { storagePut } from "server/storage";
import { ENV } from "./env";
export type GenerateImageOptions = {
prompt: string;
originalImages?: Array<{
url?: string;
b64Json?: string;
mimeType?: string;
}>;
};
export type GenerateImageResponse = {
url?: string;
};
export async function generateImage(
options: GenerateImageOptions
): Promise<GenerateImageResponse> {
if (!ENV.forgeApiUrl) {
throw new Error("BUILT_IN_FORGE_API_URL is not configured");
}
if (!ENV.forgeApiKey) {
throw new Error("BUILT_IN_FORGE_API_KEY is not configured");
}
// Build the full URL by appending the service path to the base URL
const baseUrl = ENV.forgeApiUrl.endsWith("/")
? ENV.forgeApiUrl
: `${ENV.forgeApiUrl}/`;
const fullUrl = new URL(
"images.v1.ImageService/GenerateImage",
baseUrl
).toString();
const response = await fetch(fullUrl, {
method: "POST",
headers: {
accept: "application/json",
"content-type": "application/json",
"connect-protocol-version": "1",
authorization: `Bearer ${ENV.forgeApiKey}`,
},
body: JSON.stringify({
prompt: options.prompt,
original_images: options.originalImages || [],
}),
});
if (!response.ok) {
const detail = await response.text().catch(() => "");
throw new Error(
`Image generation request failed (${response.status} ${response.statusText})${detail ? `: ${detail}` : ""}`
);
}
const result = (await response.json()) as {
image: {
b64Json: string;
mimeType: string;
};
};
const base64Data = result.image.b64Json;
const buffer = Buffer.from(base64Data, "base64");
// Save to S3
const { url } = await storagePut(
`generated/${Date.now()}.png`,
buffer,
result.image.mimeType
);
return {
url,
};
}

217
server/_core/index.ts Normal file
View file

@ -0,0 +1,217 @@
import "dotenv/config";
import express from "express";
import { createServer } from "http";
import net from "net";
import path from "node:path";
import { createExpressMiddleware } from "@trpc/server/adapters/express";
import { appRouter, computeReservationAnalytics, runStatsReportScheduler } from "../routers";
import { createContext } from "./context";
import { serveStatic, setupVite } from "./vite";
import { registerEmailActionRoutes } from "../emailActions";
import { registerSocialAuthRoutes } from "../socialAuth";
import { ENV } from "./env";
import { runMaterialReturnScheduler } from "../materialReturnWorkflow";
import { authenticateRequest, runUserPurgeScheduler } from "./auth";
import { withEffectiveInternalAccess } from "../internalAccess";
import { buildRuntimeHealth, ensureMaintenanceFlagDirectory, isMaintenanceModeEnabled, markRuntimeReady, markRuntimeShuttingDown } from "./runtime";
function isPortAvailable(port: number): Promise<boolean> {
return new Promise(resolve => {
const server = net.createServer();
server.listen(port, () => {
server.close(() => resolve(true));
});
server.on("error", () => resolve(false));
});
}
async function findAvailablePort(startPort: number = 3000): Promise<number> {
for (let port = startPort; port < startPort + 20; port++) {
if (await isPortAvailable(port)) {
return port;
}
}
throw new Error(`No available port found starting from ${startPort}`);
}
async function startServer() {
const app = express();
const server = createServer(app);
const schedulerTimers: NodeJS.Timeout[] = [];
const openSockets = new Set<net.Socket>();
let shutdownInFlight = false;
await ensureMaintenanceFlagDirectory();
server.on("connection", (socket) => {
openSockets.add(socket);
socket.on("close", () => {
openSockets.delete(socket);
});
});
async function sendHealth(res: express.Response, mode: "live" | "ready") {
const health = await buildRuntimeHealth();
const status = mode === "live"
? (health.checks.shuttingDown ? 503 : 200)
: (health.ok ? 200 : 503);
res.status(status).json(health);
}
function renderMaintenancePage() {
return `<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Maintenance en cours</title>
<style>
body{margin:0;font-family:Arial,sans-serif;background:#f6f9fc;color:#162133;display:grid;place-items:center;min-height:100vh;padding:24px}
.panel{max-width:560px;background:#fff;border:1px solid #d5e2f3;border-radius:20px;padding:32px;box-shadow:0 12px 30px rgba(15,23,42,.08)}
h1{margin:0 0 12px;font-size:32px;line-height:1.1}
p{margin:0 0 10px;font-size:16px;line-height:1.6;color:#52627a}
.badge{display:inline-flex;padding:6px 12px;border-radius:999px;background:#e8f2ff;color:#2c63c9;font-size:12px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;margin-bottom:18px}
</style>
</head>
<body>
<main class="panel">
<div class="badge">Maintenance</div>
<h1>Le portail revient dans un instant</h1>
<p>Nous appliquons une mise à jour de service pour garder une expérience stable, propre et fiable.</p>
<p>Tu peux recharger la page dans quelques instants.</p>
</main>
</body>
</html>`;
}
async function gracefulShutdown(signal: string) {
if (shutdownInFlight) return;
shutdownInFlight = true;
console.log(`[Runtime] graceful shutdown triggered by ${signal}`);
markRuntimeShuttingDown();
schedulerTimers.forEach(clearTimeout);
schedulerTimers.splice(0, schedulerTimers.length);
const forceCloseTimer = setTimeout(() => {
for (const socket of Array.from(openSockets)) {
socket.destroy();
}
}, ENV.gracefulShutdownTimeoutMs);
await new Promise<void>((resolve) => {
server.close(() => resolve());
});
clearTimeout(forceCloseTimer);
process.exit(0);
}
process.on("SIGTERM", () => {
void gracefulShutdown("SIGTERM");
});
process.on("SIGINT", () => {
void gracefulShutdown("SIGINT");
});
// Configure body parser with larger size limit for file uploads
app.use(express.json({ limit: "50mb" }));
app.use(express.urlencoded({ limit: "50mb", extended: true }));
app.use("/uploads", express.static(path.resolve(process.cwd(), "uploads")));
app.get("/health/live", async (_req, res) => {
await sendHealth(res, "live");
});
app.get("/health/ready", async (_req, res) => {
await sendHealth(res, "ready");
});
app.get("/health", async (_req, res) => {
await sendHealth(res, "ready");
});
// Email action routes for validate/refuse from email
registerEmailActionRoutes(app);
registerSocialAuthRoutes(app);
app.get("/api/internal/stats/reservations", async (req, res) => {
try {
let authenticatedUser;
try {
authenticatedUser = await withEffectiveInternalAccess(await authenticateRequest(req));
} catch {
return res.status(401).json({ error: "Authentification requise" });
}
if (!authenticatedUser) {
return res.status(401).json({ error: "Authentification requise" });
}
const allowedRoles = new Set(["accueil", "admin", "super_admin"]);
if (!allowedRoles.has(authenticatedUser.role)) {
return res.status(403).json({ error: "Accès réservé à laccueil et aux administrateurs" });
}
const rawPeriod = typeof req.query.period === "string" ? req.query.period : "month";
const period = ["7d", "month", "quarter", "semester", "year"].includes(rawPeriod) ? rawPeriod as "7d" | "month" | "quarter" | "semester" | "year" : "month";
const payload = await computeReservationAnalytics(period);
return res.json(payload);
} catch {
return res.status(500).json({ error: "Impossible de récupérer les statistiques" });
}
});
// tRPC API
app.use(
"/api/trpc",
createExpressMiddleware({
router: appRouter,
createContext,
})
);
app.use(async (req, res, next) => {
if (!["GET", "HEAD"].includes(req.method)) {
next();
return;
}
if (req.path.startsWith("/api") || req.path.startsWith("/health") || req.path.startsWith("/uploads")) {
next();
return;
}
if (!(await isMaintenanceModeEnabled())) {
next();
return;
}
res.status(503).type("html").send(renderMaintenancePage());
});
// development mode uses Vite, production mode uses static files
if (process.env.NODE_ENV === "development") {
await setupVite(app, server);
} else {
serveStatic(app);
}
const preferredPort = parseInt(process.env.PORT || "3000");
const port = await findAvailablePort(preferredPort);
if (port !== preferredPort) {
console.log(`Port ${preferredPort} is busy, using port ${port} instead`);
}
server.listen(port, () => {
console.log(`Server running on http://localhost:${port}/`);
const baseUrl = (ENV.appBaseUrl || `http://localhost:${port}`).replace(/\/$/, "");
const runScheduler = () => {
runMaterialReturnScheduler(baseUrl).catch((error) => {
console.error("[MaterialReturnScheduler] execution error:", error);
});
runStatsReportScheduler(baseUrl).catch((error) => {
console.error("[StatsReportScheduler] execution error:", error);
});
runUserPurgeScheduler().catch((error) => {
console.error("[UserPurgeScheduler] execution error:", error);
});
};
markRuntimeReady();
schedulerTimers.push(setTimeout(runScheduler, 5_000));
schedulerTimers.push(setInterval(runScheduler, 60 * 60 * 1000));
});
}
startServer().catch(console.error);

332
server/_core/llm.ts Normal file
View file

@ -0,0 +1,332 @@
import { ENV } from "./env";
export type Role = "system" | "user" | "assistant" | "tool" | "function";
export type TextContent = {
type: "text";
text: string;
};
export type ImageContent = {
type: "image_url";
image_url: {
url: string;
detail?: "auto" | "low" | "high";
};
};
export type FileContent = {
type: "file_url";
file_url: {
url: string;
mime_type?: "audio/mpeg" | "audio/wav" | "application/pdf" | "audio/mp4" | "video/mp4" ;
};
};
export type MessageContent = string | TextContent | ImageContent | FileContent;
export type Message = {
role: Role;
content: MessageContent | MessageContent[];
name?: string;
tool_call_id?: string;
};
export type Tool = {
type: "function";
function: {
name: string;
description?: string;
parameters?: Record<string, unknown>;
};
};
export type ToolChoicePrimitive = "none" | "auto" | "required";
export type ToolChoiceByName = { name: string };
export type ToolChoiceExplicit = {
type: "function";
function: {
name: string;
};
};
export type ToolChoice =
| ToolChoicePrimitive
| ToolChoiceByName
| ToolChoiceExplicit;
export type InvokeParams = {
messages: Message[];
tools?: Tool[];
toolChoice?: ToolChoice;
tool_choice?: ToolChoice;
maxTokens?: number;
max_tokens?: number;
outputSchema?: OutputSchema;
output_schema?: OutputSchema;
responseFormat?: ResponseFormat;
response_format?: ResponseFormat;
};
export type ToolCall = {
id: string;
type: "function";
function: {
name: string;
arguments: string;
};
};
export type InvokeResult = {
id: string;
created: number;
model: string;
choices: Array<{
index: number;
message: {
role: Role;
content: string | Array<TextContent | ImageContent | FileContent>;
tool_calls?: ToolCall[];
};
finish_reason: string | null;
}>;
usage?: {
prompt_tokens: number;
completion_tokens: number;
total_tokens: number;
};
};
export type JsonSchema = {
name: string;
schema: Record<string, unknown>;
strict?: boolean;
};
export type OutputSchema = JsonSchema;
export type ResponseFormat =
| { type: "text" }
| { type: "json_object" }
| { type: "json_schema"; json_schema: JsonSchema };
const ensureArray = (
value: MessageContent | MessageContent[]
): MessageContent[] => (Array.isArray(value) ? value : [value]);
const normalizeContentPart = (
part: MessageContent
): TextContent | ImageContent | FileContent => {
if (typeof part === "string") {
return { type: "text", text: part };
}
if (part.type === "text") {
return part;
}
if (part.type === "image_url") {
return part;
}
if (part.type === "file_url") {
return part;
}
throw new Error("Unsupported message content part");
};
const normalizeMessage = (message: Message) => {
const { role, name, tool_call_id } = message;
if (role === "tool" || role === "function") {
const content = ensureArray(message.content)
.map(part => (typeof part === "string" ? part : JSON.stringify(part)))
.join("\n");
return {
role,
name,
tool_call_id,
content,
};
}
const contentParts = ensureArray(message.content).map(normalizeContentPart);
// If there's only text content, collapse to a single string for compatibility
if (contentParts.length === 1 && contentParts[0].type === "text") {
return {
role,
name,
content: contentParts[0].text,
};
}
return {
role,
name,
content: contentParts,
};
};
const normalizeToolChoice = (
toolChoice: ToolChoice | undefined,
tools: Tool[] | undefined
): "none" | "auto" | ToolChoiceExplicit | undefined => {
if (!toolChoice) return undefined;
if (toolChoice === "none" || toolChoice === "auto") {
return toolChoice;
}
if (toolChoice === "required") {
if (!tools || tools.length === 0) {
throw new Error(
"tool_choice 'required' was provided but no tools were configured"
);
}
if (tools.length > 1) {
throw new Error(
"tool_choice 'required' needs a single tool or specify the tool name explicitly"
);
}
return {
type: "function",
function: { name: tools[0].function.name },
};
}
if ("name" in toolChoice) {
return {
type: "function",
function: { name: toolChoice.name },
};
}
return toolChoice;
};
const resolveApiUrl = () =>
ENV.forgeApiUrl && ENV.forgeApiUrl.trim().length > 0
? `${ENV.forgeApiUrl.replace(/\/$/, "")}/v1/chat/completions`
: "https://forge.manus.im/v1/chat/completions";
const assertApiKey = () => {
if (!ENV.forgeApiKey) {
throw new Error("OPENAI_API_KEY is not configured");
}
};
const normalizeResponseFormat = ({
responseFormat,
response_format,
outputSchema,
output_schema,
}: {
responseFormat?: ResponseFormat;
response_format?: ResponseFormat;
outputSchema?: OutputSchema;
output_schema?: OutputSchema;
}):
| { type: "json_schema"; json_schema: JsonSchema }
| { type: "text" }
| { type: "json_object" }
| undefined => {
const explicitFormat = responseFormat || response_format;
if (explicitFormat) {
if (
explicitFormat.type === "json_schema" &&
!explicitFormat.json_schema?.schema
) {
throw new Error(
"responseFormat json_schema requires a defined schema object"
);
}
return explicitFormat;
}
const schema = outputSchema || output_schema;
if (!schema) return undefined;
if (!schema.name || !schema.schema) {
throw new Error("outputSchema requires both name and schema");
}
return {
type: "json_schema",
json_schema: {
name: schema.name,
schema: schema.schema,
...(typeof schema.strict === "boolean" ? { strict: schema.strict } : {}),
},
};
};
export async function invokeLLM(params: InvokeParams): Promise<InvokeResult> {
assertApiKey();
const {
messages,
tools,
toolChoice,
tool_choice,
outputSchema,
output_schema,
responseFormat,
response_format,
} = params;
const payload: Record<string, unknown> = {
model: "gemini-2.5-flash",
messages: messages.map(normalizeMessage),
};
if (tools && tools.length > 0) {
payload.tools = tools;
}
const normalizedToolChoice = normalizeToolChoice(
toolChoice || tool_choice,
tools
);
if (normalizedToolChoice) {
payload.tool_choice = normalizedToolChoice;
}
payload.max_tokens = 32768
payload.thinking = {
"budget_tokens": 128
}
const normalizedResponseFormat = normalizeResponseFormat({
responseFormat,
response_format,
outputSchema,
output_schema,
});
if (normalizedResponseFormat) {
payload.response_format = normalizedResponseFormat;
}
const response = await fetch(resolveApiUrl(), {
method: "POST",
headers: {
"content-type": "application/json",
authorization: `Bearer ${ENV.forgeApiKey}`,
},
body: JSON.stringify(payload),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(
`LLM invoke failed: ${response.status} ${response.statusText} ${errorText}`
);
}
return (await response.json()) as InvokeResult;
}

319
server/_core/map.ts Normal file
View file

@ -0,0 +1,319 @@
/**
* Google Maps API Integration for Manus WebDev Templates
*
* Main function: makeRequest<T>(endpoint, params) - Makes authenticated requests to Google Maps APIs
* All credentials are automatically injected. Array parameters use | as separator.
*
* See API examples below the type definitions for usage patterns.
*/
import { ENV } from "./env";
// ============================================================================
// Configuration
// ============================================================================
type MapsConfig = {
baseUrl: string;
apiKey: string;
};
function getMapsConfig(): MapsConfig {
const baseUrl = ENV.forgeApiUrl;
const apiKey = ENV.forgeApiKey;
if (!baseUrl || !apiKey) {
throw new Error(
"Google Maps proxy credentials missing: set BUILT_IN_FORGE_API_URL and BUILT_IN_FORGE_API_KEY"
);
}
return {
baseUrl: baseUrl.replace(/\/+$/, ""),
apiKey,
};
}
// ============================================================================
// Core Request Handler
// ============================================================================
interface RequestOptions {
method?: "GET" | "POST";
body?: Record<string, unknown>;
}
/**
* Make authenticated requests to Google Maps APIs
*
* @param endpoint - The API endpoint (e.g., "/maps/api/geocode/json")
* @param params - Query parameters for the request
* @param options - Additional request options
* @returns The API response
*/
export async function makeRequest<T = unknown>(
endpoint: string,
params: Record<string, unknown> = {},
options: RequestOptions = {}
): Promise<T> {
const { baseUrl, apiKey } = getMapsConfig();
// Construct full URL: baseUrl + /v1/maps/proxy + endpoint
const url = new URL(`${baseUrl}/v1/maps/proxy${endpoint}`);
// Add API key as query parameter (standard Google Maps API authentication)
url.searchParams.append("key", apiKey);
// Add other query parameters
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined && value !== null) {
url.searchParams.append(key, String(value));
}
});
const response = await fetch(url.toString(), {
method: options.method || "GET",
headers: {
"Content-Type": "application/json",
},
body: options.body ? JSON.stringify(options.body) : undefined,
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(
`Google Maps API request failed (${response.status} ${response.statusText}): ${errorText}`
);
}
return (await response.json()) as T;
}
// ============================================================================
// Type Definitions
// ============================================================================
export type TravelMode = "driving" | "walking" | "bicycling" | "transit";
export type MapType = "roadmap" | "satellite" | "terrain" | "hybrid";
export type SpeedUnit = "KPH" | "MPH";
export type LatLng = {
lat: number;
lng: number;
};
export type DirectionsResult = {
routes: Array<{
legs: Array<{
distance: { text: string; value: number };
duration: { text: string; value: number };
start_address: string;
end_address: string;
start_location: LatLng;
end_location: LatLng;
steps: Array<{
distance: { text: string; value: number };
duration: { text: string; value: number };
html_instructions: string;
travel_mode: string;
start_location: LatLng;
end_location: LatLng;
}>;
}>;
overview_polyline: { points: string };
summary: string;
warnings: string[];
waypoint_order: number[];
}>;
status: string;
};
export type DistanceMatrixResult = {
rows: Array<{
elements: Array<{
distance: { text: string; value: number };
duration: { text: string; value: number };
status: string;
}>;
}>;
origin_addresses: string[];
destination_addresses: string[];
status: string;
};
export type GeocodingResult = {
results: Array<{
address_components: Array<{
long_name: string;
short_name: string;
types: string[];
}>;
formatted_address: string;
geometry: {
location: LatLng;
location_type: string;
viewport: {
northeast: LatLng;
southwest: LatLng;
};
};
place_id: string;
types: string[];
}>;
status: string;
};
export type PlacesSearchResult = {
results: Array<{
place_id: string;
name: string;
formatted_address: string;
geometry: {
location: LatLng;
};
rating?: number;
user_ratings_total?: number;
business_status?: string;
types: string[];
}>;
status: string;
};
export type PlaceDetailsResult = {
result: {
place_id: string;
name: string;
formatted_address: string;
formatted_phone_number?: string;
international_phone_number?: string;
website?: string;
rating?: number;
user_ratings_total?: number;
reviews?: Array<{
author_name: string;
rating: number;
text: string;
time: number;
}>;
opening_hours?: {
open_now: boolean;
weekday_text: string[];
};
geometry: {
location: LatLng;
};
};
status: string;
};
export type ElevationResult = {
results: Array<{
elevation: number;
location: LatLng;
resolution: number;
}>;
status: string;
};
export type TimeZoneResult = {
dstOffset: number;
rawOffset: number;
status: string;
timeZoneId: string;
timeZoneName: string;
};
export type RoadsResult = {
snappedPoints: Array<{
location: LatLng;
originalIndex?: number;
placeId: string;
}>;
};
// ============================================================================
// Google Maps API Reference
// ============================================================================
/**
* GEOCODING - Convert between addresses and coordinates
* Endpoint: /maps/api/geocode/json
* Input: { address: string } OR { latlng: string } // latlng: "37.42,-122.08"
* Output: GeocodingResult // results[0].geometry.location, results[0].formatted_address
*/
/**
* DIRECTIONS - Get navigation routes between locations
* Endpoint: /maps/api/directions/json
* Input: { origin: string, destination: string, mode?: TravelMode, waypoints?: string, alternatives?: boolean }
* Output: DirectionsResult // routes[0].legs[0].distance, duration, steps
*/
/**
* DISTANCE MATRIX - Calculate travel times/distances for multiple origin-destination pairs
* Endpoint: /maps/api/distancematrix/json
* Input: { origins: string, destinations: string, mode?: TravelMode, units?: "metric"|"imperial" } // origins: "NYC|Boston"
* Output: DistanceMatrixResult // rows[0].elements[1] = first origin to second destination
*/
/**
* PLACE SEARCH - Find businesses/POIs by text query
* Endpoint: /maps/api/place/textsearch/json
* Input: { query: string, location?: string, radius?: number, type?: string } // location: "40.7,-74.0"
* Output: PlacesSearchResult // results[].name, rating, geometry.location, place_id
*/
/**
* NEARBY SEARCH - Find places near a specific location
* Endpoint: /maps/api/place/nearbysearch/json
* Input: { location: string, radius: number, type?: string, keyword?: string } // location: "40.7,-74.0"
* Output: PlacesSearchResult
*/
/**
* PLACE DETAILS - Get comprehensive information about a specific place
* Endpoint: /maps/api/place/details/json
* Input: { place_id: string, fields?: string } // fields: "name,rating,opening_hours,website"
* Output: PlaceDetailsResult // result.name, rating, opening_hours, etc.
*/
/**
* ELEVATION - Get altitude data for geographic points
* Endpoint: /maps/api/elevation/json
* Input: { locations?: string, path?: string, samples?: number } // locations: "39.73,-104.98|36.45,-116.86"
* Output: ElevationResult // results[].elevation (meters)
*/
/**
* TIME ZONE - Get timezone information for a location
* Endpoint: /maps/api/timezone/json
* Input: { location: string, timestamp: number } // timestamp: Math.floor(Date.now()/1000)
* Output: TimeZoneResult // timeZoneId, timeZoneName
*/
/**
* ROADS - Snap GPS traces to roads, find nearest roads, get speed limits
* - /v1/snapToRoads: Input: { path: string, interpolate?: boolean } // path: "lat,lng|lat,lng"
* - /v1/nearestRoads: Input: { points: string } // points: "lat,lng|lat,lng"
* - /v1/speedLimits: Input: { path: string, units?: SpeedUnit }
* Output: RoadsResult
*/
/**
* PLACE AUTOCOMPLETE - Real-time place suggestions as user types
* Endpoint: /maps/api/place/autocomplete/json
* Input: { input: string, location?: string, radius?: number }
* Output: { predictions: Array<{ description: string, place_id: string }> }
*/
/**
* STATIC MAPS - Generate map images as URLs (for emails, reports, <img> tags)
* Endpoint: /maps/api/staticmap
* Input: URL params - center: string, zoom: number, size: string, markers?: string, maptype?: MapType
* Output: Image URL (not JSON) - use directly in <img src={url} />
* Note: Construct URL manually with getMapsConfig() for auth
*/

View file

@ -0,0 +1,110 @@
import { TRPCError } from "@trpc/server";
import { ENV } from "./env";
export type NotificationPayload = {
title: string;
content: string;
};
const TITLE_MAX_LENGTH = 1200;
const CONTENT_MAX_LENGTH = 20000;
const trimValue = (value: string): string => value.trim();
const isNonEmptyString = (value: unknown): value is string =>
typeof value === "string" && value.trim().length > 0;
const buildEndpointUrl = (baseUrl: string): string => {
const normalizedBase = baseUrl.endsWith("/")
? baseUrl
: `${baseUrl}/`;
return new URL(
"webdevtoken.v1.WebDevService/SendNotification",
normalizedBase
).toString();
};
const validatePayload = (input: NotificationPayload): NotificationPayload => {
if (!isNonEmptyString(input.title)) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "Notification title is required.",
});
}
if (!isNonEmptyString(input.content)) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "Notification content is required.",
});
}
const title = trimValue(input.title);
const content = trimValue(input.content);
if (title.length > TITLE_MAX_LENGTH) {
throw new TRPCError({
code: "BAD_REQUEST",
message: `Notification title must be at most ${TITLE_MAX_LENGTH} characters.`,
});
}
if (content.length > CONTENT_MAX_LENGTH) {
throw new TRPCError({
code: "BAD_REQUEST",
message: `Notification content must be at most ${CONTENT_MAX_LENGTH} characters.`,
});
}
return { title, content };
};
/**
* Dispatches a project-owner notification through the Manus Notification Service.
* Returns `true` if the request was accepted, `false` when the upstream service
* cannot be reached (callers can fall back to email/slack). Validation errors
* bubble up as TRPC errors so callers can fix the payload.
*/
export async function notifyOwner(
payload: NotificationPayload
): Promise<boolean> {
const { title, content } = validatePayload(payload);
if (!ENV.forgeApiUrl) {
console.warn("[Notification] forgeApiUrl is not configured. Skipping notification.");
return false;
}
if (!ENV.forgeApiKey) {
console.warn("[Notification] forgeApiKey is not configured. Skipping notification.");
return false;
}
const endpoint = buildEndpointUrl(ENV.forgeApiUrl);
try {
const response = await fetch(endpoint, {
method: "POST",
headers: {
accept: "application/json",
authorization: `Bearer ${ENV.forgeApiKey}`,
"content-type": "application/json",
"connect-protocol-version": "1",
},
body: JSON.stringify({ title, content }),
});
if (!response.ok) {
const detail = await response.text().catch(() => "");
console.warn(
`[Notification] Failed to notify owner (${response.status} ${response.statusText})${
detail ? `: ${detail}` : ""
}`
);
return false;
}
return true;
} catch (error) {
console.warn("[Notification] Error calling notification service:", error);
return false;
}
}

78
server/_core/runtime.ts Normal file
View file

@ -0,0 +1,78 @@
import fs from "node:fs/promises";
import path from "node:path";
import { getDb, isDatabaseConfigured } from "../db";
import { ENV } from "./env";
type RuntimeHealthState = "starting" | "ready" | "maintenance" | "shutting_down";
const startedAt = Date.now();
let ready = false;
let shuttingDown = false;
function resolveMaintenanceFlagPath() {
return path.resolve(ENV.maintenanceFlagPath || path.join(process.cwd(), "uploads/system/maintenance.flag"));
}
async function fileExists(filePath: string) {
try {
await fs.access(filePath);
return true;
} catch {
return false;
}
}
export function markRuntimeReady() {
ready = true;
}
export function markRuntimeShuttingDown() {
shuttingDown = true;
ready = false;
}
export async function isMaintenanceModeEnabled() {
return fileExists(resolveMaintenanceFlagPath());
}
export async function buildRuntimeHealth() {
const uptimeMs = Date.now() - startedAt;
const db = await getDb();
const databaseOk = !isDatabaseConfigured() || Boolean(db);
const startupDelaySatisfied = uptimeMs >= ENV.appReadyDelayMs;
const maintenance = await isMaintenanceModeEnabled();
let state: RuntimeHealthState = "starting";
if (shuttingDown) {
state = "shutting_down";
} else if (maintenance) {
state = "maintenance";
} else if (ready && startupDelaySatisfied && databaseOk) {
state = "ready";
}
const ok = state === "ready" || state === "maintenance";
return {
ok,
state,
service: "portail-associations",
environment: process.env.NODE_ENV || "development",
timestamp: new Date().toISOString(),
uptimeMs,
maintenance,
checks: {
startupDelaySatisfied,
databaseConfigured: isDatabaseConfigured(),
databaseOk,
ready,
shuttingDown,
},
};
}
export async function ensureMaintenanceFlagDirectory() {
const filePath = resolveMaintenanceFlagPath();
await fs.mkdir(path.dirname(filePath), { recursive: true });
return filePath;
}

View file

@ -0,0 +1,29 @@
import { z } from "zod";
import { notifyOwner } from "./notification";
import { adminProcedure, publicProcedure, router } from "./trpc";
export const systemRouter = router({
health: publicProcedure
.input(
z.object({
timestamp: z.number().min(0, "timestamp cannot be negative"),
})
)
.query(() => ({
ok: true,
})),
notifyOwner: adminProcedure
.input(
z.object({
title: z.string().min(1, "title is required"),
content: z.string().min(1, "content is required"),
})
)
.mutation(async ({ input }) => {
const delivered = await notifyOwner(input);
return {
success: delivered,
} as const;
}),
});

45
server/_core/trpc.ts Normal file
View file

@ -0,0 +1,45 @@
import { NOT_ADMIN_ERR_MSG, UNAUTHED_ERR_MSG } from '@shared/const';
import { initTRPC, TRPCError } from "@trpc/server";
import superjson from "superjson";
import type { TrpcContext } from "./context";
const t = initTRPC.context<TrpcContext>().create({
transformer: superjson,
});
export const router = t.router;
export const publicProcedure = t.procedure;
const requireUser = t.middleware(async opts => {
const { ctx, next } = opts;
if (!ctx.user) {
throw new TRPCError({ code: "UNAUTHORIZED", message: UNAUTHED_ERR_MSG });
}
return next({
ctx: {
...ctx,
user: ctx.user,
},
});
});
export const protectedProcedure = t.procedure.use(requireUser);
export const adminProcedure = t.procedure.use(
t.middleware(async opts => {
const { ctx, next } = opts;
if (!ctx.user || ctx.user.role !== 'admin') {
throw new TRPCError({ code: "FORBIDDEN", message: NOT_ADMIN_ERR_MSG });
}
return next({
ctx: {
...ctx,
user: ctx.user,
},
});
}),
);

6
server/_core/types/cookie.d.ts vendored Normal file
View file

@ -0,0 +1,6 @@
declare module "cookie" {
export function parse(
str: string,
options?: Record<string, unknown>
): Record<string, string>;
}

88
server/_core/vite.ts Normal file
View file

@ -0,0 +1,88 @@
import express, { type Express } from "express";
import fs from "fs";
import { type Server } from "http";
import { nanoid } from "nanoid";
import path from "path";
import { createServer as createViteServer } from "vite";
import viteConfig from "../../vite.config";
export async function setupVite(app: Express, server: Server) {
const serverOptions = {
middlewareMode: true,
hmr: { server },
allowedHosts: true as const,
};
const vite = await createViteServer({
...viteConfig,
configFile: false,
server: serverOptions,
appType: "custom",
});
app.use(vite.middlewares);
app.use("*", async (req, res, next) => {
const url = req.originalUrl;
try {
const clientTemplate = path.resolve(
import.meta.dirname,
"../..",
"client",
"index.html"
);
// always reload the index.html file from disk incase it changes
let template = await fs.promises.readFile(clientTemplate, "utf-8");
template = template.replace(
`src="/src/main.tsx"`,
`src="/src/main.tsx?v=${nanoid()}"`
);
const page = await vite.transformIndexHtml(url, template);
res.status(200).set({ "Content-Type": "text/html" }).end(page);
} catch (e) {
vite.ssrFixStacktrace(e as Error);
next(e);
}
});
}
export function serveStatic(app: Express) {
const distPath =
process.env.NODE_ENV === "development"
? path.resolve(import.meta.dirname, "../..", "dist", "public")
: path.resolve(import.meta.dirname, "public");
if (!fs.existsSync(distPath)) {
console.error(
`Could not find the build directory: ${distPath}, make sure to build the client first`
);
}
app.use(express.static(distPath, {
index: false,
setHeaders(res, filePath) {
if (filePath.endsWith("index.html")) {
res.setHeader("Cache-Control", "no-store");
return;
}
if (filePath.includes(`${path.sep}assets${path.sep}`)) {
res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
}
},
}));
// fall through to index.html if the file doesn't exist
app.use("*", (req, res) => {
const requestPath = req.path;
const hasFileExtension = path.extname(requestPath).length > 0;
if (requestPath.startsWith("/assets/") || hasFileExtension) {
res.status(404).type("text/plain").send("Not found");
return;
}
res.setHeader("Cache-Control", "no-store");
res.sendFile(path.resolve(distPath, "index.html"));
});
}

View file

@ -0,0 +1,284 @@
/**
* Voice transcription helper using internal Speech-to-Text service
*
* Frontend implementation guide:
* 1. Capture audio using MediaRecorder API
* 2. Upload audio to storage (e.g., S3) to get URL
* 3. Call transcription with the URL
*
* Example usage:
* ```tsx
* // Frontend component
* const transcribeMutation = trpc.voice.transcribe.useMutation({
* onSuccess: (data) => {
* console.log(data.text); // Full transcription
* console.log(data.language); // Detected language
* console.log(data.segments); // Timestamped segments
* }
* });
*
* // After uploading audio to storage
* transcribeMutation.mutate({
* audioUrl: uploadedAudioUrl,
* language: 'en', // optional
* prompt: 'Transcribe the meeting' // optional
* });
* ```
*/
import { ENV } from "./env";
export type TranscribeOptions = {
audioUrl: string; // URL to the audio file (e.g., S3 URL)
language?: string; // Optional: specify language code (e.g., "en", "es", "zh")
prompt?: string; // Optional: custom prompt for the transcription
};
// Native Whisper API segment format
export type WhisperSegment = {
id: number;
seek: number;
start: number;
end: number;
text: string;
tokens: number[];
temperature: number;
avg_logprob: number;
compression_ratio: number;
no_speech_prob: number;
};
// Native Whisper API response format
export type WhisperResponse = {
task: "transcribe";
language: string;
duration: number;
text: string;
segments: WhisperSegment[];
};
export type TranscriptionResponse = WhisperResponse; // Return native Whisper API response directly
export type TranscriptionError = {
error: string;
code: "FILE_TOO_LARGE" | "INVALID_FORMAT" | "TRANSCRIPTION_FAILED" | "UPLOAD_FAILED" | "SERVICE_ERROR";
details?: string;
};
/**
* Transcribe audio to text using the internal Speech-to-Text service
*
* @param options - Audio data and metadata
* @returns Transcription result or error
*/
export async function transcribeAudio(
options: TranscribeOptions
): Promise<TranscriptionResponse | TranscriptionError> {
try {
// Step 1: Validate environment configuration
if (!ENV.forgeApiUrl) {
return {
error: "Voice transcription service is not configured",
code: "SERVICE_ERROR",
details: "BUILT_IN_FORGE_API_URL is not set"
};
}
if (!ENV.forgeApiKey) {
return {
error: "Voice transcription service authentication is missing",
code: "SERVICE_ERROR",
details: "BUILT_IN_FORGE_API_KEY is not set"
};
}
// Step 2: Download audio from URL
let audioBuffer: Buffer;
let mimeType: string;
try {
const response = await fetch(options.audioUrl);
if (!response.ok) {
return {
error: "Failed to download audio file",
code: "INVALID_FORMAT",
details: `HTTP ${response.status}: ${response.statusText}`
};
}
audioBuffer = Buffer.from(await response.arrayBuffer());
mimeType = response.headers.get('content-type') || 'audio/mpeg';
// Check file size (16MB limit)
const sizeMB = audioBuffer.length / (1024 * 1024);
if (sizeMB > 16) {
return {
error: "Audio file exceeds maximum size limit",
code: "FILE_TOO_LARGE",
details: `File size is ${sizeMB.toFixed(2)}MB, maximum allowed is 16MB`
};
}
} catch (error) {
return {
error: "Failed to fetch audio file",
code: "SERVICE_ERROR",
details: error instanceof Error ? error.message : "Unknown error"
};
}
// Step 3: Create FormData for multipart upload to Whisper API
const formData = new FormData();
// Create a Blob from the buffer and append to form
const filename = `audio.${getFileExtension(mimeType)}`;
const audioBlob = new Blob([new Uint8Array(audioBuffer)], { type: mimeType });
formData.append("file", audioBlob, filename);
formData.append("model", "whisper-1");
formData.append("response_format", "verbose_json");
// Add prompt - use custom prompt if provided, otherwise generate based on language
const prompt = options.prompt || (
options.language
? `Transcribe the user's voice to text, the user's working language is ${getLanguageName(options.language)}`
: "Transcribe the user's voice to text"
);
formData.append("prompt", prompt);
// Step 4: Call the transcription service
const baseUrl = ENV.forgeApiUrl.endsWith("/")
? ENV.forgeApiUrl
: `${ENV.forgeApiUrl}/`;
const fullUrl = new URL(
"v1/audio/transcriptions",
baseUrl
).toString();
const response = await fetch(fullUrl, {
method: "POST",
headers: {
authorization: `Bearer ${ENV.forgeApiKey}`,
"Accept-Encoding": "identity",
},
body: formData,
});
if (!response.ok) {
const errorText = await response.text().catch(() => "");
return {
error: "Transcription service request failed",
code: "TRANSCRIPTION_FAILED",
details: `${response.status} ${response.statusText}${errorText ? `: ${errorText}` : ""}`
};
}
// Step 5: Parse and return the transcription result
const whisperResponse = await response.json() as WhisperResponse;
// Validate response structure
if (!whisperResponse.text || typeof whisperResponse.text !== 'string') {
return {
error: "Invalid transcription response",
code: "SERVICE_ERROR",
details: "Transcription service returned an invalid response format"
};
}
return whisperResponse; // Return native Whisper API response directly
} catch (error) {
// Handle unexpected errors
return {
error: "Voice transcription failed",
code: "SERVICE_ERROR",
details: error instanceof Error ? error.message : "An unexpected error occurred"
};
}
}
/**
* Helper function to get file extension from MIME type
*/
function getFileExtension(mimeType: string): string {
const mimeToExt: Record<string, string> = {
'audio/webm': 'webm',
'audio/mp3': 'mp3',
'audio/mpeg': 'mp3',
'audio/wav': 'wav',
'audio/wave': 'wav',
'audio/ogg': 'ogg',
'audio/m4a': 'm4a',
'audio/mp4': 'm4a',
};
return mimeToExt[mimeType] || 'audio';
}
/**
* Helper function to get full language name from ISO code
*/
function getLanguageName(langCode: string): string {
const langMap: Record<string, string> = {
'en': 'English',
'es': 'Spanish',
'fr': 'French',
'de': 'German',
'it': 'Italian',
'pt': 'Portuguese',
'ru': 'Russian',
'ja': 'Japanese',
'ko': 'Korean',
'zh': 'Chinese',
'ar': 'Arabic',
'hi': 'Hindi',
'nl': 'Dutch',
'pl': 'Polish',
'tr': 'Turkish',
'sv': 'Swedish',
'da': 'Danish',
'no': 'Norwegian',
'fi': 'Finnish',
};
return langMap[langCode] || langCode;
}
/**
* Example tRPC procedure implementation:
*
* ```ts
* // In server/routers.ts
* import { transcribeAudio } from "./_core/voiceTranscription";
*
* export const voiceRouter = router({
* transcribe: protectedProcedure
* .input(z.object({
* audioUrl: z.string(),
* language: z.string().optional(),
* prompt: z.string().optional(),
* }))
* .mutation(async ({ input, ctx }) => {
* const result = await transcribeAudio(input);
*
* // Check if it's an error
* if ('error' in result) {
* throw new TRPCError({
* code: 'BAD_REQUEST',
* message: result.error,
* cause: result,
* });
* }
*
* // Optionally save transcription to database
* await db.insert(transcriptions).values({
* userId: ctx.user.id,
* text: result.text,
* duration: result.duration,
* language: result.language,
* audioUrl: input.audioUrl,
* createdAt: new Date(),
* });
*
* return result;
* }),
* });
* ```
*/