Files
waseel/app/(api)/driver/documents+api.ts
T
KrikoriosandClaude Opus 5 8807ff41c5 Waseel: driver capture, chat/calls, dispatch, and session fixes
Driver onboarding now photographs the licence, ID card and vehicle
registration and reads the credential fields off them, plus a camera-only
profile selfie riders check the arriving driver against. Adds in-app chat
and WebRTC calls, push-backed ride offers, ratings, cancellation and
payment sheets, settlement, and the owner dashboard endpoints behind them.

Camera permission on Android:
  - Declare CAMERA and READ_MEDIA_IMAGES in the manifest. expo-image-picker's
    own plugin never declares CAMERA, and Android denies a request for an
    undeclared permission instantly and silently — no dialog is ever shown,
    which is indistinguishable from the app not asking at all.
  - Handle canAskAgain: once Android stops showing the dialog, repeating why
    we need it is a dead end, so offer Open Settings instead (lib/capture-
    permission.ts), matching what the location flow already did.

Session: a 401 on a request that carried a token now ends the session
instead of being reinterpreted per-screen — driver-home had been reading it
as "this user has no driver profile" and showing an onboarding form to an
already-onboarded driver. Requests without a token are exempt so a failed
sign-in doesn't sign you out, and the notification is latched per token so
concurrent polls tear the session down once. (root) gains the auth guard
that turns that into the sign-in screen; app/index.tsx only guarded the way
in, leaving a session that ended mid-screen with nowhere to go.

Also ignore .uploads/ — it holds driver licence, ID and vehicle scans plus
profile photos, which are personal data and must not be committed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-26 02:17:55 +03:00

82 lines
3.0 KiB
TypeScript

import { preflight, withCors } from "@/lib/admin";
import { sql } from "@/lib/db";
import { requireAuth } from "@/lib/jwt";
import { isStoredUploadName, readUpload, uploadMimeType } from "@/lib/uploads";
// GET /(api)/driver/documents?name=… — serve one stored document scan.
//
// These are identity documents, so they are not static files: every read is
// authenticated and authorised here. Exactly two principals may fetch a scan —
// the driver it belongs to, and an owner reviewing that driver. Knowing the
// (unguessable) file name is not itself permission.
//
// The name travels as a query parameter rather than a path segment because it
// ends in .jpg/.png/.webp, and a dotted final segment is exactly what static
// asset middleware tends to claim before the router ever sees it. A query
// parameter cannot be mistaken for a file on disk.
//
// CORS is applied because the admin dashboard is a separate origin; it fetches
// the bytes with its bearer token and renders them from a blob URL, since an
// <img src> cannot carry an Authorization header.
export async function OPTIONS(request: Request) {
return preflight(request);
}
const notFound = (request: Request) =>
withCors(request, Response.json({ error: "Not found." }, { status: 404 }));
export async function GET(request: Request) {
const auth = requireAuth(request);
if ("error" in auth) return withCors(request, auth.error);
const name = new URL(request.url).searchParams.get("name");
// Rejecting the name before it reaches the filesystem is what keeps a
// crafted "../../.env" from ever being joined onto the upload directory.
if (!isStoredUploadName(name)) return notFound(request);
try {
const rows = await sql<{ role: string | null; owns: boolean }>`
SELECT
(SELECT role FROM users WHERE id = ${auth.userId}) AS role,
EXISTS (
SELECT 1 FROM drivers
WHERE user_id = ${auth.userId}
AND ${name} IN (
license_image_url, id_image_url, vehicle_reg_image_url
)
) AS owns
`;
const allowed = rows[0]?.role === "owner" || rows[0]?.owns === true;
// A 404 rather than a 403: a caller who is not entitled to the document
// shouldn't learn whether it exists.
if (!allowed) return notFound(request);
const bytes = await readUpload(name, "document");
if (!bytes) return notFound(request);
return withCors(
request,
new Response(new Uint8Array(bytes), {
headers: {
"Content-Type": uploadMimeType(name),
"Content-Length": String(bytes.length),
// Never let a shared cache hold somebody's ID card.
"Cache-Control": "private, no-store",
"Content-Disposition": `inline; filename="${name}"`,
"X-Content-Type-Options": "nosniff",
},
}),
);
} catch (error) {
console.error("[DRIVER_DOCUMENT_GET]: ", error);
return withCors(
request,
Response.json({ error: "Internal Server Error" }, { status: 500 }),
);
}
}