Two repositories, one system. This repository is the React client. The API lives in Safe-Backend (Express 5, Socket.IO, MongoDB Atlas). Both must be running.
Conventional navigation software optimises for time. For a person travelling alone after dark, the quantity that matters is different: the probability that something goes wrong along the way, and whether anyone would notice.
Safe is a web platform that treats journey safety as a measurable, explainable quantity. It scores every candidate route against community-reported incidents using a transparent, deterministic model (§3), lets chosen contacts follow a journey in real time under explicit permissions (§4), escalates automatically when a journey overruns its time budget, and gives the traveller low-friction tools for the moments in between: an SOS alert, a simulated incoming call, and short-lived proximity groups called Safe Circles.
The scoring model is intentionally simple enough to be audited by hand. Every route shows its score, the number of incidents behind it, and a plain-language explanation of how it was reached.
- Motivation
- Capabilities
- Risk model
- Journey model
- System architecture
- Privacy and security
- Identity verification
- Administration
- Reproducibility
- Interfaces
- Limitations and future work
- Contributing, citation, license
| Design question | Typical map application | Safe |
|---|---|---|
| What is optimised? | Duration | Duration and incident exposure |
| Why was this route chosen? | Opaque | A score, an incident count and an explanation |
| Who knows where I am? | Nobody, or everybody | Only contacts I choose, only for the share's lifetime |
| What if I do not arrive? | Nothing happens | The journey has a time budget; overrun triggers escalation |
| Where does my data go? | Third-party services | Assistant runs on a local model, so questions stay on your machine |
| Phase | Capability |
|---|---|
| Plan | Type-ahead place search (Nominatim) · current-location start via reverse geocoding · several candidate routes per query, each with a risk score, incident count and explanation · traffic level, delay and duration from Google or Mapbox when configured, otherwise a time-of-day estimate · area safety score within 3 km · nearest police station with a route to it |
| Travel |
Live position streaming with progress and distance remaining · time budget with 15-minute extensions · admin-initiated arrival check-in · trusted-contact monitoring with per-share permissions (LOCATION, ROUTE, STATUS), optional expiry, instant revoke and an access audit trail
|
| Respond | Emergency SOS that captures GPS and raises a real-time alert on the admin console · discreet escape call · Safe Circles (private, capped, expiring groups with join approval) · street incident reports that feed the route score · trusted contact management |
| Assist | Account-aware help assistant on a local Ollama model, with cited sources, confirmation-gated actions and voice dictation · two-step identity verification (§7) |
Each route returned by the API carries riskScore (0 to 100, lower is safer), riskLevel, incidentCount and an explanation.
Let
and the route's risk score is
The recommended route is
|
Severity weight
|
Recency multiplier
|
Interpretation of
|
The dashboard's area safety score applies the same weights to incidents within a 3 km radius of the user and is displayed on a scale from 100 (safest) down to 10.
Two candidate routes between the same origin and destination:
| Route | Incidents within 1 km | Contribution | Sum | Level | |
|---|---|---|---|---|---|
| A (fastest) |
HIGH, 3 days old |
||||
MODERATE, 40 days old |
|||||
LOW, 100 days old |
60 | 60 | HIGH |
||
| B (+6 min) |
MODERATE, 5 days old |
25 | 25 | LOW |
Route B is recommended. The interface shows the 6-minute cost next to the 35-point reduction, so the trade-off is explicit and the user decides.
- Monotone. Adding an incident never lowers a score.
- Additive. Contributions are independent, so any score can be decomposed and checked by hand.
-
Bounded.
$R \in [0, 100]$ by the cap. - Decaying. Older reports count for less, in four discrete steps.
- Deterministic. The same incidents and the same route always give the same score.
The limitations that follow from these choices are discussed in §11.
Categories: Harassment · Stalking · Theft · Suspicious Activity · Assault · Unsafe Road · Poor Lighting · Other.
Reporters enter only a place name. The server geocodes it, stores the coordinates and timestamps the report, so location and time cannot be typed in by the reporter. Administrators can triage reports, add notes and attach evidence links.
A journey is a finite-state process with one live state and one terminal state.
stateDiagram-v2
direction LR
[*] --> ACTIVE: start
ACTIVE --> ACTIVE: extend (+15 min)
ACTIVE --> COMPLETED: user stops
ACTIVE --> COMPLETED: time budget exceeded
ACTIVE --> COMPLETED: admin escalation
COMPLETED --> [*]
On completion, every active share expires and all monitoring sockets are disconnected, so access to a person's location ends with the journey.
| Parameter | Value |
|---|---|
| Time budget | estimated duration + 60 min |
| Extension step | 15 min |
| Position update | every 10 s, or earlier once the user has moved 25 m |
| Circle location precision | 3 decimal places, about 110 m |
| Monitor access condition | journey is ACTIVE, share is unexpired, share grants LOCATION |
flowchart LR
subgraph FE["Client: React + Vite (this repo)"]
UI["Pages, dock, SOS button"]
MAP["Leaflet maps"]
HK["useSocket, useLocationTracking"]
end
subgraph BE["Server: Express 5 + Socket.IO"]
API["REST API, session auth"]
SCORE["Safety scoring"]
RT["Realtime rooms"]
end
DB[("MongoDB Atlas")]
subgraph EXT["External, optional"]
OSM["Nominatim, OSRM"]
TRF["Google or Mapbox traffic"]
CLD["Cloudinary"]
OLL["Ollama (local)"]
end
UI -->|"REST via /api proxy"| API
HK <-->|"Socket.IO"| RT
MAP --- UI
API --> SCORE --> DB
API --> DB
API --> OSM
API --> TRF
API --> CLD
API --> OLL
| Layer | Choice | Rationale |
|---|---|---|
| Client | React 19, TypeScript, Vite 8, Tailwind 4 | Typed UI with fast iteration |
| Maps | Leaflet on OpenStreetMap tiles | Open data, no vendor lock-in |
| Routing | OSRM, optionally enriched by Google or Mapbox | Works with no API keys; traffic is an upgrade |
| Realtime | Socket.IO, authenticated with the session token | Rooms map directly to journeys and circles |
| Persistence | MongoDB Atlas | Flexible documents for incidents, journeys, shares |
| Assistant | Ollama (llama3.2:3b by default) |
No third-party AI API sees user questions |
| Testing | Playwright (client), Node test runner (server) | End-to-end smoke tests plus unit and integration tests |
| Threat | Mitigation |
|---|---|
| Password database disclosure | scrypt with a per-user salt; constant-time comparison |
| Session token theft from the database | 256-bit random tokens; only the SHA-256 hash is stored, with an expiry |
| Credential guessing | Login limited to 10 attempts per 15 minutes on both user and admin portals |
| Unauthorised access to a journey | Ownership checks on user routes; shares must be unexpired and grant LOCATION; sockets authenticate during the handshake |
| Location overexposure inside a group | Safe Circle coordinates rounded to about 110 m before broadcast |
| Lingering access after a trip | Shares expire and monitor sockets disconnect when a journey completes |
| Privilege misuse | requireAdmin on all /api/admin routes; admin actions written to an audit log; share access has its own audit trail |
| Abusive or compromised accounts | Suspension enforced at the session layer; sessions revocable individually or all at once |
| Leakage of user questions to AI vendors | Help assistant runs on a local model |
Transport security (TLS) is expected to be provided by the deployment. .env files hold secrets and must never be committed.
Full access requires a two-step check followed by human review.
flowchart LR
A["Register, sign in"] --> B["Voice check"]
B --> C["Details and document upload"]
C --> D{"Automated review hook?"}
D -->|"yes"| E["Provider result attached"]
D -->|"no"| F["Marked for manual review"]
E --> G["Admin review queue"]
F --> G
G -->|"approve"| H["Verified member"]
G -->|"reject"| I["Access stays limited"]
The voice step runs entirely in the browser: the Web Audio API captures the signal and pitch is estimated by autocorrelation, so no audio leaves the device. The document step posts to /api/auth/verification-submission. An external review service can be attached through AADHAAR_AI_REVIEW_URL; without it, submissions go straight to manual review.
A separate full-screen console at /admin, with its own sign-in at /login?admin=true. Admins are kept out of the citizen app and citizens out of /admin.
| Module | Function |
|---|---|
| Dashboard | Platform statistics, recent reports, incident trend |
| Users | Directory, verification status, suspend or restore, role changes, session revocation |
| Reports | Triage, status, notes, evidence links |
| Safety Map | Risk zones and hotspots |
| Live Journeys | Every active journey with its latest authorised position |
| Journey Check-ins | Ask a traveller to confirm arrival; escalate on NO or silence |
| Verification Review | Queue of pending identity submissions |
| Broadcast | Safety broadcasts to users, with history |
| Analytics | Trends over a chosen date range |
| Settings | Alert radius, routing provider, feature switches, retention, audit logging, maintenance mode |
Admins receive real-time notifications for SOS alerts and check-in responses, and can export data as files.
- Node.js 20.19 or newer (22 LTS recommended)
- A free MongoDB Atlas cluster
- Optional: Ollama for the help assistant
The Playwright config starts the API from ../backend, so clone with these folder names:
mkdir safe-platform && cd safe-platform
git clone https://github.com/Puskar2Sora/Safe-Backend.git backend
git clone https://github.com/Puskar2Sora/Safe.git frontendBackend
cd backend
npm install
cp .env.example .env # Windows PowerShell: copy .env.example .env
# edit .env, then:
node scripts/importData.js # optional seed: incidents, journeys, circles, help docs
npm run dev # http://localhost:5000Expected output: Connected to MongoDB Atlas, then the listening message.
Frontend
cd ../frontend
npm install
npm run dev # http://localhost:5173Vite proxies /api and WebSocket traffic to http://localhost:5000. To target a deployed API, set VITE_API_URL in frontend/.env.
First administrator
- Register normally in the app.
- In Atlas, open the
userscollection and setrole: "admin"on your user. - Sign in at
http://localhost:5173/login?admin=true.
Local assistant (optional)
ollama pull llama3.2:3bIf Ollama is not running, the assistant falls back to a static help guide.
All variables go in backend/.env.
| Variable | Required | Purpose |
|---|---|---|
MONGODB_URI |
yes | Atlas connection string |
MONGODB_DB_NAME |
Database name (default womens_safety) |
|
PORT |
API port (default 5000) |
|
FRONTEND_URL |
Allowed Socket.IO origin (default http://localhost:5173) |
|
GOOGLE_MAPS_API_KEY |
Google traffic-aware routing | |
MAPBOX_ACCESS_TOKEN |
Fallback traffic provider | |
CLOUDINARY_CLOUD_NAME, CLOUDINARY_API_KEY, CLOUDINARY_API_SECRET |
Profile photo uploads | |
OLLAMA_BASE_URL, OLLAMA_MODEL |
Local model for the assistant | |
AADHAAR_AI_REVIEW_URL, AADHAAR_AI_REVIEW_API_KEY |
Optional automated document review |
With no Google or Mapbox key, routing runs on OSRM with time-of-day traffic estimates.
| Where | Command | Purpose |
|---|---|---|
| frontend | npm run dev |
Dev server |
| frontend | npm run build |
Type-check (tsc -b) and production build |
| frontend | npm run lint |
Oxlint |
| frontend | npm run test:e2e |
Playwright smoke tests (starts API and app) |
| backend | npm run dev / npm start |
API with or without nodemon |
| backend | npm test |
Auth, profile, contacts, journeys, SOS, Safe Circles, routing and traffic logic |
Common failures and fixes
| Symptom | Cause and fix |
|---|---|
404 on /api/... |
Backend not running, or Vite not restarted after vite.config.ts changed |
MONGODB_URI is not set |
require('dotenv').config() must run before anything that reads process.env |
querySrv ECONNREFUSED |
DNS SRV lookups are blocked. Use 8.8.8.8 or 1.1.1.1, or Atlas's non-SRV mongodb:// string |
| Atlas connection times out | Add your IP under Network Access in Atlas |
| Signed out immediately | A 401 clears the stored session by design. Sign in again and check the system clock |
| Generic assistant answers | Ollama is not running or the model is not pulled |
Base URL http://localhost:5000/api. Every endpoint except /health, /auth/register and the login routes requires Authorization: Bearer <token>.
Authentication
| Method | Endpoint | Purpose |
|---|---|---|
POST |
/auth/register |
Create an account |
POST |
/auth/login |
User sign-in (rate limited) |
POST |
/auth/admin-login |
Admin sign-in (rate limited) |
POST |
/auth/logout |
End the session |
GET |
/auth/me |
Current user |
PATCH |
/auth/profile |
Update profile |
POST |
/auth/profile/avatar |
Upload a photo |
POST |
/auth/verification-submission |
Submit identity verification (multipart) |
Routes and places
| Method | Endpoint | Purpose |
|---|---|---|
GET |
/routes/search?q=&lat=&lon= |
Place suggestions |
GET |
/routes/reverse?latitude=&longitude= |
Coordinates to address |
POST |
/routes |
Candidate routes with risk and traffic |
GET |
/routes/nearest-police?lat=&lon= |
Nearest police station |
GET |
/routes/safety-assessment?lat=&lon= |
Area safety score |
POST /routes accepts place names or resolved coordinates:
{
"from": { "latitude": 22.5726, "longitude": 88.3639, "displayName": "Kolkata" },
"to": "Barasat"
}Journeys
| Method | Endpoint | Purpose |
|---|---|---|
POST |
/journeys |
Start a journey |
GET |
/journeys |
List your journeys |
GET |
/journeys/:userId/active |
Your active journey |
GET |
/journeys/:userId/active/:journeyId |
A specific active journey |
PATCH |
/journeys/:id/extend |
Add minutes to the budget |
PATCH |
/journeys/:id/check-in |
Answer a check-in (YES or NO) |
PATCH |
/journeys/:id/stop |
Complete the journey |
POST |
/journeys/:journeyId/share |
Share with trusted contacts |
GET |
/journeys/:journeyId/shares |
List active shares |
DELETE |
/journeys/:journeyId/share/:shareId |
Revoke a share |
GET |
/journeys/:journeyId/monitor |
Monitor view for a contact |
GET |
/journeys/:journeyId/access-audit |
Who accessed a share, and when |
Incidents, contacts, emergencies, circles, assistant
| Method | Endpoint | Purpose |
|---|---|---|
GET POST |
/incidents |
Browse or report incidents |
POST GET DELETE |
/contacts, /contacts/:userId, /contacts/:id |
Trusted contacts |
POST GET |
/emergencies |
Raise or list SOS alerts |
POST |
/safe-circles |
Create a circle |
GET |
/safe-circles/nearby |
Circles near you |
GET |
/safe-circles/:id, /safe-circles/:id/requests |
Details and join requests |
POST PATCH |
/safe-circles/:id/request, /requests/:requestId |
Request, approve or decline |
POST PATCH |
/safe-circles/:id/leave, /safe-circles/:id/end |
Leave or end |
POST |
/chatbot/query |
Ask the assistant |
GET |
/health |
Health check (public) |
Administration (role: admin)
/admin/stats · /admin/analytics · /admin/audit-logs · /admin/export/:resource · /admin/settings · /admin/broadcast · /admin/broadcasts · /admin/users (verify, suspension, role, revoke-sessions) · /admin/incidents (update, notes, evidence) · /admin/live-journeys · /admin/journey-check-ins/:journeyId (+ /escalate)
Socket.IO shares the API port and authenticates with the session token.
| Direction | Event | Meaning |
|---|---|---|
| client → server | join_journey, leave_journey |
Owner enters or leaves a journey room |
| client → server | join_monitoring |
Trusted contact joins a shared journey |
| client → server | location_update |
Owner broadcasts a position |
| client → server | join_circle, leave_circle |
Enter or leave a Safe Circle |
| client → server | circle_location_update |
Share a rounded position with the circle |
| server → client | journey_joined, user_connected, user_disconnected |
Room presence |
| server → client | location_updated |
New journey position |
| server → client | journey_check_in |
Ask the traveller whether they have arrived |
| server → client | journey_completed |
Stopped, timed out or escalated |
| server → client | circle_location_update |
A circle member moved |
| server → client | admin_notification |
SOS and check-in alerts |
| server → client | journey_error |
Authorisation or validation failure |
| Route | Page | Access |
|---|---|---|
/ |
Landing | Public (signed-in users redirected) |
/login, /register |
Authentication | Public |
/verify-gender |
Identity verification | Signed in |
/home, /dashboard |
Quick actions, safety score, nearest police | Verified |
/journey, /journey/active/:journeyId |
Planner, live tracking | Verified |
/monitor/journey/:journeyId |
Follow a shared journey | Verified |
/safe-circle, /incidents, /contacts, /profile, /help |
Circles, reports, contacts, profile, assistant | Verified |
/admin |
Admin console | Admin only |
Frontend and backend trees
Safe/ (this repository)
├── e2e/smoke.spec.ts Playwright smoke tests
├── vite.config.ts dev proxy: /api -> http://localhost:5000
├── docs/assets/banner.svg
└── src/
├── App.tsx router, auth guards, shell
├── lib/api.ts apiFetch: Bearer token, sign-out on 401
├── hooks/ useSocket, useLocationTracking
├── pages/ Landing, Dashboard, Journey, ActiveJourney,
│ MonitorJourney, SafeCircle, IncidentReport,
│ Contacts, Profile, Chatbot, VerifyGender,
│ Login, Register, AdminDashboard
└── components/ admin, auth, common, dashboard, emergency,
journey, map, navigation
Safe-Backend/
├── server.js Express, Socket.IO, socket auth
├── config/db.js connection and indexes
├── middleware/ auth (sessions, roles), rateLimit
├── routes/ auth, admin, routes, incidents, journeys, contacts,
│ emergencies, safeCircles, chatbot, health
├── services/ routingService, safetyScoringService,
│ chatbotService, aadhaarReview
├── scripts/importData.js seed loader
└── test/ integration and routing tests
| Limitation | Consequence |
|---|---|
| Reporting bias. Scores reflect what people report, not what happens | Under-reported areas look safer than they are |
| No length normalisation. The score is a sum, not a rate | Longer routes accumulate more incidents and are penalised even when per-kilometre exposure is lower |
| Saturation at 100 | Routes beyond the cap cannot be told apart |
| Uniform 1 km radius | A report 900 m away counts as much as one on the route itself |
| Time-blind. No dependence on time of day | A route that is unsafe only after dark is scored the same at noon |
| Hand-set weights. Severity and recency values are design parameters | Scores are a ranking aid, not a probability of harm |
- SOS alerts reach the admin console, not yet the traveller's own trusted contacts.
- No installable PWA or push notifications for shared journeys.
- Interface is English only.
- Risk-scored alternatives with traffic-aware ETAs
- Journey sharing with permissions, expiry, revoke and audit trail
- Time-limited journeys with extension, check-ins and admin escalation
- Safe Circles with approval and privacy-rounded locations
- Two-step verification with admin review queue
- Admin console: live journeys, broadcasts, analytics, settings
- Local-model assistant
- SOS delivery to trusted contacts (SMS or push)
- Time-of-day aware risk scoring
- Distance-weighted incident influence and per-kilometre normalisation
- PWA and push notifications
- Hindi and Bengali translations
- Broader end-to-end coverage
Contributing. Fork, branch (git checkout -b feature/your-idea), run npm run lint and npm run build, then open a pull request describing what changed and why. Changes to the risk model should include a worked example showing the effect on a score.
Citation. Acknowledgements. Map data © OpenStreetMap contributors. Geocoding by Nominatim, routing by OSRM, maps rendered with Leaflet. Please respect the public usage policies of Nominatim and OSRM, and self-host them for real traffic.