Initial commit: itinova-podcasts v1

Stack: Node.js/Express + React/Vite + tRPC + MySQL (Drizzle ORM)
Features: Gestion de podcasts, établissements, mots-clés, upload audio S3
Migrations: 0000-0002 (users, etablissements, mots_cles, podcasts, podcast_mots_cles)
This commit is contained in:
manus-admin
2026-04-12 18:34:56 -04:00
commit aab11c8308
138 changed files with 27782 additions and 0 deletions

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

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

48
server/_core/cookies.ts Normal file
View File

@@ -0,0 +1,48 @@
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;
return {
httpOnly: true,
path: "/",
sameSite: "none",
secure: isSecureRequest(req),
};
}

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;
}

10
server/_core/env.ts Normal file
View File

@@ -0,0 +1,10 @@
export const ENV = {
appId: process.env.VITE_APP_ID ?? "",
cookieSecret: process.env.JWT_SECRET ?? "",
databaseUrl: process.env.DATABASE_URL ?? "",
oAuthServerUrl: process.env.OAUTH_SERVER_URL ?? "",
ownerOpenId: process.env.OWNER_OPEN_ID ?? "",
isProduction: process.env.NODE_ENV === "production",
forgeApiUrl: process.env.BUILT_IN_FORGE_API_URL ?? "",
forgeApiKey: process.env.BUILT_IN_FORGE_API_KEY ?? "",
};

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,
};
}

102
server/_core/index.ts Normal file
View File

@@ -0,0 +1,102 @@
import "dotenv/config";
import express from "express";
import { createServer } from "http";
import net from "net";
import { createExpressMiddleware } from "@trpc/server/adapters/express";
import { registerOAuthRoutes } from "./oauth";
import { appRouter } from "../routers";
import { createContext } from "./context";
import { serveStatic, setupVite } from "./vite";
import { storagePut } from "../storage";
import { nanoid } from "nanoid";
import { sdk } from "./sdk";
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);
app.use(express.json({ limit: "60mb" }));
app.use(express.urlencoded({ limit: "60mb", extended: true }));
// OAuth callback under /api/oauth/callback
registerOAuthRoutes(app);
// Route d'upload audio (base64 → S3)
app.post("/api/upload-audio", async (req, res) => {
try {
let user;
try { user = await sdk.authenticateRequest(req); } catch { user = null; }
if (!user) {
res.status(401).json({ error: "Non authentifié" });
return;
}
const { data, contentType, filename } = req.body as {
data: string;
contentType: string;
filename: string;
};
if (!data || !contentType) {
res.status(400).json({ error: "Données manquantes" });
return;
}
const ext = filename?.split(".").pop() ?? "mp3";
const key = `podcasts/audio/${nanoid()}.${ext}`;
const buffer = Buffer.from(data, "base64");
const { url } = await storagePut(key, buffer, contentType);
res.json({ key, url });
} catch (err: any) {
console.error("[upload-audio]", err);
res.status(500).json({ error: err.message ?? "Erreur serveur" });
}
});
// tRPC API
app.use(
"/api/trpc",
createExpressMiddleware({
router: appRouter,
createContext,
})
);
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}/`);
});
}
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,114 @@
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) {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "Notification service URL is not configured.",
});
}
if (!ENV.forgeApiKey) {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "Notification service API key is not configured.",
});
}
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;
}
}

53
server/_core/oauth.ts Normal file
View File

@@ -0,0 +1,53 @@
import { COOKIE_NAME, ONE_YEAR_MS } from "@shared/const";
import type { Express, Request, Response } from "express";
import * as db from "../db";
import { getSessionCookieOptions } from "./cookies";
import { sdk } from "./sdk";
function getQueryParam(req: Request, key: string): string | undefined {
const value = req.query[key];
return typeof value === "string" ? value : undefined;
}
export function registerOAuthRoutes(app: Express) {
app.get("/api/oauth/callback", async (req: Request, res: Response) => {
const code = getQueryParam(req, "code");
const state = getQueryParam(req, "state");
if (!code || !state) {
res.status(400).json({ error: "code and state are required" });
return;
}
try {
const tokenResponse = await sdk.exchangeCodeForToken(code, state);
const userInfo = await sdk.getUserInfo(tokenResponse.accessToken);
if (!userInfo.openId) {
res.status(400).json({ error: "openId missing from user info" });
return;
}
await db.upsertUser({
openId: userInfo.openId,
name: userInfo.name || null,
email: userInfo.email ?? null,
loginMethod: userInfo.loginMethod ?? userInfo.platform ?? null,
lastSignedIn: new Date(),
});
const sessionToken = await sdk.createSessionToken(userInfo.openId, {
name: userInfo.name || "",
expiresInMs: ONE_YEAR_MS,
});
const cookieOptions = getSessionCookieOptions(req);
res.cookie(COOKIE_NAME, sessionToken, { ...cookieOptions, maxAge: ONE_YEAR_MS });
res.redirect(302, "/");
} catch (error) {
console.error("[OAuth] Callback failed", error);
res.status(500).json({ error: "OAuth callback failed" });
}
});
}

292
server/_core/sdk.ts Normal file
View File

@@ -0,0 +1,292 @@
import { AXIOS_TIMEOUT_MS, COOKIE_NAME, ONE_YEAR_MS } from "@shared/const";
import { ForbiddenError } from "@shared/_core/errors";
import axios, { type AxiosInstance } from "axios";
import { parse as parseCookieHeader } from "cookie";
import type { Request } from "express";
import { SignJWT, jwtVerify } from "jose";
import type { User } from "../../drizzle/schema";
import * as db from "../db";
import { ENV } from "./env";
import type {
ExchangeTokenRequest,
ExchangeTokenResponse,
GetUserInfoResponse,
GetUserInfoWithJwtRequest,
GetUserInfoWithJwtResponse,
} from "./types/manusTypes";
// Utility function
const isNonEmptyString = (value: unknown): value is string =>
typeof value === "string" && value.length > 0;
export type SessionPayload = {
openId: string;
appId: string;
name: string;
};
const EXCHANGE_TOKEN_PATH = `/webdev.v1.WebDevAuthPublicService/ExchangeToken`;
const GET_USER_INFO_PATH = `/webdev.v1.WebDevAuthPublicService/GetUserInfo`;
const GET_USER_INFO_WITH_JWT_PATH = `/webdev.v1.WebDevAuthPublicService/GetUserInfoWithJwt`;
class OAuthService {
constructor(private client: ReturnType<typeof axios.create>) {
console.log("[OAuth] Initialized with baseURL:", ENV.oAuthServerUrl);
if (!ENV.oAuthServerUrl) {
console.error(
"[OAuth] ERROR: OAUTH_SERVER_URL is not configured! Set OAUTH_SERVER_URL environment variable."
);
}
}
private decodeState(state: string): string {
const redirectUri = atob(state);
return redirectUri;
}
async getTokenByCode(
code: string,
state: string
): Promise<ExchangeTokenResponse> {
const payload: ExchangeTokenRequest = {
clientId: ENV.appId,
grantType: "authorization_code",
code,
redirectUri: this.decodeState(state),
};
const { data } = await this.client.post<ExchangeTokenResponse>(
EXCHANGE_TOKEN_PATH,
payload
);
return data;
}
async getUserInfoByToken(
token: ExchangeTokenResponse
): Promise<GetUserInfoResponse> {
const { data } = await this.client.post<GetUserInfoResponse>(
GET_USER_INFO_PATH,
{
accessToken: token.accessToken,
}
);
return data;
}
}
const createOAuthHttpClient = (): AxiosInstance =>
axios.create({
baseURL: ENV.oAuthServerUrl,
timeout: AXIOS_TIMEOUT_MS,
});
class SDKServer {
private readonly client: AxiosInstance;
private readonly oauthService: OAuthService;
constructor(client: AxiosInstance = createOAuthHttpClient()) {
this.client = client;
this.oauthService = new OAuthService(this.client);
}
private deriveLoginMethod(
platforms: unknown,
fallback: string | null | undefined
): string | null {
if (fallback && fallback.length > 0) return fallback;
if (!Array.isArray(platforms) || platforms.length === 0) return null;
const set = new Set<string>(
platforms.filter((p): p is string => typeof p === "string")
);
if (set.has("REGISTERED_PLATFORM_EMAIL")) return "email";
if (set.has("REGISTERED_PLATFORM_GOOGLE")) return "google";
if (set.has("REGISTERED_PLATFORM_APPLE")) return "apple";
if (
set.has("REGISTERED_PLATFORM_MICROSOFT") ||
set.has("REGISTERED_PLATFORM_AZURE")
)
return "microsoft";
if (set.has("REGISTERED_PLATFORM_GITHUB")) return "github";
const first = Array.from(set)[0];
return first ? first.toLowerCase() : null;
}
/**
* Exchange OAuth authorization code for access token
* @example
* const tokenResponse = await sdk.exchangeCodeForToken(code, state);
*/
async exchangeCodeForToken(
code: string,
state: string
): Promise<ExchangeTokenResponse> {
return this.oauthService.getTokenByCode(code, state);
}
/**
* Get user information using access token
* @example
* const userInfo = await sdk.getUserInfo(tokenResponse.accessToken);
*/
async getUserInfo(accessToken: string): Promise<GetUserInfoResponse> {
const data = await this.oauthService.getUserInfoByToken({
accessToken,
} as ExchangeTokenResponse);
const loginMethod = this.deriveLoginMethod(
(data as any)?.platforms,
(data as any)?.platform ?? data.platform ?? null
);
return {
...(data as any),
platform: loginMethod,
loginMethod,
} as GetUserInfoResponse;
}
private parseCookies(cookieHeader: string | undefined) {
if (!cookieHeader) {
return new Map<string, string>();
}
const parsed = parseCookieHeader(cookieHeader);
return new Map(Object.entries(parsed));
}
private getSessionSecret() {
const secret = ENV.cookieSecret;
return new TextEncoder().encode(secret);
}
/**
* Create a session token for a Manus user openId
* @example
* const sessionToken = await sdk.createSessionToken(userInfo.openId);
*/
async createSessionToken(
openId: string,
options: { expiresInMs?: number; name?: string } = {}
): Promise<string> {
return this.signSession(
{
openId,
appId: ENV.appId,
name: options.name || "",
},
options
);
}
async signSession(
payload: SessionPayload,
options: { expiresInMs?: number } = {}
): Promise<string> {
const issuedAt = Date.now();
const expiresInMs = options.expiresInMs ?? ONE_YEAR_MS;
const expirationSeconds = Math.floor((issuedAt + expiresInMs) / 1000);
const secretKey = this.getSessionSecret();
return new SignJWT({
openId: payload.openId,
appId: payload.appId,
name: payload.name,
})
.setProtectedHeader({ alg: "HS256", typ: "JWT" })
.setExpirationTime(expirationSeconds)
.sign(secretKey);
}
async verifySession(
cookieValue: string | undefined | null
): Promise<{ openId: string; appId: string; name: string } | null> {
if (!cookieValue) {
console.warn("[Auth] Missing session cookie");
return null;
}
try {
const secretKey = this.getSessionSecret();
const { payload } = await jwtVerify(cookieValue, secretKey, {
algorithms: ["HS256"],
});
const { openId, appId, name } = payload as Record<string, unknown>;
if (
!isNonEmptyString(openId) ||
!isNonEmptyString(appId) ||
!isNonEmptyString(name)
) {
console.warn("[Auth] Session payload missing required fields");
return null;
}
return {
openId,
appId,
name,
};
} catch (error) {
console.warn("[Auth] Session verification failed", String(error));
return null;
}
}
async getUserInfoWithJwt(
jwtToken: string
): Promise<GetUserInfoWithJwtResponse> {
const payload: GetUserInfoWithJwtRequest = {
jwtToken,
projectId: ENV.appId,
};
const { data } = await this.client.post<GetUserInfoWithJwtResponse>(
GET_USER_INFO_WITH_JWT_PATH,
payload
);
const loginMethod = this.deriveLoginMethod(
(data as any)?.platforms,
(data as any)?.platform ?? data.platform ?? null
);
return {
...(data as any),
platform: loginMethod,
loginMethod,
} as GetUserInfoWithJwtResponse;
}
async authenticateRequest(req: Request): Promise<User> {
// Only accept local sessions (appId === "local").
// OAuth Manus sessions are rejected to prevent ghost logins.
const cookies = this.parseCookies(req.headers.cookie);
const sessionCookie = cookies.get(COOKIE_NAME);
const session = await this.verifySession(sessionCookie);
if (!session) {
throw ForbiddenError("Invalid session cookie");
}
// Reject any session that was not created by the local auth flow
if (session.appId !== "local") {
throw ForbiddenError("Only local sessions are accepted");
}
const sessionUserId = session.openId;
const signedInAt = new Date();
const user = await db.getUserByOpenId(sessionUserId);
if (!user) {
throw ForbiddenError("User not found");
}
await db.upsertUser({
openId: user.openId,
lastSignedIn: signedInAt,
});
return user;
}
}
export const sdk = new SDKServer();

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>;
}

View File

@@ -0,0 +1,69 @@
// WebDev Auth TypeScript types
// Auto-generated from protobuf definitions
// Generated on: 2025-09-24T05:57:57.338Z
export interface AuthorizeRequest {
redirectUri: string;
projectId: string;
state: string;
responseType: string;
scope: string;
}
export interface AuthorizeResponse {
redirectUrl: string;
}
export interface ExchangeTokenRequest {
grantType: string;
code: string;
refreshToken?: string;
clientId: string;
clientSecret?: string;
redirectUri: string;
}
export interface ExchangeTokenResponse {
accessToken: string;
tokenType: string;
expiresIn: number;
refreshToken?: string;
scope: string;
idToken: string;
}
export interface GetUserInfoRequest {
accessToken: string;
}
export interface GetUserInfoResponse {
openId: string;
projectId: string;
name: string;
email?: string | null;
platform?: string | null;
loginMethod?: string | null;
}
export interface CanAccessRequest {
openId: string;
projectId: string;
}
export interface CanAccessResponse {
canAccess: boolean;
}
export interface GetUserInfoWithJwtRequest {
jwtToken: string;
projectId: string;
}
export interface GetUserInfoWithJwtResponse {
openId: string;
projectId: string;
name: string;
email?: string | null;
platform?: string | null;
loginMethod?: string | null;
}

67
server/_core/vite.ts Normal file
View File

@@ -0,0 +1,67 @@
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));
// fall through to index.html if the file doesn't exist
app.use("*", (_req, res) => {
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;
* }),
* });
* ```
*/

198
server/auth.local.test.ts Normal file
View File

@@ -0,0 +1,198 @@
import { describe, expect, it, vi, beforeEach } from "vitest";
import { appRouter } from "./routers";
import type { TrpcContext } from "./_core/context";
import bcrypt from "bcryptjs";
// ─── Mocks ─────────────────────────────────────────────────────────────────────
const mockPasswordHash = bcrypt.hashSync("Itinova69!", 10);
vi.mock("./db", () => ({
getUserByUsername: vi.fn().mockImplementation(async (username: string) => {
if (username === "adminServPodcast") {
return {
id: 99,
openId: "local-adminServPodcast",
username: "adminServPodcast",
name: "Administrateur Service Podcast",
email: null,
loginMethod: "local",
role: "admin",
passwordHash: mockPasswordHash,
immutable: true,
createdAt: new Date(),
updatedAt: new Date(),
lastSignedIn: new Date(),
};
}
return undefined;
}),
getUserByOpenId: vi.fn().mockImplementation(async (openId: string) => {
if (openId === "local-adminServPodcast") {
return {
id: 99,
openId: "local-adminServPodcast",
username: "adminServPodcast",
name: "Administrateur Service Podcast",
email: null,
loginMethod: "local",
role: "admin",
passwordHash: mockPasswordHash,
immutable: true,
createdAt: new Date(),
updatedAt: new Date(),
lastSignedIn: new Date(),
};
}
return undefined;
}),
upsertUser: vi.fn().mockResolvedValue(undefined),
getAllEtablissements: vi.fn().mockResolvedValue([]),
getAllMotsCles: vi.fn().mockResolvedValue([]),
getPodcasts: vi.fn().mockResolvedValue([]),
getPodcastById: vi.fn().mockResolvedValue(null),
createPodcast: vi.fn().mockResolvedValue(1),
updatePodcast: vi.fn().mockResolvedValue(undefined),
deletePodcast: vi.fn().mockResolvedValue(undefined),
getPodcastStats: vi.fn().mockResolvedValue({ total: 0, publies: 0, brouillons: 0, etablissements: 0 }),
getAllUsers: vi.fn().mockResolvedValue([]),
updateUserRole: vi.fn().mockResolvedValue(undefined),
createLocalUser: vi.fn().mockResolvedValue(undefined),
getEtablissementById: vi.fn().mockResolvedValue(null),
createEtablissement: vi.fn().mockResolvedValue(undefined),
updateEtablissement: vi.fn().mockResolvedValue(undefined),
deleteEtablissement: vi.fn().mockResolvedValue(undefined),
createMotCle: vi.fn().mockResolvedValue(undefined),
deleteMotCle: vi.fn().mockResolvedValue(undefined),
}));
// ─── Helpers ───────────────────────────────────────────────────────────────────
function makePublicCtx(): TrpcContext {
const cookies: Record<string, string> = {};
return {
user: null,
req: {
protocol: "https",
headers: {},
} as TrpcContext["req"],
res: {
clearCookie: vi.fn(),
cookie: vi.fn((name: string, value: string) => {
cookies[name] = value;
}),
} as unknown as TrpcContext["res"],
};
}
// ─── Tests ─────────────────────────────────────────────────────────────────────
describe("auth.loginLocal", () => {
it("réussit avec les bonnes credentials adminServPodcast", async () => {
const ctx = makePublicCtx();
const caller = appRouter.createCaller(ctx);
const result = await caller.auth.loginLocal({
username: "adminServPodcast",
password: "Itinova69!",
});
expect(result.success).toBe(true);
expect(result.user).toBeDefined();
expect(result.user.username).toBe("adminServPodcast");
expect(result.user.role).toBe("admin");
expect(result.user.immutable).toBe(true);
});
it("échoue avec un mauvais mot de passe", async () => {
const ctx = makePublicCtx();
const caller = appRouter.createCaller(ctx);
await expect(
caller.auth.loginLocal({
username: "adminServPodcast",
password: "mauvais-mot-de-passe",
})
).rejects.toMatchObject({
code: "UNAUTHORIZED",
message: "Identifiant ou mot de passe incorrect",
});
});
it("échoue avec un utilisateur inexistant", async () => {
const ctx = makePublicCtx();
const caller = appRouter.createCaller(ctx);
await expect(
caller.auth.loginLocal({
username: "utilisateurInexistant",
password: "n'importe-quoi",
})
).rejects.toMatchObject({
code: "UNAUTHORIZED",
});
});
it("définit un cookie de session après connexion réussie", async () => {
const setCookieCalls: Array<{ name: string; value: string }> = [];
const ctx: TrpcContext = {
user: null,
req: { protocol: "https", headers: {} } as TrpcContext["req"],
res: {
clearCookie: vi.fn(),
cookie: vi.fn((name: string, value: string) => {
setCookieCalls.push({ name, value });
}),
} as unknown as TrpcContext["res"],
};
const caller = appRouter.createCaller(ctx);
await caller.auth.loginLocal({
username: "adminServPodcast",
password: "Itinova69!",
});
expect(setCookieCalls.length).toBeGreaterThan(0);
expect(setCookieCalls[0].name).toBeDefined();
expect(typeof setCookieCalls[0].value).toBe("string");
expect(setCookieCalls[0].value.length).toBeGreaterThan(10);
});
});
describe("compte adminServPodcast - propriétés immuables", () => {
it("le compte est marqué immutable = true", async () => {
const ctx = makePublicCtx();
const caller = appRouter.createCaller(ctx);
const result = await caller.auth.loginLocal({
username: "adminServPodcast",
password: "Itinova69!",
});
expect(result.user.immutable).toBe(true);
});
it("le compte a le rôle admin", async () => {
const ctx = makePublicCtx();
const caller = appRouter.createCaller(ctx);
const result = await caller.auth.loginLocal({
username: "adminServPodcast",
password: "Itinova69!",
});
expect(result.user.role).toBe("admin");
});
it("le compte utilise la méthode de connexion locale", async () => {
const ctx = makePublicCtx();
const caller = appRouter.createCaller(ctx);
const result = await caller.auth.loginLocal({
username: "adminServPodcast",
password: "Itinova69!",
});
expect(result.user.loginMethod).toBe("local");
});
});

View File

@@ -0,0 +1,62 @@
import { describe, expect, it } from "vitest";
import { appRouter } from "./routers";
import { COOKIE_NAME } from "../shared/const";
import type { TrpcContext } from "./_core/context";
type CookieCall = {
name: string;
options: Record<string, unknown>;
};
type AuthenticatedUser = NonNullable<TrpcContext["user"]>;
function createAuthContext(): { ctx: TrpcContext; clearedCookies: CookieCall[] } {
const clearedCookies: CookieCall[] = [];
const user: AuthenticatedUser = {
id: 1,
openId: "sample-user",
email: "sample@example.com",
name: "Sample User",
loginMethod: "manus",
role: "user",
createdAt: new Date(),
updatedAt: new Date(),
lastSignedIn: new Date(),
};
const ctx: TrpcContext = {
user,
req: {
protocol: "https",
headers: {},
} as TrpcContext["req"],
res: {
clearCookie: (name: string, options: Record<string, unknown>) => {
clearedCookies.push({ name, options });
},
} as TrpcContext["res"],
};
return { ctx, clearedCookies };
}
describe("auth.logout", () => {
it("clears the session cookie and reports success", async () => {
const { ctx, clearedCookies } = createAuthContext();
const caller = appRouter.createCaller(ctx);
const result = await caller.auth.logout();
expect(result).toEqual({ success: true });
expect(clearedCookies).toHaveLength(1);
expect(clearedCookies[0]?.name).toBe(COOKIE_NAME);
expect(clearedCookies[0]?.options).toMatchObject({
maxAge: -1,
secure: true,
sameSite: "none",
httpOnly: true,
path: "/",
});
});
});

380
server/db.ts Normal file
View File

@@ -0,0 +1,380 @@
import { and, desc, eq, inArray, like, or, sql } from "drizzle-orm";
import { drizzle } from "drizzle-orm/mysql2";
import {
etablissements,
InsertEtablissement,
InsertMotCle,
InsertPodcast,
InsertUser,
motsCles,
podcastMotsCles,
podcasts,
users,
} from "../drizzle/schema";
import { ENV } from "./_core/env";
let _db: ReturnType<typeof drizzle> | null = null;
export async function getDb() {
if (!_db && process.env.DATABASE_URL) {
try {
_db = drizzle(process.env.DATABASE_URL);
} catch (error) {
console.warn("[Database] Failed to connect:", error);
_db = null;
}
}
return _db;
}
// ─── Users ─────────────────────────────────────────────────────────────────────
export async function upsertUser(user: InsertUser): Promise<void> {
if (!user.openId) throw new Error("User openId is required for upsert");
const db = await getDb();
if (!db) return;
const values: InsertUser = { openId: user.openId };
const updateSet: Record<string, unknown> = {};
const textFields = ["name", "email", "loginMethod"] as const;
textFields.forEach((field) => {
const value = user[field];
if (value === undefined) return;
const normalized = value ?? null;
values[field] = normalized;
updateSet[field] = normalized;
});
if (user.lastSignedIn !== undefined) {
values.lastSignedIn = user.lastSignedIn;
updateSet.lastSignedIn = user.lastSignedIn;
}
if (user.role !== undefined) {
values.role = user.role;
updateSet.role = user.role;
} else if (user.openId === ENV.ownerOpenId) {
values.role = "admin";
updateSet.role = "admin";
}
if (!values.lastSignedIn) values.lastSignedIn = new Date();
if (Object.keys(updateSet).length === 0) updateSet.lastSignedIn = new Date();
await db.insert(users).values(values).onDuplicateKeyUpdate({ set: updateSet });
}
export async function getUserByOpenId(openId: string) {
const db = await getDb();
if (!db) return undefined;
const result = await db.select().from(users).where(eq(users.openId, openId)).limit(1);
return result[0];
}
export async function getAllUsers() {
const db = await getDb();
if (!db) return [];
return db.select().from(users).orderBy(desc(users.createdAt));
}
export async function updateUserRole(userId: number, role: "user" | "admin") {
const db = await getDb();
if (!db) return;
// Protect immutable accounts
const target = await db.select().from(users).where(eq(users.id, userId)).limit(1);
if (target[0]?.immutable) throw new Error("Ce compte est immuable et ne peut pas être modifié");
await db.update(users).set({ role }).where(eq(users.id, userId));
}
export async function getUserByUsername(username: string) {
const db = await getDb();
if (!db) return undefined;
const result = await db.select().from(users).where(eq(users.username, username)).limit(1);
return result[0];
}
export async function createLocalUser(data: {
username: string;
passwordHash: string;
name: string;
role: "user" | "admin";
immutable?: boolean;
openId: string;
}) {
const db = await getDb();
if (!db) throw new Error("DB not available");
await db.insert(users).values({
openId: data.openId,
username: data.username,
passwordHash: data.passwordHash,
name: data.name,
role: data.role,
immutable: data.immutable ?? false,
loginMethod: "local",
lastSignedIn: new Date(),
}).onDuplicateKeyUpdate({
set: { name: data.name, role: data.role },
});
}
export async function updateUser(
id: number,
data: { name?: string; username?: string; passwordHash?: string; role?: "user" | "admin" }
) {
const db = await getDb();
if (!db) throw new Error("DB not available");
const target = await db.select().from(users).where(eq(users.id, id)).limit(1);
if (!target[0]) throw new Error("Utilisateur introuvable");
if (target[0].immutable) throw new Error("Ce compte est immuable et ne peut pas être modifié");
const updateData: Record<string, unknown> = {};
if (data.name !== undefined) updateData.name = data.name;
if (data.username !== undefined) updateData.username = data.username;
if (data.passwordHash !== undefined) updateData.passwordHash = data.passwordHash;
if (data.role !== undefined) updateData.role = data.role;
if (Object.keys(updateData).length > 0) {
await db.update(users).set(updateData).where(eq(users.id, id));
}
}
export async function deleteUser(id: number) {
const db = await getDb();
if (!db) throw new Error("DB not available");
const target = await db.select().from(users).where(eq(users.id, id)).limit(1);
if (!target[0]) throw new Error("Utilisateur introuvable");
if (target[0].immutable) throw new Error("Ce compte est immuable et ne peut pas être supprimé");
await db.delete(users).where(eq(users.id, id));
}
export async function getUserById(id: number) {
const db = await getDb();
if (!db) return undefined;
const result = await db.select().from(users).where(eq(users.id, id)).limit(1);
return result[0];
}
// ─── Établissements ────────────────────────────────────────────────────────────
export async function getAllEtablissements() {
const db = await getDb();
if (!db) return [];
return db.select().from(etablissements).orderBy(etablissements.nom);
}
export async function getEtablissementById(id: number) {
const db = await getDb();
if (!db) return undefined;
const result = await db.select().from(etablissements).where(eq(etablissements.id, id)).limit(1);
return result[0];
}
export async function createEtablissement(data: InsertEtablissement) {
const db = await getDb();
if (!db) throw new Error("DB not available");
const result = await db.insert(etablissements).values(data);
return result[0];
}
export async function updateEtablissement(id: number, data: Partial<InsertEtablissement>) {
const db = await getDb();
if (!db) throw new Error("DB not available");
await db.update(etablissements).set(data).where(eq(etablissements.id, id));
}
export async function deleteEtablissement(id: number) {
const db = await getDb();
if (!db) throw new Error("DB not available");
await db.delete(etablissements).where(eq(etablissements.id, id));
}
// ─── Mots-clés ─────────────────────────────────────────────────────────────────
export async function getAllMotsCles() {
const db = await getDb();
if (!db) return [];
return db.select().from(motsCles).orderBy(motsCles.label);
}
export async function createMotCle(data: InsertMotCle) {
const db = await getDb();
if (!db) throw new Error("DB not available");
await db.insert(motsCles).values(data);
}
export async function deleteMotCle(id: number) {
const db = await getDb();
if (!db) throw new Error("DB not available");
await db.delete(motsCles).where(eq(motsCles.id, id));
}
// ─── Podcasts ──────────────────────────────────────────────────────────────────
export interface PodcastWithRelations {
id: number;
titre: string;
resume: string;
etablissementId: number;
etablissementNom: string;
audioUrl: string | null;
audioKey: string | null;
dureeSecondes: number | null;
statut: "brouillon" | "publie";
auteurId: number | null;
auteurNom: string | null;
imageUrl: string | null;
createdAt: Date;
updatedAt: Date;
motsCles: { id: number; label: string }[];
}
export async function getPodcasts(opts?: {
etablissementId?: number;
motCleIds?: number[];
search?: string;
statut?: "brouillon" | "publie";
auteurId?: number;
}): Promise<PodcastWithRelations[]> {
const db = await getDb();
if (!db) return [];
const conditions = [];
if (opts?.etablissementId) conditions.push(eq(podcasts.etablissementId, opts.etablissementId));
if (opts?.statut) conditions.push(eq(podcasts.statut, opts.statut));
if (opts?.auteurId) conditions.push(eq(podcasts.auteurId, opts.auteurId));
if (opts?.search) {
conditions.push(
or(
like(podcasts.titre, `%${opts.search}%`),
like(podcasts.resume, `%${opts.search}%`)
)
);
}
const rows = await db
.select({
id: podcasts.id,
titre: podcasts.titre,
resume: podcasts.resume,
etablissementId: podcasts.etablissementId,
etablissementNom: etablissements.nom,
audioUrl: podcasts.audioUrl,
audioKey: podcasts.audioKey,
dureeSecondes: podcasts.dureeSecondes,
statut: podcasts.statut,
auteurId: podcasts.auteurId,
auteurNom: users.name,
imageUrl: podcasts.imageUrl,
createdAt: podcasts.createdAt,
updatedAt: podcasts.updatedAt,
})
.from(podcasts)
.leftJoin(etablissements, eq(podcasts.etablissementId, etablissements.id))
.leftJoin(users, eq(podcasts.auteurId, users.id))
.where(conditions.length > 0 ? and(...conditions) : undefined)
.orderBy(desc(podcasts.createdAt));
// Charger les mots-clés pour chaque podcast
const podcastIds = rows.map((r) => r.id);
let keywordsMap: Map<number, { id: number; label: string }[]> = new Map();
if (podcastIds.length > 0) {
const kwRows = await db
.select({
podcastId: podcastMotsCles.podcastId,
motCleId: motsCles.id,
label: motsCles.label,
})
.from(podcastMotsCles)
.innerJoin(motsCles, eq(podcastMotsCles.motCleId, motsCles.id))
.where(inArray(podcastMotsCles.podcastId, podcastIds));
for (const kw of kwRows) {
if (!keywordsMap.has(kw.podcastId)) keywordsMap.set(kw.podcastId, []);
keywordsMap.get(kw.podcastId)!.push({ id: kw.motCleId, label: kw.label });
}
}
let result = rows.map((r) => ({
...r,
etablissementNom: r.etablissementNom ?? "",
auteurNom: r.auteurNom ?? null,
motsCles: keywordsMap.get(r.id) ?? [],
}));
// Filtrer par mots-clés si demandé
if (opts?.motCleIds && opts.motCleIds.length > 0) {
result = result.filter((p) =>
opts.motCleIds!.some((id) => p.motsCles.some((mk) => mk.id === id))
);
}
return result;
}
export async function getPodcastById(id: number): Promise<PodcastWithRelations | undefined> {
const results = await getPodcasts();
return results.find((p) => p.id === id);
}
export async function createPodcast(
data: InsertPodcast,
motCleIds: number[]
): Promise<number> {
const db = await getDb();
if (!db) throw new Error("DB not available");
const result = await db.insert(podcasts).values(data);
const insertId = (result[0] as any).insertId as number;
if (motCleIds.length > 0) {
await db.insert(podcastMotsCles).values(
motCleIds.map((motCleId) => ({ podcastId: insertId, motCleId }))
);
}
return insertId;
}
export async function updatePodcast(
id: number,
data: Partial<InsertPodcast>,
motCleIds?: number[]
) {
const db = await getDb();
if (!db) throw new Error("DB not available");
await db.update(podcasts).set(data).where(eq(podcasts.id, id));
if (motCleIds !== undefined) {
await db.delete(podcastMotsCles).where(eq(podcastMotsCles.podcastId, id));
if (motCleIds.length > 0) {
await db.insert(podcastMotsCles).values(
motCleIds.map((motCleId) => ({ podcastId: id, motCleId }))
);
}
}
}
export async function deletePodcast(id: number) {
const db = await getDb();
if (!db) throw new Error("DB not available");
await db.delete(podcasts).where(eq(podcasts.id, id));
}
export async function getPodcastStats() {
const db = await getDb();
if (!db) return { total: 0, publies: 0, brouillons: 0, etablissements: 0 };
const [totalRow] = await db.select({ count: sql<number>`count(*)` }).from(podcasts);
const [publiesRow] = await db
.select({ count: sql<number>`count(*)` })
.from(podcasts)
.where(eq(podcasts.statut, "publie"));
const [etabRow] = await db.select({ count: sql<number>`count(*)` }).from(etablissements);
const total = Number(totalRow?.count ?? 0);
const publies = Number(publiesRow?.count ?? 0);
return {
total,
publies,
brouillons: total - publies,
etablissements: Number(etabRow?.count ?? 0),
};
}

244
server/podcasts.test.ts Normal file
View File

@@ -0,0 +1,244 @@
import { describe, expect, it, vi, beforeEach } from "vitest";
import { appRouter } from "./routers";
import type { TrpcContext } from "./_core/context";
// Mock the db module
vi.mock("./db", () => ({
getAllEtablissements: vi.fn().mockResolvedValue([
{ id: 1, nom: "Établissement Test", description: null, logoUrl: null, actif: true, createdAt: new Date(), updatedAt: new Date() },
]),
getEtablissementById: vi.fn().mockResolvedValue({ id: 1, nom: "Établissement Test", description: null }),
createEtablissement: vi.fn().mockResolvedValue(undefined),
updateEtablissement: vi.fn().mockResolvedValue(undefined),
deleteEtablissement: vi.fn().mockResolvedValue(undefined),
getAllMotsCles: vi.fn().mockResolvedValue([
{ id: 1, label: "Bien-être", createdAt: new Date() },
{ id: 2, label: "Formation", createdAt: new Date() },
]),
createMotCle: vi.fn().mockResolvedValue(undefined),
deleteMotCle: vi.fn().mockResolvedValue(undefined),
getPodcasts: vi.fn().mockResolvedValue([
{
id: 1,
titre: "Podcast Test",
resume: "Un résumé de test",
etablissementId: 1,
etablissementNom: "Établissement Test",
audioUrl: "https://example.com/audio.mp3",
audioKey: "podcasts/audio/test.mp3",
dureeSecondes: 300,
statut: "publie",
auteurId: 1,
auteurNom: "Test User",
imageUrl: null,
createdAt: new Date(),
updatedAt: new Date(),
motsCles: [{ id: 1, label: "Bien-être" }],
},
]),
getPodcastById: vi.fn().mockResolvedValue({
id: 1,
titre: "Podcast Test",
resume: "Un résumé de test",
etablissementId: 1,
etablissementNom: "Établissement Test",
audioUrl: "https://example.com/audio.mp3",
audioKey: "podcasts/audio/test.mp3",
dureeSecondes: 300,
statut: "publie",
auteurId: 1,
auteurNom: "Test User",
imageUrl: null,
createdAt: new Date(),
updatedAt: new Date(),
motsCles: [{ id: 1, label: "Bien-être" }],
}),
createPodcast: vi.fn().mockResolvedValue(42),
updatePodcast: vi.fn().mockResolvedValue(undefined),
deletePodcast: vi.fn().mockResolvedValue(undefined),
getPodcastStats: vi.fn().mockResolvedValue({ total: 5, publies: 3, brouillons: 2, etablissements: 2 }),
getAllUsers: vi.fn().mockResolvedValue([]),
updateUserRole: vi.fn().mockResolvedValue(undefined),
upsertUser: vi.fn().mockResolvedValue(undefined),
getUserByOpenId: vi.fn().mockResolvedValue(undefined),
}));
function makePublicCtx(): TrpcContext {
return {
user: null,
req: { protocol: "https", headers: {} } as TrpcContext["req"],
res: { clearCookie: vi.fn() } as unknown as TrpcContext["res"],
};
}
function makeUserCtx(role: "user" | "admin" = "user"): TrpcContext {
return {
user: {
id: 1,
openId: "test-user",
name: "Test User",
email: "test@example.com",
loginMethod: "email",
role,
createdAt: new Date(),
updatedAt: new Date(),
lastSignedIn: new Date(),
},
req: { protocol: "https", headers: {} } as TrpcContext["req"],
res: { clearCookie: vi.fn() } as unknown as TrpcContext["res"],
};
}
// ─── Établissements ────────────────────────────────────────────────────────────
describe("etablissements.list", () => {
it("retourne la liste des établissements sans authentification", async () => {
const caller = appRouter.createCaller(makePublicCtx());
const result = await caller.etablissements.list();
expect(Array.isArray(result)).toBe(true);
expect(result.length).toBeGreaterThan(0);
expect(result[0]).toHaveProperty("nom");
});
});
describe("etablissements.create", () => {
it("refuse la création sans authentification admin", async () => {
const caller = appRouter.createCaller(makePublicCtx());
await expect(
caller.etablissements.create({ nom: "Test" })
).rejects.toThrow();
});
it("refuse la création pour un utilisateur standard", async () => {
const caller = appRouter.createCaller(makeUserCtx("user"));
await expect(
caller.etablissements.create({ nom: "Test" })
).rejects.toMatchObject({ code: "FORBIDDEN" });
});
it("permet la création pour un administrateur", async () => {
const caller = appRouter.createCaller(makeUserCtx("admin"));
await expect(
caller.etablissements.create({ nom: "Nouvel Établissement" })
).resolves.not.toThrow();
});
});
// ─── Mots-clés ─────────────────────────────────────────────────────────────────
describe("motsCles.list", () => {
it("retourne la liste des mots-clés publiquement", async () => {
const caller = appRouter.createCaller(makePublicCtx());
const result = await caller.motsCles.list();
expect(Array.isArray(result)).toBe(true);
expect(result.length).toBe(2);
expect(result[0]).toHaveProperty("label");
});
});
describe("motsCles.create", () => {
it("refuse la création sans rôle admin", async () => {
const caller = appRouter.createCaller(makeUserCtx("user"));
await expect(
caller.motsCles.create({ label: "Test" })
).rejects.toMatchObject({ code: "FORBIDDEN" });
});
});
// ─── Podcasts ──────────────────────────────────────────────────────────────────
describe("podcasts.list", () => {
it("retourne la liste des podcasts publiquement", async () => {
const caller = appRouter.createCaller(makePublicCtx());
const result = await caller.podcasts.list({});
expect(Array.isArray(result)).toBe(true);
expect(result[0]).toHaveProperty("titre");
expect(result[0]).toHaveProperty("motsCles");
});
it("accepte un filtre par établissement", async () => {
const caller = appRouter.createCaller(makePublicCtx());
const result = await caller.podcasts.list({ etablissementId: 1 });
expect(Array.isArray(result)).toBe(true);
});
it("accepte un filtre par statut", async () => {
const caller = appRouter.createCaller(makePublicCtx());
const result = await caller.podcasts.list({ statut: "publie" });
expect(Array.isArray(result)).toBe(true);
});
});
describe("podcasts.getById", () => {
it("retourne un podcast par son id", async () => {
const caller = appRouter.createCaller(makePublicCtx());
const result = await caller.podcasts.getById({ id: 1 });
expect(result).toHaveProperty("id", 1);
expect(result).toHaveProperty("titre", "Podcast Test");
});
});
describe("podcasts.create", () => {
it("refuse la création sans authentification", async () => {
const caller = appRouter.createCaller(makePublicCtx());
await expect(
caller.podcasts.create({
titre: "Test",
resume: "Résumé",
etablissementId: 1,
statut: "brouillon",
motCleIds: [],
})
).rejects.toThrow();
});
it("permet la création pour un utilisateur authentifié", async () => {
const caller = appRouter.createCaller(makeUserCtx("user"));
const result = await caller.podcasts.create({
titre: "Nouveau Podcast",
resume: "Un résumé complet",
etablissementId: 1,
statut: "brouillon",
motCleIds: [1],
});
expect(result).toBe(42);
});
});
describe("podcasts.delete", () => {
it("refuse la suppression pour un utilisateur non propriétaire", async () => {
const caller = appRouter.createCaller(makeUserCtx("user"));
// auteurId est 1, user.id est 1 → devrait réussir
await expect(
caller.podcasts.delete({ id: 1 })
).resolves.not.toThrow();
});
});
describe("podcasts.stats", () => {
it("retourne les statistiques pour un utilisateur authentifié", async () => {
const caller = appRouter.createCaller(makeUserCtx("user"));
const result = await caller.podcasts.stats();
expect(result).toHaveProperty("total");
expect(result).toHaveProperty("publies");
expect(result).toHaveProperty("brouillons");
expect(result).toHaveProperty("etablissements");
});
});
// ─── Auth ──────────────────────────────────────────────────────────────────────
describe("auth.me", () => {
it("retourne null pour un utilisateur non connecté", async () => {
const caller = appRouter.createCaller(makePublicCtx());
const result = await caller.auth.me();
expect(result).toBeNull();
});
it("retourne l'utilisateur connecté", async () => {
const caller = appRouter.createCaller(makeUserCtx("user"));
const result = await caller.auth.me();
expect(result).toHaveProperty("id", 1);
expect(result).toHaveProperty("role", "user");
});
});

342
server/routers.ts Normal file
View File

@@ -0,0 +1,342 @@
import { TRPCError } from "@trpc/server";
import { z } from "zod";
import { COOKIE_NAME } from "@shared/const";
import { getSessionCookieOptions } from "./_core/cookies";
import { systemRouter } from "./_core/systemRouter";
import { protectedProcedure, publicProcedure, router } from "./_core/trpc";
import {
createEtablissement,
createLocalUser,
createMotCle,
createPodcast,
deleteEtablissement,
deleteMotCle,
deletePodcast,
deleteUser,
getAllEtablissements,
getAllMotsCles,
getAllUsers,
getEtablissementById,
getPodcastById,
getPodcasts,
getPodcastStats,
getUserById,
getUserByUsername,
updateEtablissement,
updatePodcast,
updateUser,
updateUserRole,
} from "./db";
import { storagePut } from "./storage";
import { nanoid } from "nanoid";
import bcrypt from "bcryptjs";
import { sdk } from "./_core/sdk";
// ─── Admin guard ───────────────────────────────────────────────────────────────
const adminProcedure = protectedProcedure.use(({ ctx, next }) => {
if (ctx.user.role !== "admin") {
throw new TRPCError({ code: "FORBIDDEN", message: "Accès réservé aux administrateurs" });
}
return next({ ctx });
});
// ─── Établissements ────────────────────────────────────────────────────────────
const etablissementsRouter = router({
list: publicProcedure.query(() => getAllEtablissements()),
getById: publicProcedure
.input(z.object({ id: z.number() }))
.query(({ input }) => getEtablissementById(input.id)),
create: adminProcedure
.input(
z.object({
nom: z.string().min(1).max(255),
description: z.string().optional(),
logoUrl: z.string().optional(),
})
)
.mutation(({ input }) => createEtablissement(input)),
update: adminProcedure
.input(
z.object({
id: z.number(),
nom: z.string().min(1).max(255).optional(),
description: z.string().optional(),
logoUrl: z.string().optional(),
actif: z.boolean().optional(),
})
)
.mutation(({ input }) => {
const { id, ...data } = input;
return updateEtablissement(id, data);
}),
delete: adminProcedure
.input(z.object({ id: z.number() }))
.mutation(({ input }) => deleteEtablissement(input.id)),
});
// ─── Mots-clés ─────────────────────────────────────────────────────────────────
const motsClesRouter = router({
list: publicProcedure.query(() => getAllMotsCles()),
create: adminProcedure
.input(z.object({ label: z.string().min(1).max(100) }))
.mutation(({ input }) => createMotCle(input)),
delete: adminProcedure
.input(z.object({ id: z.number() }))
.mutation(({ input }) => deleteMotCle(input.id)),
});
// ─── Podcasts ──────────────────────────────────────────────────────────────────
const podcastsRouter = router({
list: publicProcedure
.input(
z.object({
etablissementId: z.number().optional(),
motCleIds: z.array(z.number()).optional(),
search: z.string().optional(),
statut: z.enum(["brouillon", "publie"]).optional(),
})
)
.query(({ input }) => getPodcasts(input)),
listMine: protectedProcedure
.query(({ ctx }) => getPodcasts({ auteurId: ctx.user.id })),
getById: publicProcedure
.input(z.object({ id: z.number() }))
.query(async ({ input }) => {
const podcast = await getPodcastById(input.id);
if (!podcast) throw new TRPCError({ code: "NOT_FOUND" });
return podcast;
}),
create: protectedProcedure
.input(
z.object({
titre: z.string().min(1).max(255),
resume: z.string().min(1),
etablissementId: z.number(),
audioUrl: z.string().optional(),
audioKey: z.string().optional(),
dureeSecondes: z.number().optional(),
statut: z.enum(["brouillon", "publie"]).default("brouillon"),
motCleIds: z.array(z.number()).default([]),
imageUrl: z.string().optional(),
})
)
.mutation(({ input, ctx }) => {
const { motCleIds, ...data } = input;
return createPodcast({ ...data, auteurId: ctx.user.id }, motCleIds);
}),
update: protectedProcedure
.input(
z.object({
id: z.number(),
titre: z.string().min(1).max(255).optional(),
resume: z.string().min(1).optional(),
etablissementId: z.number().optional(),
audioUrl: z.string().optional(),
audioKey: z.string().optional(),
dureeSecondes: z.number().optional(),
statut: z.enum(["brouillon", "publie"]).optional(),
motCleIds: z.array(z.number()).optional(),
imageUrl: z.string().optional(),
})
)
.mutation(async ({ input, ctx }) => {
const podcast = await getPodcastById(input.id);
if (!podcast) throw new TRPCError({ code: "NOT_FOUND" });
// Un utilisateur standard ne peut modifier que ses propres podcasts
if (ctx.user.role !== "admin" && podcast.auteurId !== ctx.user.id) {
throw new TRPCError({ code: "FORBIDDEN" });
}
const { id, motCleIds, ...data } = input;
return updatePodcast(id, data, motCleIds);
}),
delete: protectedProcedure
.input(z.object({ id: z.number() }))
.mutation(async ({ input, ctx }) => {
const podcast = await getPodcastById(input.id);
if (!podcast) throw new TRPCError({ code: "NOT_FOUND" });
if (ctx.user.role !== "admin" && podcast.auteurId !== ctx.user.id) {
throw new TRPCError({ code: "FORBIDDEN" });
}
return deletePodcast(input.id);
}),
stats: protectedProcedure.query(() => getPodcastStats()),
});
// ─── Upload audio ──────────────────────────────────────────────────────────────
const uploadRouter = router({
getAudioUploadUrl: protectedProcedure
.input(
z.object({
filename: z.string(),
contentType: z.string(),
sizeBytes: z.number().max(50 * 1024 * 1024, "Fichier trop volumineux (max 50 Mo)"),
})
)
.mutation(async ({ input }) => {
const ext = input.filename.split(".").pop() ?? "mp3";
const key = `podcasts/audio/${nanoid()}.${ext}`;
return { key, contentType: input.contentType };
}),
});
// ─── Users (admin) ─────────────────────────────────────────────────────────────
const usersRouter = router({
list: adminProcedure.query(() => getAllUsers()),
getById: adminProcedure
.input(z.object({ id: z.number() }))
.query(({ input }) => getUserById(input.id)),
create: adminProcedure
.input(
z.object({
username: z.string().min(2).max(64),
password: z.string().min(6),
name: z.string().min(1).max(255),
role: z.enum(["user", "admin"]),
})
)
.mutation(async ({ input }) => {
// Vérifier que le username n'existe pas déjà
const existing = await getUserByUsername(input.username);
if (existing) {
throw new TRPCError({ code: "CONFLICT", message: "Cet identifiant est déjà utilisé" });
}
const passwordHash = await bcrypt.hash(input.password, 10);
await createLocalUser({
openId: `local-${input.username}-${Date.now()}`,
username: input.username,
passwordHash,
name: input.name,
role: input.role,
immutable: false,
});
return { success: true };
}),
update: adminProcedure
.input(
z.object({
id: z.number(),
name: z.string().min(1).max(255).optional(),
username: z.string().min(2).max(64).optional(),
password: z.string().min(6).optional(),
role: z.enum(["user", "admin"]).optional(),
})
)
.mutation(async ({ input }) => {
const { id, password, ...rest } = input;
const updateData: Parameters<typeof updateUser>[1] = { ...rest };
if (password) {
updateData.passwordHash = await bcrypt.hash(password, 10);
}
// Vérifier unicité du username si changé
if (rest.username) {
const existing = await getUserByUsername(rest.username);
if (existing && existing.id !== id) {
throw new TRPCError({ code: "CONFLICT", message: "Cet identifiant est déjà utilisé" });
}
}
try {
await updateUser(id, updateData);
return { success: true };
} catch (e: any) {
throw new TRPCError({ code: "BAD_REQUEST", message: e.message });
}
}),
delete: adminProcedure
.input(z.object({ id: z.number() }))
.mutation(async ({ input, ctx }) => {
// Empêcher l'admin de se supprimer lui-même
if (ctx.user.id === input.id) {
throw new TRPCError({ code: "BAD_REQUEST", message: "Vous ne pouvez pas supprimer votre propre compte" });
}
try {
await deleteUser(input.id);
return { success: true };
} catch (e: any) {
throw new TRPCError({ code: "BAD_REQUEST", message: e.message });
}
}),
updateRole: adminProcedure
.input(z.object({ userId: z.number(), role: z.enum(["user", "admin"]) }))
.mutation(({ input }) => updateUserRole(input.userId, input.role)),
});
// ─── App router ────────────────────────────────────────────────────────────────
export const appRouter = router({
system: systemRouter,
auth: router({
me: publicProcedure.query((opts) => opts.ctx.user),
logout: publicProcedure.mutation(({ ctx }) => {
const cookieOptions = getSessionCookieOptions(ctx.req);
ctx.res.clearCookie(COOKIE_NAME, { ...cookieOptions, maxAge: -1 });
return { success: true } as const;
}),
/**
* Connexion locale par identifiant + mot de passe.
* Utilisé pour les comptes internes (ex: adminServPodcast).
*/
loginLocal: publicProcedure
.input(
z.object({
username: z.string().min(1),
password: z.string().min(1),
})
)
.mutation(async ({ input, ctx }) => {
const user = await getUserByUsername(input.username);
if (!user || !user.passwordHash) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "Identifiant ou mot de passe incorrect",
});
}
const valid = await bcrypt.compare(input.password, user.passwordHash);
if (!valid) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "Identifiant ou mot de passe incorrect",
});
}
// Créer une session JWT identique au flux OAuth
const token = await sdk.signSession({
openId: user.openId,
appId: "local",
name: user.name ?? user.username ?? "",
});
const cookieOptions = getSessionCookieOptions(ctx.req);
ctx.res.cookie(COOKIE_NAME, token, cookieOptions);
return { success: true, user } as const;
}),
}),
etablissements: etablissementsRouter,
motsCles: motsClesRouter,
podcasts: podcastsRouter,
upload: uploadRouter,
users: usersRouter,
});
export type AppRouter = typeof appRouter;

102
server/storage.ts Normal file
View File

@@ -0,0 +1,102 @@
// Preconfigured storage helpers for Manus WebDev templates
// Uses the Biz-provided storage proxy (Authorization: Bearer <token>)
import { ENV } from './_core/env';
type StorageConfig = { baseUrl: string; apiKey: string };
function getStorageConfig(): StorageConfig {
const baseUrl = ENV.forgeApiUrl;
const apiKey = ENV.forgeApiKey;
if (!baseUrl || !apiKey) {
throw new Error(
"Storage proxy credentials missing: set BUILT_IN_FORGE_API_URL and BUILT_IN_FORGE_API_KEY"
);
}
return { baseUrl: baseUrl.replace(/\/+$/, ""), apiKey };
}
function buildUploadUrl(baseUrl: string, relKey: string): URL {
const url = new URL("v1/storage/upload", ensureTrailingSlash(baseUrl));
url.searchParams.set("path", normalizeKey(relKey));
return url;
}
async function buildDownloadUrl(
baseUrl: string,
relKey: string,
apiKey: string
): Promise<string> {
const downloadApiUrl = new URL(
"v1/storage/downloadUrl",
ensureTrailingSlash(baseUrl)
);
downloadApiUrl.searchParams.set("path", normalizeKey(relKey));
const response = await fetch(downloadApiUrl, {
method: "GET",
headers: buildAuthHeaders(apiKey),
});
return (await response.json()).url;
}
function ensureTrailingSlash(value: string): string {
return value.endsWith("/") ? value : `${value}/`;
}
function normalizeKey(relKey: string): string {
return relKey.replace(/^\/+/, "");
}
function toFormData(
data: Buffer | Uint8Array | string,
contentType: string,
fileName: string
): FormData {
const blob =
typeof data === "string"
? new Blob([data], { type: contentType })
: new Blob([data as any], { type: contentType });
const form = new FormData();
form.append("file", blob, fileName || "file");
return form;
}
function buildAuthHeaders(apiKey: string): HeadersInit {
return { Authorization: `Bearer ${apiKey}` };
}
export async function storagePut(
relKey: string,
data: Buffer | Uint8Array | string,
contentType = "application/octet-stream"
): Promise<{ key: string; url: string }> {
const { baseUrl, apiKey } = getStorageConfig();
const key = normalizeKey(relKey);
const uploadUrl = buildUploadUrl(baseUrl, key);
const formData = toFormData(data, contentType, key.split("/").pop() ?? key);
const response = await fetch(uploadUrl, {
method: "POST",
headers: buildAuthHeaders(apiKey),
body: formData,
});
if (!response.ok) {
const message = await response.text().catch(() => response.statusText);
throw new Error(
`Storage upload failed (${response.status} ${response.statusText}): ${message}`
);
}
const url = (await response.json()).url;
return { key, url };
}
export async function storageGet(relKey: string): Promise<{ key: string; url: string; }> {
const { baseUrl, apiKey } = getStorageConfig();
const key = normalizeKey(relKey);
return {
key,
url: await buildDownloadUrl(baseUrl, key, apiKey),
};
}