Checkpoint: Migration complète vers authentification locale (JWT + bcrypt) : schéma DB (10 tables), routes tRPC (auth, users, etablissements, inventaire, capex, opex, parametres), page de login avec branding Itinova/Santinova, protection des routes, onglets Établissements et Utilisateurs branchés sur tRPC, import inventaire/établissements/utilisateurs via tRPC, 14 tests Vitest passants.
This commit is contained in:
28
server/_core/context.ts
Normal file
28
server/_core/context.ts
Normal 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
48
server/_core/cookies.ts
Normal 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
64
server/_core/dataApi.ts
Normal 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
10
server/_core/env.ts
Normal 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 ?? "",
|
||||
};
|
||||
213
server/_core/heartbeat.ts
Normal file
213
server/_core/heartbeat.ts
Normal file
@@ -0,0 +1,213 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { ENV } from "./env";
|
||||
|
||||
export type HeartbeatJob = {
|
||||
name: string;
|
||||
/**
|
||||
* 6-field cron with seconds (`sec min hour dom mon dow`), UTC, min interval 60s.
|
||||
* Use `0` for the seconds field — e.g. `"0 0 9 * * *"` is daily 09:00 UTC.
|
||||
* See periodic-updates.md.
|
||||
*/
|
||||
cron: string;
|
||||
/** Callback path. MUST start with `/api/scheduled/`. */
|
||||
path: string;
|
||||
method?: "POST" | "PUT";
|
||||
payload?: unknown;
|
||||
description?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Update patch. All fields optional; unset = leave unchanged.
|
||||
* `enable`: true = resume, false = pause; omit = unchanged.
|
||||
* `name` is the (project, owner)-scope key and cannot be changed.
|
||||
*/
|
||||
export type HeartbeatJobUpdate = Partial<Omit<HeartbeatJob, "name">> & {
|
||||
enable?: boolean;
|
||||
};
|
||||
|
||||
export type HeartbeatJobInfo = {
|
||||
taskUid: string;
|
||||
name: string;
|
||||
userId: string;
|
||||
description: string;
|
||||
cronExpression: string;
|
||||
callbackPath: string;
|
||||
callbackMethod: string;
|
||||
callbackPayload: string;
|
||||
isEnable: boolean;
|
||||
createdAt?: string | null;
|
||||
lastExecutedAt?: string | null;
|
||||
nextExecutionAt?: string | null;
|
||||
};
|
||||
|
||||
const SERVICE = "webdevtoken.v1.WebDevService";
|
||||
|
||||
const buildEndpoint = (rpc: string): string => {
|
||||
if (!ENV.forgeApiUrl) {
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "Heartbeat service URL is not configured (BUILT_IN_FORGE_API_URL).",
|
||||
});
|
||||
}
|
||||
if (!ENV.forgeApiKey) {
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "Heartbeat service API key is not configured (BUILT_IN_FORGE_API_KEY).",
|
||||
});
|
||||
}
|
||||
const baseUrl = ENV.forgeApiUrl;
|
||||
const normalizedBase = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
|
||||
return new URL(`${SERVICE}/${rpc}`, normalizedBase).toString();
|
||||
};
|
||||
|
||||
const callForge = async <T>(
|
||||
rpc: string,
|
||||
body: Record<string, unknown>,
|
||||
userSession: string
|
||||
): Promise<T> => {
|
||||
const endpoint = buildEndpoint(rpc);
|
||||
const headers: Record<string, string> = {
|
||||
accept: "application/json",
|
||||
authorization: `Bearer ${ENV.forgeApiKey}`,
|
||||
"content-type": "application/json",
|
||||
"connect-protocol-version": "1",
|
||||
};
|
||||
// userSession is the decoded `app_session_id` cookie value (NOT the raw
|
||||
// Cookie header). Empty string falls back to the project owner identity.
|
||||
if (userSession) {
|
||||
headers["x-manus-user-session"] = userSession;
|
||||
}
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(endpoint, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
} catch (error) {
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: `Heartbeat ${rpc} network error: ${String(error)}`,
|
||||
});
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const detail = await response.text().catch(() => "");
|
||||
throw mapForgeError(response, detail, rpc);
|
||||
}
|
||||
return (await response.json()) as T;
|
||||
};
|
||||
|
||||
const mapForgeError = (
|
||||
response: Response,
|
||||
detail: string,
|
||||
rpc: string
|
||||
): TRPCError => {
|
||||
const status = response.status;
|
||||
let code: TRPCError["code"] = "INTERNAL_SERVER_ERROR";
|
||||
if (status === 401) code = "UNAUTHORIZED";
|
||||
else if (status === 403) code = "FORBIDDEN";
|
||||
else if (status === 404) code = "NOT_FOUND";
|
||||
else if (status === 400 || status === 422) code = "BAD_REQUEST";
|
||||
else if (status === 409) code = "CONFLICT";
|
||||
else if (status === 429) code = "TOO_MANY_REQUESTS";
|
||||
return new TRPCError({
|
||||
code,
|
||||
message: `Heartbeat ${rpc} failed (${status})${detail ? `: ${detail}` : ""}`,
|
||||
});
|
||||
};
|
||||
|
||||
const stringifyPayload = (payload: unknown): string => {
|
||||
if (payload === undefined || payload === null) return "{}";
|
||||
if (typeof payload === "string") return payload;
|
||||
return JSON.stringify(payload);
|
||||
};
|
||||
|
||||
const validateCallbackPath = (path: string): void => {
|
||||
if (!path || !path.startsWith("/api/scheduled/")) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "callback path must start with /api/scheduled/",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Create a new HTTP cron job. Returns the assigned `taskUid` to persist on
|
||||
* your business row so callbacks can dereference it.
|
||||
*/
|
||||
export async function createHeartbeatJob(
|
||||
job: HeartbeatJob,
|
||||
userSession: string
|
||||
): Promise<{ taskUid: string; nextExecutionAt?: string | null }> {
|
||||
validateCallbackPath(job.path);
|
||||
return callForge<{ taskUid: string; nextExecutionAt?: string | null }>(
|
||||
"CreateHeartbeatJob",
|
||||
{
|
||||
name: job.name,
|
||||
cronExpression: job.cron,
|
||||
callbackPath: job.path,
|
||||
callbackMethod: job.method ?? "POST",
|
||||
callbackPayload: stringifyPayload(job.payload),
|
||||
description: job.description ?? "",
|
||||
},
|
||||
userSession
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an existing cron located by `taskUid`. Only fields you pass in
|
||||
* `patch` are mutated. `enable` flips resume/pause; omit to leave alone.
|
||||
*/
|
||||
export async function updateHeartbeatJob(
|
||||
taskUid: string,
|
||||
patch: HeartbeatJobUpdate,
|
||||
userSession: string
|
||||
): Promise<{ nextExecutionAt?: string | null }> {
|
||||
if (patch.path !== undefined) validateCallbackPath(patch.path);
|
||||
const body: Record<string, unknown> = { taskUid };
|
||||
if (patch.cron !== undefined) body.cronExpression = patch.cron;
|
||||
if (patch.path !== undefined) body.callbackPath = patch.path;
|
||||
if (patch.method !== undefined) body.callbackMethod = patch.method;
|
||||
if (patch.payload !== undefined) {
|
||||
body.callbackPayload = stringifyPayload(patch.payload);
|
||||
}
|
||||
if (patch.description !== undefined) body.description = patch.description;
|
||||
if (patch.enable !== undefined) body.enable = patch.enable;
|
||||
return callForge<{ nextExecutionAt?: string | null }>(
|
||||
"UpdateHeartbeatJob",
|
||||
body,
|
||||
userSession
|
||||
);
|
||||
}
|
||||
|
||||
/** Delete a cron located by `taskUid`. Idempotent on caller side. */
|
||||
export async function deleteHeartbeatJob(
|
||||
taskUid: string,
|
||||
userSession: string
|
||||
): Promise<void> {
|
||||
await callForge("DeleteHeartbeatJob", { taskUid }, userSession);
|
||||
}
|
||||
|
||||
/**
|
||||
* List cron jobs owned by the resolved actor (end-user when `userSession`
|
||||
* is set, project owner otherwise) within the current project.
|
||||
*
|
||||
* `actorUserId` in the response echoes whose cron list you got back. End-users
|
||||
* cannot list other users' crons via this SDK; cross-user inspection is
|
||||
* owner-only via the sandbox CLI (`manus-heartbeat list --user-id <uid>`).
|
||||
*/
|
||||
export async function listHeartbeatJobs(
|
||||
userSession: string,
|
||||
pagination?: { page?: number; pageSize?: number }
|
||||
): Promise<{ total: number; actorUserId: string; jobs: HeartbeatJobInfo[] }> {
|
||||
const body: Record<string, unknown> = {};
|
||||
if (pagination?.page !== undefined) body.page = pagination.page;
|
||||
if (pagination?.pageSize !== undefined) body.pageSize = pagination.pageSize;
|
||||
return callForge<{
|
||||
total: number;
|
||||
actorUserId: string;
|
||||
jobs: HeartbeatJobInfo[];
|
||||
}>("ListHeartbeatJobs", body, userSession);
|
||||
}
|
||||
92
server/_core/imageGeneration.ts
Normal file
92
server/_core/imageGeneration.ts
Normal 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,
|
||||
};
|
||||
}
|
||||
66
server/_core/index.ts
Normal file
66
server/_core/index.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
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 { registerStorageProxy } from "./storageProxy";
|
||||
import { appRouter } from "../routers";
|
||||
import { createContext } from "./context";
|
||||
import { serveStatic, setupVite } from "./vite";
|
||||
|
||||
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);
|
||||
// Configure body parser with larger size limit for file uploads
|
||||
app.use(express.json({ limit: "50mb" }));
|
||||
app.use(express.urlencoded({ limit: "50mb", extended: true }));
|
||||
registerStorageProxy(app);
|
||||
registerOAuthRoutes(app);
|
||||
// tRPC API
|
||||
app.use(
|
||||
"/api/trpc",
|
||||
createExpressMiddleware({
|
||||
router: appRouter,
|
||||
createContext,
|
||||
})
|
||||
);
|
||||
// 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}/`);
|
||||
});
|
||||
}
|
||||
|
||||
startServer().catch(console.error);
|
||||
383
server/_core/llm.ts
Normal file
383
server/_core/llm.ts
Normal file
@@ -0,0 +1,383 @@
|
||||
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;
|
||||
model?: string;
|
||||
thinking?: Record<string, unknown>;
|
||||
reasoning?: Record<string, unknown>;
|
||||
};
|
||||
|
||||
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,
|
||||
model,
|
||||
thinking,
|
||||
reasoning,
|
||||
maxTokens,
|
||||
max_tokens,
|
||||
} = params;
|
||||
|
||||
const payload: Record<string, unknown> = {
|
||||
messages: messages.map(normalizeMessage),
|
||||
};
|
||||
|
||||
if (model) {
|
||||
payload.model = model;
|
||||
}
|
||||
|
||||
if (tools && tools.length > 0) {
|
||||
payload.tools = tools;
|
||||
}
|
||||
|
||||
const normalizedToolChoice = normalizeToolChoice(
|
||||
toolChoice || tool_choice,
|
||||
tools
|
||||
);
|
||||
if (normalizedToolChoice) {
|
||||
payload.tool_choice = normalizedToolChoice;
|
||||
}
|
||||
|
||||
const resolvedMaxTokens = max_tokens ?? maxTokens;
|
||||
if (typeof resolvedMaxTokens === "number") {
|
||||
payload.max_tokens = resolvedMaxTokens;
|
||||
}
|
||||
|
||||
if (thinking) {
|
||||
payload.thinking = thinking;
|
||||
}
|
||||
if (reasoning) {
|
||||
payload.reasoning = reasoning;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
export type ModelInfo = {
|
||||
id: string;
|
||||
object: string;
|
||||
created: number;
|
||||
owned_by: string;
|
||||
};
|
||||
|
||||
export type ModelsResponse = {
|
||||
object: string;
|
||||
data: ModelInfo[];
|
||||
};
|
||||
|
||||
export async function listLLMModels(): Promise<ModelsResponse> {
|
||||
assertApiKey();
|
||||
|
||||
const url = ENV.forgeApiUrl && ENV.forgeApiUrl.trim().length > 0
|
||||
? `${ENV.forgeApiUrl.replace(/\/$/, "")}/v1/models`
|
||||
: "https://forge.manus.im/v1/models";
|
||||
|
||||
const response = await fetch(url, {
|
||||
headers: { authorization: `Bearer ${ENV.forgeApiKey}` },
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(
|
||||
`List LLM models failed: ${response.status} ${response.statusText} – ${errorText}`
|
||||
);
|
||||
}
|
||||
|
||||
return (await response.json()) as ModelsResponse;
|
||||
}
|
||||
319
server/_core/map.ts
Normal file
319
server/_core/map.ts
Normal 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
|
||||
*/
|
||||
|
||||
|
||||
|
||||
|
||||
114
server/_core/notification.ts
Normal file
114
server/_core/notification.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
19
server/_core/oauth.ts
Normal file
19
server/_core/oauth.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* Routes d'authentification locale Itinova.
|
||||
* Le flow Manus OAuth est désactivé — on utilise email/password + JWT local.
|
||||
*/
|
||||
import { COOKIE_NAME, ONE_YEAR_MS } from "@shared/const";
|
||||
import type { Express, Request, Response } from "express";
|
||||
import { getSessionCookieOptions } from "./cookies";
|
||||
|
||||
/**
|
||||
* Enregistre les routes d'auth locale.
|
||||
* Le vrai endpoint de login est géré via tRPC (auth.login).
|
||||
* Cette fonction est conservée pour compatibilité avec le framework.
|
||||
*/
|
||||
export function registerOAuthRoutes(app: Express) {
|
||||
// Route de callback Manus OAuth désactivée — auth locale uniquement
|
||||
app.get("/api/oauth/callback", (_req: Request, res: Response) => {
|
||||
res.redirect(302, "/login");
|
||||
});
|
||||
}
|
||||
98
server/_core/sdk.ts
Normal file
98
server/_core/sdk.ts
Normal file
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* SDK Server — Auth locale Itinova
|
||||
* Remplace le flow Manus OAuth par une authentification locale email/password + JWT.
|
||||
* Le cookie de session contient un JWT signé avec JWT_SECRET.
|
||||
*/
|
||||
import { COOKIE_NAME, ONE_YEAR_MS } from "@shared/const";
|
||||
import { ForbiddenError } from "@shared/_core/errors";
|
||||
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";
|
||||
|
||||
const isNonEmptyString = (value: unknown): value is string =>
|
||||
typeof value === "string" && value.length > 0;
|
||||
|
||||
export type SessionPayload = {
|
||||
userId: number;
|
||||
login: string;
|
||||
role: string;
|
||||
};
|
||||
|
||||
/** Result of `sdk.authenticateRequest`. */
|
||||
export type AuthenticatedUser = User & {
|
||||
taskUid?: string;
|
||||
isCron?: boolean;
|
||||
};
|
||||
|
||||
class SDKServer {
|
||||
private getSessionSecret() {
|
||||
const secret = ENV.cookieSecret;
|
||||
return new TextEncoder().encode(secret);
|
||||
}
|
||||
|
||||
async createSessionToken(
|
||||
userId: number,
|
||||
login: string,
|
||||
role: string,
|
||||
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({ userId, login, role })
|
||||
.setProtectedHeader({ alg: "HS256", typ: "JWT" })
|
||||
.setExpirationTime(expirationSeconds)
|
||||
.sign(secretKey);
|
||||
}
|
||||
|
||||
async verifySession(
|
||||
cookieValue: string | undefined | null
|
||||
): Promise<SessionPayload | null> {
|
||||
if (!cookieValue) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const secretKey = this.getSessionSecret();
|
||||
const { payload } = await jwtVerify(cookieValue, secretKey, {
|
||||
algorithms: ["HS256"],
|
||||
});
|
||||
const { userId, login, role } = payload as Record<string, unknown>;
|
||||
if (!userId || !isNonEmptyString(login) || !isNonEmptyString(role)) {
|
||||
return null;
|
||||
}
|
||||
return { userId: userId as number, login, role };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private parseCookies(cookieHeader: string | undefined) {
|
||||
if (!cookieHeader) return new Map<string, string>();
|
||||
const parsed = parseCookieHeader(cookieHeader);
|
||||
return new Map(Object.entries(parsed));
|
||||
}
|
||||
|
||||
async authenticateRequest(req: Request): Promise<AuthenticatedUser> {
|
||||
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");
|
||||
}
|
||||
|
||||
const user = await db.getUserById(session.userId);
|
||||
if (!user || !user.isActive) {
|
||||
throw ForbiddenError("User not found or inactive");
|
||||
}
|
||||
|
||||
return user as AuthenticatedUser;
|
||||
}
|
||||
}
|
||||
|
||||
export const sdk = new SDKServer();
|
||||
48
server/_core/storageProxy.ts
Normal file
48
server/_core/storageProxy.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import type { Express } from "express";
|
||||
import { ENV } from "./env";
|
||||
|
||||
export function registerStorageProxy(app: Express) {
|
||||
app.get("/manus-storage/*", async (req, res) => {
|
||||
const key = (req.params as Record<string, string>)[0];
|
||||
if (!key) {
|
||||
res.status(400).send("Missing storage key");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!ENV.forgeApiUrl || !ENV.forgeApiKey) {
|
||||
res.status(500).send("Storage proxy not configured");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const forgeUrl = new URL(
|
||||
"v1/storage/presign/get",
|
||||
ENV.forgeApiUrl.replace(/\/+$/, "") + "/",
|
||||
);
|
||||
forgeUrl.searchParams.set("path", key);
|
||||
|
||||
const forgeResp = await fetch(forgeUrl, {
|
||||
headers: { Authorization: `Bearer ${ENV.forgeApiKey}` },
|
||||
});
|
||||
|
||||
if (!forgeResp.ok) {
|
||||
const body = await forgeResp.text().catch(() => "");
|
||||
console.error(`[StorageProxy] forge error: ${forgeResp.status} ${body}`);
|
||||
res.status(502).send("Storage backend error");
|
||||
return;
|
||||
}
|
||||
|
||||
const { url } = (await forgeResp.json()) as { url: string };
|
||||
if (!url) {
|
||||
res.status(502).send("Empty signed URL from backend");
|
||||
return;
|
||||
}
|
||||
|
||||
res.set("Cache-Control", "no-store");
|
||||
res.redirect(307, url);
|
||||
} catch (err) {
|
||||
console.error("[StorageProxy] failed:", err);
|
||||
res.status(502).send("Storage proxy error");
|
||||
}
|
||||
});
|
||||
}
|
||||
29
server/_core/systemRouter.ts
Normal file
29
server/_core/systemRouter.ts
Normal 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
45
server/_core/trpc.ts
Normal 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
6
server/_core/types/cookie.d.ts
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
declare module "cookie" {
|
||||
export function parse(
|
||||
str: string,
|
||||
options?: Record<string, unknown>
|
||||
): Record<string, string>;
|
||||
}
|
||||
71
server/_core/types/manusTypes.ts
Normal file
71
server/_core/types/manusTypes.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
// 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;
|
||||
/** Cron-only; references `schedule_task.uid`. */
|
||||
taskUid?: string | null;
|
||||
}
|
||||
67
server/_core/vite.ts
Normal file
67
server/_core/vite.ts
Normal 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"));
|
||||
});
|
||||
}
|
||||
284
server/_core/voiceTranscription.ts
Normal file
284
server/_core/voiceTranscription.ts
Normal 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;
|
||||
* }),
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
270
server/auth.local.test.ts
Normal file
270
server/auth.local.test.ts
Normal file
@@ -0,0 +1,270 @@
|
||||
/**
|
||||
* Tests Vitest — Authentification locale Itinova Budget SI
|
||||
* Couvre : login, logout, me, users.create, etablissements.list
|
||||
*/
|
||||
import { describe, expect, it, vi, beforeEach } from "vitest";
|
||||
import { appRouter } from "./routers";
|
||||
import { COOKIE_NAME } from "../shared/const";
|
||||
import type { TrpcContext } from "./_core/context";
|
||||
import type { User } from "../drizzle/schema";
|
||||
|
||||
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
function makeUser(overrides: Partial<User> = {}): User {
|
||||
return {
|
||||
id: 1,
|
||||
login: "admin",
|
||||
email: "admin@itinova.fr",
|
||||
passwordHash: "$2a$10$hashedpassword",
|
||||
firstName: "Admin",
|
||||
lastName: "Itinova",
|
||||
role: "admin",
|
||||
isActive: true,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
lastSignedIn: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
type CookieCall = { name: string; options: Record<string, unknown> };
|
||||
|
||||
function createPublicCtx(): { ctx: TrpcContext; setCookies: CookieCall[]; clearedCookies: CookieCall[] } {
|
||||
const setCookies: CookieCall[] = [];
|
||||
const clearedCookies: CookieCall[] = [];
|
||||
const ctx: TrpcContext = {
|
||||
user: null,
|
||||
req: { protocol: "https", headers: {} } as TrpcContext["req"],
|
||||
res: {
|
||||
cookie: (name: string, _val: string, options: Record<string, unknown>) => setCookies.push({ name, options }),
|
||||
clearCookie: (name: string, options: Record<string, unknown>) => clearedCookies.push({ name, options }),
|
||||
} as unknown as TrpcContext["res"],
|
||||
};
|
||||
return { ctx, setCookies, clearedCookies };
|
||||
}
|
||||
|
||||
function createAuthCtx(userOverrides: Partial<User> = {}): { ctx: TrpcContext; clearedCookies: CookieCall[] } {
|
||||
const clearedCookies: CookieCall[] = [];
|
||||
const ctx: TrpcContext = {
|
||||
user: makeUser(userOverrides),
|
||||
req: { protocol: "https", headers: {} } as TrpcContext["req"],
|
||||
res: {
|
||||
cookie: () => {},
|
||||
clearCookie: (name: string, options: Record<string, unknown>) => clearedCookies.push({ name, options }),
|
||||
} as unknown as TrpcContext["res"],
|
||||
};
|
||||
return { ctx, clearedCookies };
|
||||
}
|
||||
|
||||
// ─── Mock db ─────────────────────────────────────────────────────────────────
|
||||
|
||||
vi.mock("./db", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("./db")>();
|
||||
return {
|
||||
...actual,
|
||||
getUserByLogin: vi.fn(),
|
||||
updateLastSignedIn: vi.fn(),
|
||||
createUser: vi.fn(),
|
||||
listUsers: vi.fn(),
|
||||
listEtablissements: vi.fn(),
|
||||
getParametres: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("./_core/sdk", () => ({
|
||||
sdk: {
|
||||
createSessionToken: vi.fn().mockResolvedValue("mock-jwt-token"),
|
||||
authenticateRequest: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
// ─── Tests auth.logout ────────────────────────────────────────────────────────
|
||||
|
||||
describe("auth.logout", () => {
|
||||
it("efface le cookie de session et retourne success:true", async () => {
|
||||
const { ctx, clearedCookies } = createAuthCtx();
|
||||
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,
|
||||
httpOnly: true,
|
||||
path: "/",
|
||||
});
|
||||
});
|
||||
|
||||
it("fonctionne aussi sans utilisateur connecté (public procedure)", async () => {
|
||||
const { ctx, clearedCookies } = createPublicCtx();
|
||||
const caller = appRouter.createCaller(ctx);
|
||||
|
||||
const result = await caller.auth.logout();
|
||||
|
||||
expect(result).toEqual({ success: true });
|
||||
expect(clearedCookies).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Tests auth.me ────────────────────────────────────────────────────────────
|
||||
|
||||
describe("auth.me", () => {
|
||||
it("retourne null si non authentifié", async () => {
|
||||
const { ctx } = createPublicCtx();
|
||||
const caller = appRouter.createCaller(ctx);
|
||||
|
||||
const result = await caller.auth.me();
|
||||
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("retourne les infos utilisateur si authentifié", async () => {
|
||||
const { ctx } = createAuthCtx({ login: "jdupont", email: "j.dupont@itinova.fr", role: "standard" });
|
||||
const caller = appRouter.createCaller(ctx);
|
||||
|
||||
const result = await caller.auth.me();
|
||||
|
||||
expect(result).not.toBeNull();
|
||||
expect(result?.login).toBe("jdupont");
|
||||
expect(result?.email).toBe("j.dupont@itinova.fr");
|
||||
expect(result?.role).toBe("standard");
|
||||
});
|
||||
|
||||
it("ne retourne pas le hash du mot de passe", async () => {
|
||||
const { ctx } = createAuthCtx();
|
||||
const caller = appRouter.createCaller(ctx);
|
||||
|
||||
const result = await caller.auth.me();
|
||||
|
||||
expect(result).not.toHaveProperty("passwordHash");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Tests auth.login ────────────────────────────────────────────────────────
|
||||
|
||||
describe("auth.login", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("refuse un login avec identifiants invalides (utilisateur inexistant)", async () => {
|
||||
const { db } = await import("./db").then(m => ({ db: m }));
|
||||
(db.getUserByLogin as ReturnType<typeof vi.fn>).mockResolvedValue(null);
|
||||
|
||||
const { ctx } = createPublicCtx();
|
||||
const caller = appRouter.createCaller(ctx);
|
||||
|
||||
await expect(caller.auth.login({ login: "inexistant", password: "mauvais" }))
|
||||
.rejects.toThrow("Identifiants invalides");
|
||||
});
|
||||
|
||||
it("refuse un compte inactif", async () => {
|
||||
const { db } = await import("./db").then(m => ({ db: m }));
|
||||
(db.getUserByLogin as ReturnType<typeof vi.fn>).mockResolvedValue(
|
||||
makeUser({ isActive: false })
|
||||
);
|
||||
|
||||
const { ctx } = createPublicCtx();
|
||||
const caller = appRouter.createCaller(ctx);
|
||||
|
||||
await expect(caller.auth.login({ login: "admin", password: "password" }))
|
||||
.rejects.toThrow("Identifiants invalides");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Tests etablissements.list ────────────────────────────────────────────────
|
||||
|
||||
describe("etablissements.list", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("retourne la liste des établissements pour un utilisateur connecté", async () => {
|
||||
const { db } = await import("./db").then(m => ({ db: m }));
|
||||
const mockEtabs = [
|
||||
{ id: 1, code: "ETB001", nom: "EHPAD Les Pins", groupe: "Itinova", ville: "Lyon", actif: true, createdAt: new Date(), updatedAt: new Date() },
|
||||
{ id: 2, code: "ETB002", nom: "Résidence Soleil", groupe: "Itinova", ville: "Grenoble", actif: true, createdAt: new Date(), updatedAt: new Date() },
|
||||
];
|
||||
(db.listEtablissements as ReturnType<typeof vi.fn>).mockResolvedValue(mockEtabs);
|
||||
|
||||
const { ctx } = createAuthCtx();
|
||||
const caller = appRouter.createCaller(ctx);
|
||||
|
||||
const result = await caller.etablissements.list();
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result[0]?.code).toBe("ETB001");
|
||||
expect(result[1]?.code).toBe("ETB002");
|
||||
});
|
||||
|
||||
it("lève une erreur UNAUTHORIZED si non authentifié", async () => {
|
||||
const { ctx } = createPublicCtx();
|
||||
const caller = appRouter.createCaller(ctx);
|
||||
|
||||
await expect(caller.etablissements.list()).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Tests users.list (admin only) ───────────────────────────────────────────
|
||||
|
||||
describe("users.list", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("retourne la liste des utilisateurs pour un admin", async () => {
|
||||
const { db } = await import("./db").then(m => ({ db: m }));
|
||||
const mockUsers = [
|
||||
makeUser({ id: 1, login: "admin", role: "admin" }),
|
||||
makeUser({ id: 2, login: "jdupont", role: "standard" }),
|
||||
];
|
||||
(db.listUsers as ReturnType<typeof vi.fn>).mockResolvedValue(mockUsers);
|
||||
|
||||
const { ctx } = createAuthCtx({ role: "admin" });
|
||||
const caller = appRouter.createCaller(ctx);
|
||||
|
||||
const result = await caller.users.list();
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result[0]?.role).toBe("admin");
|
||||
});
|
||||
|
||||
it("lève FORBIDDEN pour un utilisateur standard", async () => {
|
||||
const { ctx } = createAuthCtx({ role: "standard" });
|
||||
const caller = appRouter.createCaller(ctx);
|
||||
|
||||
await expect(caller.users.list()).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("lève FORBIDDEN pour un utilisateur readonly", async () => {
|
||||
const { ctx } = createAuthCtx({ role: "readonly" });
|
||||
const caller = appRouter.createCaller(ctx);
|
||||
|
||||
await expect(caller.users.list()).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Tests parametres.get ─────────────────────────────────────────────────────
|
||||
|
||||
describe("parametres.get", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("retourne les paramètres sous forme d'objet clé-valeur", async () => {
|
||||
const { db } = await import("./db").then(m => ({ db: m }));
|
||||
(db.getParametres as ReturnType<typeof vi.fn>).mockResolvedValue([
|
||||
{ id: 1, cle: "seuil_fixes_ans", valeur: "5", updatedAt: new Date() },
|
||||
{ id: 2, cle: "cout_fixe", valeur: "850", updatedAt: new Date() },
|
||||
]);
|
||||
|
||||
const { ctx } = createAuthCtx();
|
||||
const caller = appRouter.createCaller(ctx);
|
||||
|
||||
const result = await caller.parametres.get();
|
||||
|
||||
expect(result).toEqual({ seuil_fixes_ans: "5", cout_fixe: "850" });
|
||||
});
|
||||
});
|
||||
63
server/auth.logout.test.ts
Normal file
63
server/auth.logout.test.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { appRouter } from "./routers";
|
||||
import { COOKIE_NAME } from "../shared/const";
|
||||
import type { TrpcContext } from "./_core/context";
|
||||
import type { User } from "../drizzle/schema";
|
||||
|
||||
type CookieCall = {
|
||||
name: string;
|
||||
options: Record<string, unknown>;
|
||||
};
|
||||
|
||||
function createAuthContext(): { ctx: TrpcContext; clearedCookies: CookieCall[] } {
|
||||
const clearedCookies: CookieCall[] = [];
|
||||
|
||||
const user: User = {
|
||||
id: 1,
|
||||
login: "admin",
|
||||
email: "admin@itinova.fr",
|
||||
passwordHash: "$2a$10$hashedpassword",
|
||||
firstName: "Admin",
|
||||
lastName: "Itinova",
|
||||
role: "admin",
|
||||
isActive: true,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
lastSignedIn: null,
|
||||
};
|
||||
|
||||
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: "/",
|
||||
});
|
||||
});
|
||||
});
|
||||
310
server/db.ts
Normal file
310
server/db.ts
Normal file
@@ -0,0 +1,310 @@
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { drizzle } from "drizzle-orm/mysql2";
|
||||
import {
|
||||
capexLignes,
|
||||
etablissements,
|
||||
InsertCapexLigne,
|
||||
InsertEtablissement,
|
||||
InsertOpexMontantEtab,
|
||||
InsertOpexPoste,
|
||||
InsertUser,
|
||||
inventaireMeta,
|
||||
inventairePostes,
|
||||
opexMontantsEtab,
|
||||
opexPostes,
|
||||
opexValidated,
|
||||
parametresApp,
|
||||
userEtablissements,
|
||||
users,
|
||||
} from "../drizzle/schema";
|
||||
|
||||
let _db: ReturnType<typeof drizzle> | null = null;
|
||||
|
||||
// Lazily create the drizzle instance so local tooling can run without a DB.
|
||||
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 getUserByLogin(login: string) {
|
||||
const db = await getDb();
|
||||
if (!db) return undefined;
|
||||
const result = await db
|
||||
.select()
|
||||
.from(users)
|
||||
.where(eq(users.login, login))
|
||||
.limit(1);
|
||||
return result.length > 0 ? result[0] : undefined;
|
||||
}
|
||||
|
||||
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.length > 0 ? result[0] : undefined;
|
||||
}
|
||||
|
||||
export async function createUser(user: InsertUser) {
|
||||
const db = await getDb();
|
||||
if (!db) throw new Error("Database not available");
|
||||
const [result] = await db.insert(users).values(user);
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function updateUser(id: number, data: Partial<InsertUser>) {
|
||||
const db = await getDb();
|
||||
if (!db) throw new Error("Database not available");
|
||||
await db.update(users).set(data).where(eq(users.id, id));
|
||||
}
|
||||
|
||||
export async function listUsers() {
|
||||
const db = await getDb();
|
||||
if (!db) return [];
|
||||
return db.select().from(users);
|
||||
}
|
||||
|
||||
export async function deleteUser(id: number) {
|
||||
const db = await getDb();
|
||||
if (!db) throw new Error("Database not available");
|
||||
await db.delete(users).where(eq(users.id, id));
|
||||
}
|
||||
|
||||
export async function updateLastSignedIn(id: number) {
|
||||
const db = await getDb();
|
||||
if (!db) return;
|
||||
await db
|
||||
.update(users)
|
||||
.set({ lastSignedIn: new Date() })
|
||||
.where(eq(users.id, id));
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// ÉTABLISSEMENTS
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function listEtablissements() {
|
||||
const db = await getDb();
|
||||
if (!db) return [];
|
||||
return db.select().from(etablissements);
|
||||
}
|
||||
|
||||
export async function upsertEtablissement(etab: InsertEtablissement) {
|
||||
const db = await getDb();
|
||||
if (!db) throw new Error("Database not available");
|
||||
await db
|
||||
.insert(etablissements)
|
||||
.values(etab)
|
||||
.onDuplicateKeyUpdate({
|
||||
set: {
|
||||
nom: etab.nom,
|
||||
groupe: etab.groupe,
|
||||
ville: etab.ville,
|
||||
actif: etab.actif,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteEtablissement(code: string) {
|
||||
const db = await getDb();
|
||||
if (!db) throw new Error("Database not available");
|
||||
await db.delete(etablissements).where(eq(etablissements.code, code));
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// PARAMÈTRES
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function getParametres() {
|
||||
const db = await getDb();
|
||||
if (!db) return [];
|
||||
return db.select().from(parametresApp);
|
||||
}
|
||||
|
||||
export async function setParametre(cle: string, valeur: string) {
|
||||
const db = await getDb();
|
||||
if (!db) throw new Error("Database not available");
|
||||
await db
|
||||
.insert(parametresApp)
|
||||
.values({ cle, valeur })
|
||||
.onDuplicateKeyUpdate({ set: { valeur } });
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// OPEX
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function getOpexPostes(annee: number) {
|
||||
const db = await getDb();
|
||||
if (!db) return [];
|
||||
return db
|
||||
.select()
|
||||
.from(opexPostes)
|
||||
.where(eq(opexPostes.annee, annee));
|
||||
}
|
||||
|
||||
export async function upsertOpexPoste(poste: InsertOpexPoste) {
|
||||
const db = await getDb();
|
||||
if (!db) throw new Error("Database not available");
|
||||
if (poste.id) {
|
||||
await db
|
||||
.update(opexPostes)
|
||||
.set(poste)
|
||||
.where(eq(opexPostes.id, poste.id));
|
||||
} else {
|
||||
await db.insert(opexPostes).values(poste);
|
||||
}
|
||||
}
|
||||
|
||||
export async function insertOpexPostes(postes: InsertOpexPoste[]) {
|
||||
const db = await getDb();
|
||||
if (!db) throw new Error("Database not available");
|
||||
if (postes.length === 0) return;
|
||||
await db.insert(opexPostes).values(postes);
|
||||
}
|
||||
|
||||
export async function getOpexMontantsEtab(annee: number) {
|
||||
const db = await getDb();
|
||||
if (!db) return [];
|
||||
return db
|
||||
.select()
|
||||
.from(opexMontantsEtab)
|
||||
.where(eq(opexMontantsEtab.annee, annee));
|
||||
}
|
||||
|
||||
export async function setOpexMontantEtab(data: InsertOpexMontantEtab) {
|
||||
const db = await getDb();
|
||||
if (!db) throw new Error("Database not available");
|
||||
await db
|
||||
.insert(opexMontantsEtab)
|
||||
.values(data)
|
||||
.onDuplicateKeyUpdate({ set: { montant: data.montant } });
|
||||
}
|
||||
|
||||
export async function insertOpexMontantsEtab(rows: InsertOpexMontantEtab[]) {
|
||||
const db = await getDb();
|
||||
if (!db) throw new Error("Database not available");
|
||||
if (rows.length === 0) return;
|
||||
// Insert par batch de 100
|
||||
for (let i = 0; i < rows.length; i += 100) {
|
||||
await db.insert(opexMontantsEtab).values(rows.slice(i, i + 100));
|
||||
}
|
||||
}
|
||||
|
||||
export async function getOpexValidated(annee: number) {
|
||||
const db = await getDb();
|
||||
if (!db) return null;
|
||||
const result = await db
|
||||
.select()
|
||||
.from(opexValidated)
|
||||
.where(eq(opexValidated.annee, annee))
|
||||
.limit(1);
|
||||
return result.length > 0 ? result[0] : null;
|
||||
}
|
||||
|
||||
export async function setOpexValidated(annee: number, userId: number) {
|
||||
const db = await getDb();
|
||||
if (!db) throw new Error("Database not available");
|
||||
await db
|
||||
.insert(opexValidated)
|
||||
.values({ annee, validatedBy: userId })
|
||||
.onDuplicateKeyUpdate({ set: { validatedAt: new Date() } });
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// INVENTAIRE PC
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function getInventaire(annee: number) {
|
||||
const db = await getDb();
|
||||
if (!db) return [];
|
||||
return db
|
||||
.select()
|
||||
.from(inventairePostes)
|
||||
.where(eq(inventairePostes.annee, annee));
|
||||
}
|
||||
|
||||
export async function getInventaireMeta(annee: number) {
|
||||
const db = await getDb();
|
||||
if (!db) return null;
|
||||
const result = await db
|
||||
.select()
|
||||
.from(inventaireMeta)
|
||||
.where(eq(inventaireMeta.annee, annee))
|
||||
.limit(1);
|
||||
return result.length > 0 ? result[0] : null;
|
||||
}
|
||||
|
||||
export async function importInventaire(
|
||||
annee: number,
|
||||
postes: typeof inventairePostes.$inferInsert[],
|
||||
meta: { filename: string; nbEtablissements: number; nbFixes: number; nbPortables: number }
|
||||
) {
|
||||
const db = await getDb();
|
||||
if (!db) throw new Error("Database not available");
|
||||
// Supprimer l'inventaire existant pour cette année
|
||||
await db.delete(inventairePostes).where(eq(inventairePostes.annee, annee));
|
||||
// Insérer les nouveaux postes par batch
|
||||
if (postes.length > 0) {
|
||||
for (let i = 0; i < postes.length; i += 200) {
|
||||
await db.insert(inventairePostes).values(postes.slice(i, i + 200));
|
||||
}
|
||||
}
|
||||
// Upsert meta
|
||||
await db
|
||||
.insert(inventaireMeta)
|
||||
.values({ annee, ...meta })
|
||||
.onDuplicateKeyUpdate({ set: { ...meta, dateImport: new Date() } });
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// CAPEX
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function getCapexLignes(annee: number, etablissementCode: string) {
|
||||
const db = await getDb();
|
||||
if (!db) return [];
|
||||
return db
|
||||
.select()
|
||||
.from(capexLignes)
|
||||
.where(
|
||||
and(
|
||||
eq(capexLignes.annee, annee),
|
||||
eq(capexLignes.etablissementCode, etablissementCode)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export async function saveCapexLignes(
|
||||
annee: number,
|
||||
etablissementCode: string,
|
||||
lignes: { cle: string; montant: string | null }[]
|
||||
) {
|
||||
const db = await getDb();
|
||||
if (!db) throw new Error("Database not available");
|
||||
for (const ligne of lignes) {
|
||||
await db
|
||||
.insert(capexLignes)
|
||||
.values({ annee, etablissementCode, cle: ligne.cle, montant: ligne.montant })
|
||||
.onDuplicateKeyUpdate({ set: { montant: ligne.montant } });
|
||||
}
|
||||
}
|
||||
|
||||
export async function insertCapexLignes(rows: InsertCapexLigne[]) {
|
||||
const db = await getDb();
|
||||
if (!db) throw new Error("Database not available");
|
||||
if (rows.length === 0) return;
|
||||
for (let i = 0; i < rows.length; i += 100) {
|
||||
await db.insert(capexLignes).values(rows.slice(i, i + 100));
|
||||
}
|
||||
}
|
||||
183
server/routers.ts
Normal file
183
server/routers.ts
Normal file
@@ -0,0 +1,183 @@
|
||||
import { COOKIE_NAME, ONE_YEAR_MS } from "@shared/const";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { z } from "zod";
|
||||
import * as db from "./db";
|
||||
import { getSessionCookieOptions } from "./_core/cookies";
|
||||
import { sdk } from "./_core/sdk";
|
||||
import { systemRouter } from "./_core/systemRouter";
|
||||
import { adminProcedure, protectedProcedure, publicProcedure, router } from "./_core/trpc";
|
||||
|
||||
const writeProcedure = protectedProcedure.use(({ ctx, next }) => {
|
||||
if (ctx.user.role === "readonly") {
|
||||
throw new TRPCError({ code: "FORBIDDEN", message: "Accès en lecture seule" });
|
||||
}
|
||||
return next({ ctx });
|
||||
});
|
||||
|
||||
export const appRouter = router({
|
||||
system: systemRouter,
|
||||
|
||||
auth: router({
|
||||
login: publicProcedure
|
||||
.input(z.object({ login: z.string().min(1), password: z.string().min(1) }))
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
const user = await db.getUserByLogin(input.login);
|
||||
if (!user || !user.isActive) {
|
||||
throw new TRPCError({ code: "UNAUTHORIZED", message: "Identifiants invalides" });
|
||||
}
|
||||
const valid = await bcrypt.compare(input.password, user.passwordHash);
|
||||
if (!valid) {
|
||||
throw new TRPCError({ code: "UNAUTHORIZED", message: "Identifiants invalides" });
|
||||
}
|
||||
await db.updateLastSignedIn(user.id);
|
||||
const token = await sdk.createSessionToken(user.id, user.login, user.role);
|
||||
const cookieOptions = getSessionCookieOptions(ctx.req);
|
||||
ctx.res.cookie(COOKIE_NAME, token, { ...cookieOptions, maxAge: ONE_YEAR_MS });
|
||||
return { id: user.id, login: user.login, email: user.email, firstName: user.firstName, lastName: user.lastName, role: user.role };
|
||||
}),
|
||||
|
||||
me: publicProcedure.query((opts) => {
|
||||
const u = opts.ctx.user;
|
||||
if (!u) return null;
|
||||
return { id: u.id, login: u.login, email: u.email, firstName: u.firstName, lastName: u.lastName, role: u.role, isActive: u.isActive };
|
||||
}),
|
||||
|
||||
logout: publicProcedure.mutation(({ ctx }) => {
|
||||
const cookieOptions = getSessionCookieOptions(ctx.req);
|
||||
ctx.res.clearCookie(COOKIE_NAME, { ...cookieOptions, maxAge: -1 });
|
||||
return { success: true } as const;
|
||||
}),
|
||||
}),
|
||||
|
||||
users: router({
|
||||
list: adminProcedure.query(async () => {
|
||||
const list = await db.listUsers();
|
||||
return list.map((u) => ({ id: u.id, login: u.login, email: u.email, firstName: u.firstName, lastName: u.lastName, role: u.role, isActive: u.isActive, createdAt: u.createdAt, lastSignedIn: u.lastSignedIn }));
|
||||
}),
|
||||
|
||||
create: adminProcedure
|
||||
.input(z.object({ login: z.string().min(1), password: z.string().min(6), email: z.string().email().optional().nullable(), firstName: z.string().optional().nullable(), lastName: z.string().optional().nullable(), role: z.enum(["admin", "standard", "readonly"]).default("standard") }))
|
||||
.mutation(async ({ input }) => {
|
||||
const existing = await db.getUserByLogin(input.login);
|
||||
if (existing) throw new TRPCError({ code: "CONFLICT", message: "Ce login existe déjà" });
|
||||
const passwordHash = await bcrypt.hash(input.password, 10);
|
||||
await db.createUser({ login: input.login, passwordHash, email: input.email ?? null, firstName: input.firstName ?? null, lastName: input.lastName ?? null, role: input.role, isActive: true });
|
||||
return { success: true };
|
||||
}),
|
||||
|
||||
update: adminProcedure
|
||||
.input(z.object({ id: z.number(), email: z.string().email().optional().nullable(), firstName: z.string().optional().nullable(), lastName: z.string().optional().nullable(), role: z.enum(["admin", "standard", "readonly"]).optional(), isActive: z.boolean().optional(), password: z.string().min(6).optional() }))
|
||||
.mutation(async ({ input }) => {
|
||||
const { id, password, ...rest } = input;
|
||||
const data: Record<string, unknown> = { ...rest };
|
||||
if (password) data.passwordHash = await bcrypt.hash(password, 10);
|
||||
await db.updateUser(id, data as Parameters<typeof db.updateUser>[1]);
|
||||
return { success: true };
|
||||
}),
|
||||
|
||||
delete: adminProcedure
|
||||
.input(z.object({ id: z.number() }))
|
||||
.mutation(async ({ input }) => { await db.deleteUser(input.id); return { success: true }; }),
|
||||
|
||||
importBulk: adminProcedure
|
||||
.input(z.array(z.object({ login: z.string().min(1), password: z.string().min(6), email: z.string().email().optional().nullable(), firstName: z.string().optional().nullable(), lastName: z.string().optional().nullable(), role: z.enum(["admin", "standard", "readonly"]).default("standard") })))
|
||||
.mutation(async ({ input }) => {
|
||||
let created = 0; let skipped = 0;
|
||||
for (const u of input) {
|
||||
const existing = await db.getUserByLogin(u.login);
|
||||
if (existing) { skipped++; continue; }
|
||||
const passwordHash = await bcrypt.hash(u.password, 10);
|
||||
await db.createUser({ login: u.login, passwordHash, email: u.email ?? null, firstName: u.firstName ?? null, lastName: u.lastName ?? null, role: u.role, isActive: true });
|
||||
created++;
|
||||
}
|
||||
return { created, skipped };
|
||||
}),
|
||||
}),
|
||||
|
||||
etablissements: router({
|
||||
list: protectedProcedure.query(async () => db.listEtablissements()),
|
||||
|
||||
upsert: adminProcedure
|
||||
.input(z.object({ code: z.string().min(1), nom: z.string().min(1), groupe: z.string().optional().nullable(), ville: z.string().optional().nullable(), actif: z.boolean().default(true) }))
|
||||
.mutation(async ({ input }) => { await db.upsertEtablissement(input); return { success: true }; }),
|
||||
|
||||
delete: adminProcedure
|
||||
.input(z.object({ code: z.string() }))
|
||||
.mutation(async ({ input }) => { await db.deleteEtablissement(input.code); return { success: true }; }),
|
||||
}),
|
||||
|
||||
parametres: router({
|
||||
get: protectedProcedure.query(async () => {
|
||||
const rows = await db.getParametres();
|
||||
return Object.fromEntries(rows.map((r) => [r.cle, r.valeur]));
|
||||
}),
|
||||
set: adminProcedure
|
||||
.input(z.object({ cle: z.string(), valeur: z.string() }))
|
||||
.mutation(async ({ input }) => { await db.setParametre(input.cle, input.valeur); return { success: true }; }),
|
||||
setBulk: adminProcedure
|
||||
.input(z.record(z.string(), z.string()))
|
||||
.mutation(async ({ input }) => {
|
||||
for (const [cle, valeur] of Object.entries(input)) await db.setParametre(cle, valeur);
|
||||
return { success: true };
|
||||
}),
|
||||
}),
|
||||
|
||||
opex: router({
|
||||
getPostes: protectedProcedure
|
||||
.input(z.object({ annee: z.number() }))
|
||||
.query(async ({ input }) => db.getOpexPostes(input.annee)),
|
||||
|
||||
upsertPoste: writeProcedure
|
||||
.input(z.object({ id: z.number().optional(), annee: z.number(), colIdx: z.number(), libelle: z.string(), libelleCourt: z.string().optional().nullable(), libelleDetail: z.string().optional().nullable(), fournisseur: z.string().optional().nullable(), categorie: z.string().optional().nullable(), type: z.string().optional().nullable(), facturation: z.string().optional().nullable(), modeVentilation: z.string().optional().nullable(), compte: z.string().optional().nullable(), detail: z.string().optional().nullable(), budgetN1: z.string().optional().nullable(), montant: z.string().optional().nullable(), isCustom: z.boolean().optional() }))
|
||||
.mutation(async ({ input }) => { await db.upsertOpexPoste(input as Parameters<typeof db.upsertOpexPoste>[0]); return { success: true }; }),
|
||||
|
||||
getMontantsEtab: protectedProcedure
|
||||
.input(z.object({ annee: z.number() }))
|
||||
.query(async ({ input }) => db.getOpexMontantsEtab(input.annee)),
|
||||
|
||||
setMontantEtab: writeProcedure
|
||||
.input(z.object({ annee: z.number(), etablissementCode: z.string(), libellePoste: z.string(), montant: z.string().nullable() }))
|
||||
.mutation(async ({ input }) => { await db.setOpexMontantEtab(input as Parameters<typeof db.setOpexMontantEtab>[0]); return { success: true }; }),
|
||||
|
||||
getValidated: protectedProcedure
|
||||
.input(z.object({ annee: z.number() }))
|
||||
.query(async ({ input }) => db.getOpexValidated(input.annee)),
|
||||
|
||||
validate: adminProcedure
|
||||
.input(z.object({ annee: z.number() }))
|
||||
.mutation(async ({ input, ctx }) => { await db.setOpexValidated(input.annee, ctx.user.id); return { success: true }; }),
|
||||
}),
|
||||
|
||||
inventaire: router({
|
||||
get: protectedProcedure
|
||||
.input(z.object({ annee: z.number() }))
|
||||
.query(async ({ input }) => {
|
||||
const postes = await db.getInventaire(input.annee);
|
||||
const meta = await db.getInventaireMeta(input.annee);
|
||||
return { postes, meta };
|
||||
}),
|
||||
|
||||
import: writeProcedure
|
||||
.input(z.object({ annee: z.number(), filename: z.string(), postes: z.array(z.object({ etablissementCode: z.string(), libelle: z.string().optional().nullable(), typePoste: z.enum(["fixe", "portable"]), dateRef: z.string().optional().nullable(), ageAns: z.string().optional().nullable(), modele: z.string().optional().nullable(), fabricant: z.string().optional().nullable() })) }))
|
||||
.mutation(async ({ input }) => {
|
||||
const nbFixes = input.postes.filter((p) => p.typePoste === "fixe").length;
|
||||
const nbPortables = input.postes.filter((p) => p.typePoste === "portable").length;
|
||||
const etabSet = new Set(input.postes.map((p) => p.etablissementCode));
|
||||
await db.importInventaire(input.annee, input.postes.map((p) => ({ ...p, annee: input.annee })), { filename: input.filename, nbEtablissements: etabSet.size, nbFixes, nbPortables });
|
||||
return { success: true, nbFixes, nbPortables, nbEtablissements: etabSet.size };
|
||||
}),
|
||||
}),
|
||||
|
||||
capex: router({
|
||||
get: protectedProcedure
|
||||
.input(z.object({ annee: z.number(), etablissementCode: z.string() }))
|
||||
.query(async ({ input }) => db.getCapexLignes(input.annee, input.etablissementCode)),
|
||||
|
||||
save: writeProcedure
|
||||
.input(z.object({ annee: z.number(), etablissementCode: z.string(), lignes: z.array(z.object({ cle: z.string(), montant: z.string().nullable() })) }))
|
||||
.mutation(async ({ input }) => { await db.saveCapexLignes(input.annee, input.etablissementCode, input.lignes); return { success: true }; }),
|
||||
}),
|
||||
});
|
||||
|
||||
export type AppRouter = typeof appRouter;
|
||||
97
server/storage.ts
Normal file
97
server/storage.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
// Preconfigured storage helpers for Manus WebDev templates
|
||||
// Uploads via Forge Server presigned URL to S3 (PUT direct).
|
||||
// Downloads return /manus-storage/{key} paths served via 307 redirect.
|
||||
|
||||
import { ENV } from "./_core/env";
|
||||
|
||||
function getForgeConfig() {
|
||||
const forgeUrl = ENV.forgeApiUrl;
|
||||
const forgeKey = ENV.forgeApiKey;
|
||||
|
||||
if (!forgeUrl || !forgeKey) {
|
||||
throw new Error(
|
||||
"Storage config missing: set BUILT_IN_FORGE_API_URL and BUILT_IN_FORGE_API_KEY",
|
||||
);
|
||||
}
|
||||
|
||||
return { forgeUrl: forgeUrl.replace(/\/+$/, ""), forgeKey };
|
||||
}
|
||||
|
||||
function normalizeKey(relKey: string): string {
|
||||
return relKey.replace(/^\/+/, "");
|
||||
}
|
||||
|
||||
function appendHashSuffix(relKey: string): string {
|
||||
const hash = crypto.randomUUID().replace(/-/g, "").slice(0, 8);
|
||||
const lastDot = relKey.lastIndexOf(".");
|
||||
if (lastDot === -1) return `${relKey}_${hash}`;
|
||||
return `${relKey.slice(0, lastDot)}_${hash}${relKey.slice(lastDot)}`;
|
||||
}
|
||||
|
||||
export async function storagePut(
|
||||
relKey: string,
|
||||
data: Buffer | Uint8Array | string,
|
||||
contentType = "application/octet-stream",
|
||||
): Promise<{ key: string; url: string }> {
|
||||
const { forgeUrl, forgeKey } = getForgeConfig();
|
||||
const key = appendHashSuffix(normalizeKey(relKey));
|
||||
|
||||
// 1. Get presigned PUT URL from Forge
|
||||
const presignUrl = new URL("v1/storage/presign/put", forgeUrl + "/");
|
||||
presignUrl.searchParams.set("path", key);
|
||||
|
||||
const presignResp = await fetch(presignUrl, {
|
||||
headers: { Authorization: `Bearer ${forgeKey}` },
|
||||
});
|
||||
|
||||
if (!presignResp.ok) {
|
||||
const msg = await presignResp.text().catch(() => presignResp.statusText);
|
||||
throw new Error(`Storage presign failed (${presignResp.status}): ${msg}`);
|
||||
}
|
||||
|
||||
const { url: s3Url } = (await presignResp.json()) as { url: string };
|
||||
if (!s3Url) throw new Error("Forge returned empty presign URL");
|
||||
|
||||
// 2. PUT file directly to S3
|
||||
const blob =
|
||||
typeof data === "string"
|
||||
? new Blob([data], { type: contentType })
|
||||
: new Blob([data as any], { type: contentType });
|
||||
|
||||
const uploadResp = await fetch(s3Url, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": contentType },
|
||||
body: blob,
|
||||
});
|
||||
|
||||
if (!uploadResp.ok) {
|
||||
throw new Error(`Storage upload to S3 failed (${uploadResp.status})`);
|
||||
}
|
||||
|
||||
return { key, url: `/manus-storage/${key}` };
|
||||
}
|
||||
|
||||
export async function storageGet(relKey: string): Promise<{ key: string; url: string }> {
|
||||
const key = normalizeKey(relKey);
|
||||
return { key, url: `/manus-storage/${key}` };
|
||||
}
|
||||
|
||||
export async function storageGetSignedUrl(relKey: string): Promise<string> {
|
||||
const { forgeUrl, forgeKey } = getForgeConfig();
|
||||
const key = normalizeKey(relKey);
|
||||
|
||||
const getUrl = new URL("v1/storage/presign/get", forgeUrl + "/");
|
||||
getUrl.searchParams.set("path", key);
|
||||
|
||||
const resp = await fetch(getUrl, {
|
||||
headers: { Authorization: `Bearer ${forgeKey}` },
|
||||
});
|
||||
|
||||
if (!resp.ok) {
|
||||
const msg = await resp.text().catch(() => resp.statusText);
|
||||
throw new Error(`Storage signed URL failed (${resp.status}): ${msg}`);
|
||||
}
|
||||
|
||||
const { url } = (await resp.json()) as { url: string };
|
||||
return url;
|
||||
}
|
||||
Reference in New Issue
Block a user