Compare commits

...
11 Commits
Author SHA1 Message Date
MythEclipseandClaude 787acf077f fix(vite): add data-cfasync="false" to script tags to prevent Cloudflare Rocket Loader breaking JS
Cloudflare Rocket Loader rewrites <script type="module"> to
<script type="randomhash-module"> which browsers can't parse,
causing complete blank page. data-cfasync="false" disables this.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-06-15 23:00:30 +07:00
MythEclipseandClaude 250355562f fix(login): replace useSearchParams with native URLSearchParams + loading spinner
- useSearchParams can lose params during re-renders, causing blank page
- Use native window.location.search + URLSearchParams instead (always accessible)
- Add oauthProcessing spinner state so user sees 'Menyelesaikan login...'
  instead of blank page while /auth/me is being called

Co-Authored-By: Claude <noreply@anthropic.com>
2026-06-15 22:38:11 +07:00
MythEclipseandClaude d47c73308e fix(auth): replace deprecated set.redirect with manual 302 Location header
Elysia's set.redirect returns 200 OK instead of 302 redirect on the
current version. Use set.status = 302 + set.headers['Location'] instead
for both /auth/google (Google OAuth redirect) and /auth/google/callback
(all redirect paths: errors, success token delivery).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-06-15 22:06:59 +07:00
MythEclipseandClaude 4b1d70d1c4 ci(deploy): inject Google OAuth env vars into VPS .env
Add GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, and GOOGLE_REDIRECT_URI
to the deploy workflow so the API can use Google OAuth on production.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-06-15 21:57:12 +07:00
MythEclipseandClaude c9ae90a042 feat(auth): implement Google OAuth callback with user auto-creation
API (apps/api/src/routes/auth.ts):
- Exchange authorization code for tokens via Google's token endpoint
- Decode id_token payload (JWT) to extract sub, email, name
- Find user by googleId → fall back to email match (link accounts)
- Auto-create user if neither found (role: 'user', no password)
- Create session + set cookie, redirect to /login?token=<token>

Web (apps/web/src/pages/login-page.tsx):
- Consume ?token= query param from OAuth redirect
- Store token in localStorage for future API calls
- Fetch /auth/me to hydrate Zustand store, then navigate to dashboard
- Show OAuth errors from ?error= query param

Co-Authored-By: Claude <noreply@anthropic.com>
2026-06-15 21:35:40 +07:00
Selly SupriyatinandGitHub caca13e32c Merge pull request #39 from ATLAS-PJK-GM007/selly/frontend
Selly/frontend
2026-06-15 21:07:56 +07:00
MythEclipseandClaude a55b1521ea ci(android): run patch-android-manifest.sh after tauri android init
Ensures CAMERA permission is always injected into the generated
AndroidManifest.xml during CI builds.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-06-15 21:05:34 +07:00
seriouselly 2eabf12b36 Merge branch 'main' of https://github.com/ATLAS-PJK-GM007/ZeaVis-Edu into selly/frontend 2026-06-15 20:55:21 +07:00
seriouselly b18b98e1a7 fix(scan): resolve empty medicine data and clean up linter warning
- Add local fallback using `diseaseCatalogSeed` to populate medicine recommendations in the diagnosis preview modal when API data is missing.
- Remove unused `diagnosesQuery` assignment to resolve SonarLint warning while preserving the background prefetching logic.
2026-06-15 20:54:44 +07:00
seriouselly 9cfbef4598 Merge branch 'main' of https://github.com/ATLAS-PJK-GM007/ZeaVis-Edu into selly/frontend 2026-06-15 20:39:01 +07:00
seriouselly 8f1308c8af fix(diagnosis): correct risk level mapping and dynamic confidence UI
- Fix `getRiskLevelKey` to properly recognize English risk level values ("low", "high"), preventing "Healthy Leaf" from incorrectly defaulting to medium risk.
- Update confidence bar text and colors to dynamically show warning alerts when AI confidence falls below the 75% threshold.
2026-06-15 20:38:26 +07:00
7 changed files with 261 additions and 40 deletions
+4
View File
@@ -136,6 +136,10 @@ jobs:
rm -rf gen/android
bun tauri android init
- name: Patch AndroidManifest (CAMERA permission)
working-directory: apps/tauri
run: bash scripts/patch-android-manifest.sh
- name: Build Tauri Android APK
working-directory: apps/tauri
env:
+3
View File
@@ -179,6 +179,9 @@ jobs:
SESSION_SECRET=${{ secrets.SESSION_SECRET }}
WEB_APP_URL=https://zeavisedu.asepharyana.my.id
ML_SERVICE_URL=http://zeavis-ml:8000
GOOGLE_CLIENT_ID=${{ secrets.GOOGLE_CLIENT_ID }}
GOOGLE_CLIENT_SECRET=${{ secrets.GOOGLE_CLIENT_SECRET }}
GOOGLE_REDIRECT_URI=https://zeavisedu.asepharyana.my.id/api/v1/auth/google/callback
ENVEOF
} > .env
+122 -3
View File
@@ -18,6 +18,54 @@ import {
import { env } from '../config/env';
import { authCounter } from '../lib/telemetry';
// ── Google OAuth Helpers ──────────────────────────────────────────────
interface GoogleTokenResponse {
access_token: string;
id_token: string;
}
interface GoogleIdPayload {
sub: string;
email: string;
email_verified: boolean;
name: string;
picture?: string;
}
async function exchangeGoogleCode(code: string): Promise<GoogleTokenResponse> {
const res = await fetch('https://oauth2.googleapis.com/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
code,
client_id: env.googleClientId!,
client_secret: env.googleClientSecret!,
redirect_uri: env.googleRedirectUri!,
grant_type: 'authorization_code',
}),
});
if (!res.ok) {
const err = await res.text();
throw new Error(`Google token exchange failed: ${res.status} ${err}`);
}
return res.json() as Promise<GoogleTokenResponse>;
}
function decodeGoogleIdToken(idToken: string): GoogleIdPayload {
// JWT: header.payload.signature — we only need the payload
// Google's id_token is verified via the token endpoint (direct server-to-server),
// so we can safely decode without verifying the signature here.
const parts = idToken.split('.');
if (parts.length !== 3) {
throw new Error('Invalid id_token format');
}
const payload = Buffer.from(parts[1], 'base64url').toString('utf-8');
return JSON.parse(payload);
}
function normalizeEmail(email: unknown) {
return typeof email === 'string' ? email.trim().toLowerCase() : '';
}
@@ -138,13 +186,84 @@ export const authRoutes = new Elysia({ prefix: '/api/v1/auth' })
prompt: 'select_account',
});
set.redirect = `https://accounts.google.com/o/oauth2/v2/auth?${params.toString()}`;
set.status = 302;
set.headers['Location'] = `https://accounts.google.com/o/oauth2/v2/auth?${params.toString()}`;
})
.get('/google/callback', ({ set }) => {
.get('/google/callback', async ({ query, set, request }) => {
if (!env.googleOAuthEnabled) {
set.status = 404;
return { error: 'Google OAuth is not configured' };
}
set.redirect = `${env.webAppUrl}/login?oauth=not-implemented`;
const code = (query as Record<string, string>).code;
const error = (query as Record<string, string>).error;
// User denied or Google returned an error
if (error || !code) {
set.status = 302;
set.headers['Location'] = `${env.webAppUrl}/login?error=${encodeURIComponent(error ?? 'missing_code')}`;
return;
}
// Exchange authorization code for tokens
let idPayload: GoogleIdPayload;
try {
const tokens = await exchangeGoogleCode(code);
idPayload = decodeGoogleIdToken(tokens.id_token);
} catch (err) {
const msg = err instanceof Error ? err.message : 'Google auth failed';
set.status = 302;
set.headers['Location'] = `${env.webAppUrl}/login?error=${encodeURIComponent(msg)}`;
return;
}
// Validate email
if (!idPayload.email_verified || !idPayload.email) {
set.status = 302;
set.headers['Location'] = `${env.webAppUrl}/login?error=${encodeURIComponent('Email not verified by Google')}`;
return;
}
const googleId = idPayload.sub;
const email = idPayload.email.trim().toLowerCase();
const name = idPayload.name?.trim() ?? email.split('@')[0];
try {
const db = createDbClient();
// 1. Try to find user by googleId
let user = await db.select().from(users).where(eq(users.googleId, googleId)).limit(1).then(r => r[0] ?? null);
// 2. If not found, try by email (link existing account)
if (!user) {
user = await db.select().from(users).where(eq(users.email, email)).limit(1).then(r => r[0] ?? null);
if (user) {
// Link googleId to existing account
await db.update(users).set({ googleId }).where(eq(users.id, user.id));
}
}
// 3. Create new user if nothing matched
if (!user) {
const inserted = await db
.insert(users)
.values({ email, name, googleId, role: 'user' })
.returning();
user = inserted[0];
authCounter.labels('register', 'true').inc();
}
// Create session
const token = await createSession(user.id);
set.headers['Set-Cookie'] = createSessionCookie(token, request.headers);
authCounter.labels('login', 'true').inc();
// Redirect to web app with token in URL for localStorage fallback
set.status = 302;
set.headers['Location'] = `${env.webAppUrl}/login?token=${encodeURIComponent(token)}`;
} catch (err) {
set.status = 302;
set.headers['Location'] = `${env.webAppUrl}/login?error=${encodeURIComponent('Database unavailable')}`;
}
});
@@ -15,7 +15,7 @@ import { RiskBadge } from "@/components/risk-badge";
type Props = {
imageUrl: string;
confidence: number; // contoh: 0.95
confidence: number;
diseaseName: string;
scientificName: string;
riskLevel: string;
@@ -42,8 +42,8 @@ export function DiagnosisResultView({
const getRiskLevelKey = (level: string): "low" | "medium" | "high" => {
const normalized = level.toLowerCase();
if (normalized.includes("rendah")) return "low";
if (normalized.includes("tinggi")) return "high";
if (normalized.includes("rendah") || normalized === "low") return "low";
if (normalized.includes("tinggi") || normalized === "high") return "high";
return "medium";
};
@@ -85,18 +85,35 @@ export function DiagnosisResultView({
<div className="space-y-2 mb-4">
<div className="flex justify-between text-sm font-bold text-slate-700">
<span>Tingkat Keyakinan AI</span>
<span className="text-emerald-600">{confidencePercent}%</span>
<span
className={
confidencePercent >= 75
? "text-emerald-600"
: "text-amber-500"
}
>
{confidencePercent}%
</span>
</div>
<div className="w-full bg-slate-200 rounded-full h-2.5 overflow-hidden">
<div
className="bg-emerald-500 h-2.5 rounded-full transition-all duration-1000"
className={`h-2.5 rounded-full transition-all duration-1000 ${
confidencePercent >= 75 ? "bg-emerald-500" : "bg-amber-500"
}`}
style={{ width: `${confidencePercent}%` }}
></div>
</div>
<p className="text-[11px] text-emerald-600 flex items-center gap-1 font-medium">
<CheckCircle2 className="w-3 h-3" /> Di atas ambang batas minimum
(75%)
</p>
{confidencePercent >= 75 ? (
<p className="text-[11px] text-emerald-600 flex items-center gap-1 font-medium">
<CheckCircle2 className="w-3 h-3" /> Di atas ambang batas
minimum (75%)
</p>
) : (
<p className="text-[11px] text-amber-600 flex items-center gap-1 font-medium">
<AlertTriangle className="w-3 h-3" /> Di bawah ambang batas
minimum (75%)
</p>
)}
</div>
<div className="flex items-center gap-3 pt-4 border-t border-amber-200/50">
+48 -3
View File
@@ -1,15 +1,48 @@
import { useState } from "react";
import { useState, useEffect, useRef } from "react";
import { Link, useNavigate } from "react-router-dom";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { AuthForm } from "@/components/auth-form";
import { apiClient } from "@/lib/api-client";
import { apiClient, setAuthToken } from "@/lib/api-client";
import { useAuthStore } from "@/store/auth-store";
function getUrlParam(name: string): string | null {
return new URLSearchParams(window.location.search).get(name);
}
export function LoginPage() {
const navigate = useNavigate();
const queryClient = useQueryClient();
const setUser = useAuthStore((state) => state.setUser);
const [error, setError] = useState<string | null>(null);
const oauthTokenConsumed = useRef(false);
const [oauthProcessing, setOauthProcessing] = useState(false);
// Handle OAuth callback: the API redirects to /login?token=<session_token>
useEffect(() => {
const token = getUrlParam("token");
if (!token || oauthTokenConsumed.current) return;
oauthTokenConsumed.current = true;
setOauthProcessing(true);
// Store token for future API calls and fetch user
setAuthToken(token);
apiClient
.getMe()
.then((data) => {
setUser(data.user);
queryClient.setQueryData(["auth", "me"], data);
navigate("/dashboard", { replace: true });
})
.catch((err) => {
setAuthToken(null);
setOauthProcessing(false);
setError(err instanceof Error ? err.message : "Google login gagal");
});
}, [setUser, queryClient, navigate]);
// Show OAuth error from query param
const oauthError = getUrlParam("error");
const meQuery = useQuery({
queryKey: ["auth", "me"],
queryFn: () => apiClient.getMe(),
@@ -26,13 +59,25 @@ export function LoginPage() {
setError(err instanceof Error ? err.message : "Login gagal"),
});
// Show loading spinner while OAuth token is being processed
if (oauthProcessing) {
return (
<main className="flex min-h-screen items-center justify-center px-6 py-12">
<div className="flex flex-col items-center gap-3">
<div className="h-10 w-10 border-4 border-green-500 border-t-transparent rounded-full animate-spin" />
<p className="text-gray-500 text-sm">Menyelesaikan login dengan Google...</p>
</div>
</main>
);
}
return (
<main className="flex min-h-screen items-center justify-center px-6 py-12">
<div className="w-full max-w-sm md:max-w-md space-y-4">
<AuthForm
mode="login"
isSubmitting={mutation.isPending}
error={error}
error={oauthError || error}
googleOAuthEnabled={Boolean(
meQuery.data?.features.googleOAuthEnabled,
)}
+42 -24
View File
@@ -16,6 +16,7 @@ import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Modal } from "@/components/ui/modal";
import type { DiagnosisRecord } from "@zeavis/shared";
import { diseaseCatalogSeed } from "@zeavis/shared"; // Import data seed lokal ditambahkan
import { apiClient } from "@/lib/api-client";
import { trackScan, trackDiagnosisResult } from "@/lib/telemetry";
import { DiagnosisResultView } from "../components/diagnose-result-view";
@@ -95,7 +96,7 @@ export function ScanPage() {
const [diagnosisPreview, setDiagnosisPreview] =
useState<DiagnosisRecord | null>(null);
const diagnosesQuery = useQuery({
useQuery({
queryKey: ["diagnoses"],
queryFn: () => apiClient.getDiagnoses(),
enabled: previewOpen,
@@ -429,29 +430,46 @@ export function ScanPage() {
</div>
)}
<DiagnosisResultView
imageUrl={
previewUrl ||
diagnosisPreview.imageUrl ||
"https://placehold.co/600x400?text=Foto+Daun"
}
confidence={diagnosisPreview.confidence ?? 0}
diseaseName={
diagnosisPreview.disease?.commonName ?? "Tidak Diketahui"
}
scientificName={diagnosisPreview.disease?.label ?? ""}
riskLevel={diagnosisPreview.disease?.riskLevel ?? "Sedang"}
description={
diagnosisPreview.disease?.description ??
diagnosisPreview.disease?.summary ??
"Deskripsi tidak tersedia."
}
symptoms={diagnosisPreview.disease?.symptoms ?? []}
preventions={diagnosisPreview.disease?.recommendations ?? []}
medicines={
(diagnosisPreview.disease as any)?.medicineRecommendations ?? []
}
/>
{/* Render DiagnosisResultView dengan Fallback Obat */}
{(() => {
// Fallback logic for scientific name and medicine recommendations
const seedData = diagnosisPreview.disease
? diseaseCatalogSeed.find(
(seed) =>
seed.commonName === diagnosisPreview.disease?.commonName,
)
: null;
// If the API doesn't return medicine recommendations, use the seed data as a fallback
const finalMedicines =
(diagnosisPreview.disease as any)?.medicineRecommendations ||
seedData?.medicineRecommendations ||
[];
return (
<DiagnosisResultView
imageUrl={
previewUrl ||
diagnosisPreview.imageUrl ||
"https://placehold.co/600x400?text=Foto+Daun"
}
confidence={diagnosisPreview.confidence ?? 0}
diseaseName={
diagnosisPreview.disease?.commonName ?? "Tidak Diketahui"
}
scientificName={diagnosisPreview.disease?.label ?? ""}
riskLevel={diagnosisPreview.disease?.riskLevel ?? "Sedang"}
description={
diagnosisPreview.disease?.description ??
diagnosisPreview.disease?.summary ??
"Deskripsi tidak tersedia."
}
symptoms={diagnosisPreview.disease?.symptoms ?? []}
preventions={diagnosisPreview.disease?.recommendations ?? []}
medicines={finalMedicines} // Datanya terhubung ke sini!
/>
);
})()}
{/* All Model Predictions */}
{diagnosisPreview.predictions &&
+16 -1
View File
@@ -9,7 +9,22 @@ export default defineConfig(({ mode }) => {
const apiProxyTarget = env.VITE_API_PROXY_TARGET || 'http://localhost:3000';
return {
plugins: [react(), tsconfigPaths(), metricsPlugin()],
plugins: [
react(),
tsconfigPaths(),
metricsPlugin(),
{
name: 'cloudflare-rocket-loader-fix',
transformIndexHtml(html) {
// Prevent Cloudflare Rocket Loader from mangling <script type="module">
// which breaks the entire JS bundle (blank page)
return html.replace(
/<script type="module"/g,
'<script data-cfasync="false" type="module"',
);
},
},
],
server: {
proxy: {
'/api': apiProxyTarget,