This commit is contained in:
Meghdad committed 2026-08-25 02:18:50 +03:30
commit 341e9e433e
65 files changed
+5782

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
*.iml
.gradle/
/local.properties
/.idea/
.idea/
/build/
/captures/
.externalNativeBuild/
.cxx/
app/build/
+72
View File
@@ -0,0 +1,72 @@
# API Guide
The official machine-readable contract is [openapi.yaml](openapi.yaml). All timestamps are Unix epoch milliseconds unless a field explicitly says seconds.
## Base URL
```text
http://<device-ip>:<configured-port>/api/v1
```
## Authentication
When authentication is enabled, use either:
```http
Authorization: Bearer YOUR_API_KEY
```
or:
```http
X-API-Key: YOUR_API_KEY
```
Bearer authentication is recommended. Authentication applies to every `/api/v1` endpoint. The app stores only the key hash. When the IP allowlist is enabled, both authentication and the allowlist must pass.
## Endpoints
| Method | Path | Purpose |
|---|---|---|
| GET | `/docs` | Open the locally bundled interactive Swagger UI |
| GET | `/docs/openapi.yaml` | Download the exact OpenAPI YAML packaged with the app |
| GET | `/api/v1` | API version, capabilities, and endpoint discovery |
| GET | `/api/v1/health` | Basic device/server health |
| GET | `/api/v1/status` | Server state and counters |
| POST | `/api/v1/sms/send` | Submit one SMS of up to 160 characters |
| GET | `/api/v1/sms/messages` | Paginated incoming/outgoing history |
| GET | `/api/v1/sms/messages/{id}` | Message details |
Message list parameters:
- `page`: positive integer, default 1
- `page_size`: 1–100, default 50
- `direction`: `all`, `incoming`, or `outgoing`
- `search`: sender, recipient, body, or outgoing status search
## Send lifecycle
Successful submission returns HTTP 202 with status `pending`. Android later updates the local outgoing record to `sent` or `failed`. `sent` means Android's SMS service accepted the message; it is not a carrier delivery receipt.
## Error format
```json
{
"success": false,
"error": {
"code": "INVALID_RECIPIENT",
"message": "Recipient phone number is invalid"
}
}
```
Stable codes include:
- `INVALID_JSON`, `INVALID_RECIPIENT`, `EMPTY_MESSAGE`, `MESSAGE_TOO_LONG`
- `LENGTH_REQUIRED`, `PAYLOAD_TOO_LARGE`
- `AUTHENTICATION_REQUIRED`, `INVALID_API_KEY`, `AUTHENTICATION_NOT_CONFIGURED`
- `IP_NOT_ALLOWED`
- `SMS_PERMISSION_DENIED`, `SMS_SEND_FAILED`
- `MESSAGE_NOT_FOUND`, `NOT_FOUND`, `METHOD_NOT_ALLOWED`, `INTERNAL_ERROR`
Clients must branch on `error.code`, not the human-readable message.
+76
View File
@@ -0,0 +1,76 @@
# Architecture
## Shape
```text
Compose UI → GatewayViewModel → repositories → Room / server controller / Android SMS
↑
HTTP transport → ApiRouter → security policy + repositories + SmsSender
SMS broadcasts ────────────────────────────────→ repositories
```
The project deliberately remains a single Gradle module. Packages provide the boundaries that are currently useful without paying the maintenance cost of premature multi-module architecture.
## Responsibilities
- `ui`: immutable screen state and user actions. It never invokes `SmsManager` or NanoHTTPD directly.
- `data.local`: Room entities, DAO, and database. Database schema version 1 is exported under `app/schemas`.
- `data`: repositories exposing persistence operations and flows.
- `sms`: `SmsSender` abstraction, Android sender, sent-result receiver, and incoming receiver.
- `security`: API-key hashing/constant-time comparison, exact-IP validation, and access decisions.
- `server`: server lifecycle, foreground service, transport adapter, API routing, JSON models, network address detection, and reboot receiver.
- `di`: a small application-scoped constructor-injection container.
Hilt was evaluated, but the current Hilt/AGP dependency chain required an unavailable Fragment artifact despite this being a Compose-only app. The small `AppContainer` keeps dependencies explicit and replaceable without introducing an artifact mirror or unused Fragment runtime. Repositories and controllers use constructor injection, so migration to Hilt remains mechanical.
## Server lifecycle
`GatewayServerService` owns the foreground-service lifetime. `GatewayServerController` serializes start/stop/restart operations with a mutex and isolates server exceptions from the UI process. A state flow exposes stopped, starting, running, stopping, and error states. NanoHTTPD uses a 10-second socket timeout and handles requests on worker threads; suspend repository work is isolated on `Dispatchers.IO`.
The desired enabled state is persisted. When reboot startup is enabled, `BootReceiver` restores the foreground service after `BOOT_COMPLETED`.
## API pipeline
Every `/api/v1` request follows one centralized path:
1. Restrict routes to `/api/v1` and the locally bundled `/docs` resources, then capture safe request metadata.
2. Load the current security settings.
3. Enforce exact-IP allowlisting when enabled.
4. Enforce Bearer or `X-API-Key` authentication when enabled.
5. Validate method, route, pagination, content length, JSON, phone number, and message size.
6. Invoke repositories or the `SmsSender` interface.
7. Emit a stable JSON response.
8. Persist sanitized method/path/status/client IP/duration metadata in `finally`.
Documentation resources are intentionally public so a normal browser can load Swagger UI and its OpenAPI document. They expose only the published contract; API operations still pass through authentication and allowlisting.
`ApiRouter` does not depend on NanoHTTPD implementation details beyond the request session at its transport boundary. Authentication decisions are separate in `SecurityPolicy`, leaving a clear insertion point for HMAC, timestamp/nonce checks, replay storage, and rate limiting.
## Persistence
Room stores four tables:
- `incoming_sms`
- `outgoing_sms`
- `request_logs`
- `app_settings`
Messages use UUID strings so IDs remain stable across API, database, pending intents, and future central management. Request logs are capped at the newest 10,000 records. API keys are stored as SHA-256 hashes, never plaintext.
## Reliability boundaries
- Server lifecycle transitions are mutex-protected.
- Each API request has a top-level exception boundary and a stable internal error response.
- Broadcast receivers use `goAsync`, defensive parsing, IO coroutines, and guaranteed `finish()` calls.
- Outgoing rows are persisted before Android submission and updated on immediate or asynchronous failure.
- Room provides serialized transactions and concurrency safety.
- Server configuration changes trigger a safe restart only when currently running.
## Future extensions
- Replace the key-only policy with a chain supporting HMAC, nonce persistence, and timestamp windows.
- Add a queue/work scheduler between API submission and `SmsSender`.
- Add multipart and delivery pending intents without changing API routing.
- Introduce a SIM-selection strategy behind `SmsSender`.
- Add CIDR parsing behind the allowlist policy.
- Terminate TLS in an Android-capable transport or a controlled reverse proxy.
+72
View File
@@ -0,0 +1,72 @@
# Android SMS Gateway
Android SMS Gateway turns a dedicated Android phone into a directly reachable, HTTP-based SMS gateway. A trusted backend can check device health, send SMS messages, and retrieve locally persisted incoming and outgoing history without polling, FCM, WebSockets, or a cloud relay.
## Current MVP
- Embedded NanoHTTPD server with configurable port and bind address
- Offline interactive Swagger UI at `GET /docs`, backed by the packaged OpenAPI contract
- Versioned `/api/v1` REST API
- API-key authentication and exact-IP allowlist
- Android `SmsManager` submission with asynchronous sent/failure result tracking
- Safe incoming SMS broadcast handling
- Room persistence for messages, settings, and sanitized request logs
- Foreground-service lifecycle, optional reboot startup, status, uptime, and counters
- Compose Material 3 dashboard, history, logs, server, security, and permissions screens
- OpenAPI contract and an agent-ready `SKILL.md`
Multipart SMS, delivery reports, retries, queues, CIDR allowlists, HMAC signing, multiple SIM selection, TLS termination, and cloud management are intentionally outside this MVP.
## Requirements
- Android Studio with JDK 17 or newer
- Android SDK 37
- Android 8.0 (API 26) or newer phone with telephony/SMS support
- A backend that can directly route to the phone over a trusted LAN, VPN, public/static IP, or carefully configured port forwarding
## Build
```bash
./gradlew assembleDebug
./gradlew testDebugUnitTest
./gradlew lintDebug
```
The debug APK is written to `app/build/outputs/apk/debug/app-debug.apk`.
## First run
1. Install and open the app on an SMS-capable phone.
2. Open **Server → SMS Permissions** and grant Send SMS and Receive SMS. Grant notifications so the foreground server status remains visible.
3. Open **Security**, enter a private API key of at least 16 characters, and keep authentication enabled.
4. Optionally enable the exact-IP allowlist and add the backend's source IP.
5. Open **Server**, confirm the port and bind address, then save.
6. Return to **Dashboard** and start the server.
7. Call `GET /api/v1/health` with `Authorization: Bearer <key>`.
API keys are stored only as SHA-256 hashes. They cannot be recovered from the app, so keep the original key in the backend's secret store.
## Network configuration
The default endpoint is `0.0.0.0:8080`, which listens on all IPv4 interfaces. The dashboard shows a currently detected non-loopback IPv4 address. The port is validated in the range 1024–65535.
The MVP serves plaintext HTTP. HTTP does not encrypt messages or credentials and must only be used on a trusted network. For remote connections, place the phone behind a VPN or a TLS-capable reverse proxy and firewall the port. Do not expose an unauthenticated gateway to the public internet.
## Android behavior
- The HTTP server runs in a foreground service with a persistent notification.
- If Android stops the process, OS/device battery policies can affect recovery. Exempt the app from aggressive vendor battery optimization on dedicated gateway devices.
- Reboot startup works only when enabled in Server settings and when the server was enabled before reboot.
- Sent status means Android's SMS service accepted the submission; carrier delivery reports are not implemented yet.
- The MVP limits outgoing message bodies to 160 characters. Multipart SMS is planned separately.
## Troubleshooting
- **503 AUTHENTICATION_NOT_CONFIGURED:** set an API key in Security settings.
- **401 INVALID_API_KEY:** verify the backend secret and Bearer header.
- **403 IP_NOT_ALLOWED:** add the actual backend source IP or disable the allowlist temporarily.
- **SMS_PERMISSION_DENIED:** grant Send SMS from the Permissions screen.
- **Server start error:** choose an unused port and ensure the bind address exists on the device.
- **Backend cannot connect:** confirm both devices can route to each other and that Wi-Fi isolation/firewall rules permit the configured TCP port.
See [API.md](API.md), [SKILL.md](SKILL.md), [ARCHITECTURE.md](ARCHITECTURE.md), [SECURITY.md](SECURITY.md), and [openapi.yaml](openapi.yaml).
+46
View File
@@ -0,0 +1,46 @@
# Security
## MVP controls
- Authentication is enabled by default and blocks API access until a key is configured.
- API keys are accepted through Bearer authentication or `X-API-Key`.
- Only SHA-256 API-key hashes are stored; the original cannot be recovered.
- Hash comparison is constant-time.
- Exact IPv4 and IPv6 allowlisting can be enabled independently.
- Request bodies require `Content-Length` and are capped at 16 KiB.
- Phone numbers, message sizes, pagination, paths, ports, bind addresses, and IP entries are validated.
- Request logs contain only timestamp, method, path, status, client IP, duration, and success. Bodies and headers are never logged.
- Error responses do not expose stack traces or secrets.
- `/docs` and `/docs/openapi.yaml` are public and expose only the published API contract; operational API routes remain protected.
- Room backup is disabled to reduce accidental secret/configuration export.
- Server code has a top-level exception boundary so malformed requests do not crash the app.
## Plaintext HTTP warning
The embedded MVP server is HTTP-only. HTTP provides no confidentiality or server identity: API keys and SMS content can be observed or modified by anyone able to intercept traffic. Use it only on a trusted, isolated network. For remote operation, use a VPN or a controlled TLS reverse proxy, firewall the gateway port, and keep authentication and allowlisting enabled.
Port forwarding directly from the public internet is strongly discouraged for the MVP.
## Key management
- Use a randomly generated high-entropy value of at least 16 characters; 32+ is preferred.
- Store the backend copy in its secret manager or environment configuration.
- Never place keys in source control, URLs, query parameters, screenshots, or logs.
- Rotate a suspected key by setting a new value in the app and backend.
- Disabling authentication should be limited to temporary testing on an isolated network.
## Allowlist limitations
The MVP supports exact IP addresses only. It intentionally does not parse CIDR ranges. Source addresses can change due to DHCP, VPNs, proxies, or NAT. Verify the client address shown in request logs before enabling a strict allowlist.
## Planned security work
- HMAC over method, canonical path, body hash, timestamp, and nonce
- Short timestamp acceptance window
- Durable nonce/replay cache
- Credential identifiers and multiple API clients
- Rate limiting and lockout telemetry
- Native TLS-capable transport or formally documented reverse-proxy deployment
- CIDR-aware allowlists
Report vulnerabilities privately to the project maintainer and do not include real SMS content, API keys, or device identifiers in reports.
+81
View File
@@ -0,0 +1,81 @@
---
name: android-sms-gateway
description: Operate an Android SMS Gateway over its versioned HTTP API to check health or status, send SMS, and read incoming or outgoing message history. Use when a user wants to interact with a configured gateway; do not use for generic Android development or unrelated SMS providers.
---
# Android SMS Gateway
Use the directly reachable Android device as an HTTP SMS gateway. The gateway has no cloud relay, polling, FCM, or WebSocket connection.
Treat [openapi.yaml](openapi.yaml) as the authoritative contract. The installed gateway provides interactive documentation at `GET /docs` and serves the same packaged contract from `GET /docs/openapi.yaml`. Read either contract copy when exact schemas, parameters, or response codes matter; do not invent endpoints or fields.
## Connection
Obtain these values from the user or the active environment:
```text
GATEWAY_BASE_URL=http://192.168.1.50:8080
GATEWAY_API_KEY=<gateway API key>
```
Never print the API key, place it in a URL, or persist it in logs or generated artifacts. Send it with `Authorization: Bearer <key>`; `X-API-Key` is supported only when Bearer authentication is impractical.
Plain HTTP is unencrypted. Use the gateway only over a trusted LAN, VPN, or TLS-terminating proxy. Do not weaken authentication or allowlisting to work around connectivity problems unless the user explicitly requests the configuration change and understands the exposure.
## Workflow
1. Call `GET /api/v1/health` before other operations to verify reachability, device identity, API version, and uptime.
2. Call `GET /api/v1/status` when server state or counters are relevant.
3. Use `POST /api/v1/sms/send` only when the user has explicitly authorized the exact recipient and message. Sending an SMS is an external side effect.
4. Preserve the returned message ID. HTTP 202 means Android accepted the submission for processing, not that the carrier delivered it.
5. Use `GET /api/v1/sms/messages/{id}` to inspect the later local status.
6. Use the paginated messages endpoint to read history. Prefer `direction=incoming` when the user asks for received SMS.
Do not automatically retry a timed-out send. The gateway may have accepted it even if the response was lost, and this MVP has no idempotency key. Ask for confirmation or use application-level duplicate protection before retrying.
## Requests
Health:
```bash
curl --fail-with-body \
-H "Authorization: Bearer $GATEWAY_API_KEY" \
"$GATEWAY_BASE_URL/api/v1/health"
```
Send one SMS:
```bash
curl --fail-with-body \
-X POST \
-H "Authorization: Bearer $GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
--data '{"to":"+989121234567","message":"Hello"}' \
"$GATEWAY_BASE_URL/api/v1/sms/send"
```
Read incoming messages:
```bash
curl --fail-with-body \
-H "Authorization: Bearer $GATEWAY_API_KEY" \
"$GATEWAY_BASE_URL/api/v1/sms/messages?direction=incoming&page=1&page_size=50"
```
Read one message:
```bash
curl --fail-with-body \
-H "Authorization: Bearer $GATEWAY_API_KEY" \
"$GATEWAY_BASE_URL/api/v1/sms/messages/MESSAGE_ID"
```
## Interpret Results
- `pending`: waiting for Android's send result.
- `sent`: Android's SMS service accepted the operation; this is not a delivery report.
- `failed`: Android reported a failure; inspect `error_code`.
- Message timestamps are Unix epoch milliseconds. Health and status uptime is seconds.
- Error responses contain `success: false` and a stable `error.code`; branch on the code rather than the human-readable message.
For health and read operations, retry transient 5xx failures with bounded exponential backoff. Do not retry unchanged credentials after 401, an unchanged client address after 403, or SMS sends without duplicate protection.
Binary file not shown.

After

Width:  |  Height:  |  Size: 432 KiB

+683
View File
@@ -0,0 +1,683 @@
# Android SMS Gateway — UI/UX Design Handoff
## 1. Purpose
This document describes every user-facing surface currently implemented in Android SMS Gateway. It is intended to give the product design team enough functional context to redesign the experience without changing gateway behavior accidentally.
The product turns a dedicated Android phone into a directly reachable HTTP SMS gateway. The primary user is a technical operator who installs the app, grants SMS permissions, configures security/networking, starts the server, and monitors its health. The operator may revisit the app only when diagnosing a problem, rotating credentials, or reviewing messages and API traffic.
The visual design should communicate three things immediately:
1. Is the gateway operational?
2. Is it secure and reachable?
3. What happened most recently?
## 2. Current Surface Inventory
| Surface | Type | Primary purpose |
|---|---|---|
| Dashboard | Main navigation page | Monitor gateway status and start or stop the server |
| Messages — Incoming | Tab within Messages | Review SMS messages received by the phone |
| Messages — Outgoing | Tab within Messages | Review SMS messages submitted through the gateway |
| Request Logs | Main navigation page | Diagnose HTTP requests and failures |
| Server Settings | Main navigation page | Configure port, bind address, reboot behavior, and reach Permissions |
| Security Settings | Main navigation page | Configure API authentication and IP allowlisting |
| SMS Permissions | Secondary Android page | Review and request required Android permissions |
| API Documentation | Browser page at `/docs` | Interactive Swagger UI for backend developers |
| Foreground Notification | Android system notification | Keep the server alive and expose its live state/stop action |
There is no onboarding wizard, message-detail page, log-detail page, manual SMS composer, API-key reveal page, or dedicated About page in the current MVP.
## 3. Global Application Structure
### 3.1 Page headers
- Every primary page uses an in-content branded header with a mint message-gateway mark, page title, and uppercase contextual subtitle.
- Dashboard: **SMS Gateway / Operations console**
- Messages: **Messages / Live SMS activity**, with a Live badge
- Request Logs: **Request logs / HTTP traffic**, with a Live badge
- Server: **Server / Network configuration**
- Security: **Security / Access control**
- Permissions: **SMS permissions / Android access**, with a standard back arrow
- Headers remain intentionally free of accounts, avatars, and generic overflow actions because credentials belong to the gateway, not an end-user account.
### 3.2 Primary navigation
Five destinations appear in the bottom navigation bar:
1. Dashboard
2. Messages
3. Logs
4. Server
5. Security
The implementation uses clear outlined Material-style icons while keeping labels visible:
- Dashboard: dashboard, monitoring, or home icon
- Messages: chat/message icon
- Logs: receipt, list, or terminal-style icon
- Server: DNS/server/settings icon
- Security: shield/lock icon
The Permissions page is secondary. It is entered from Server Settings and temporarily replaces the bottom navigation with a back action.
### 3.3 Theme
- Material 3 with a fixed gateway design system matching the approved Figma file
- Light and dark themes follow the Android system setting.
- The palette is intentionally stable across Android devices instead of using dynamic wallpaper colors.
- Core roles include deep ink green, operational primary green, signal mint, network blue, and reserved warning/error colors.
- Status colors must remain understandable without relying only on color. Always combine color with text and/or an icon.
### 3.4 Loading state
At initial launch, the app preserves its shell and shows the gateway brand mark, an indeterminate progress indicator, and **Preparing gateway** while settings initialize. Stale server state is not shown as current.
### 3.5 Feedback
Short confirmations and validation errors appear as bottom snackbars. Existing messages include:
- `Port must be between 1024 and 65535`
- `Bind address must be a valid IP address`
- `Server settings saved`
- `API key must contain at least 16 characters`
- `API key updated`
- `Enter a valid IPv4 or IPv6 address`
- `Allowed IP added`
Errors should remain visible long enough to read and should identify the field that needs attention. Where possible, the redesign should also show errors inline beneath the affected input.
## 4. Dashboard
### 4.1 Goal
Give the operator a reliable at-a-glance answer about server health, reachability, traffic, SMS activity, and security readiness.
### 4.2 Content order
#### Server status card
Current content:
- Status indicator and text
- Device IP and configured port, formatted as `192.168.1.50:8080`
- Current-process uptime in `HH:MM:SS`
- Last server error, only when present
- Primary Start or Stop button
Server states that must be represented:
| State | Meaning | Expected action treatment |
|---|---|---|
| Stopped | No HTTP listener is running | Primary action: Start server |
| Starting | Start is in progress | Disable repeated start; show progress |
| Running | Server accepts connections | Primary/destructive action: Stop server |
| Stopping | Shutdown is in progress | Disable repeated stop; show progress |
| Error | Start/stop failed | Show readable error and offer Start/Retry when appropriate |
Implemented visual convention:
- Running uses the deep green hero card, a success badge, and a healthy check icon.
- Stopped uses a neutral surface and a clear **Start server** action.
- Starting and stopping use informational progress semantics and disable repeated actions.
- Error uses the reserved error palette and exposes a **Retry** action.
- The address has a copy action.
- A running gateway exposes **Open API docs**, which opens `http://<address>:<port>/docs`.
#### Metric cards
Three equal cards display lifetime local counts:
- Requests
- Sent
- Received
Definitions:
- Requests: persisted HTTP request log count.
- Sent: total outgoing records, including pending, sent, and failed submissions.
- Received: total incoming records.
The word **Sent** may imply successful delivery even though the value is currently total outgoing submissions. The design should use a less ambiguous label such as **Outgoing** unless product requirements change the metric.
#### Last request card
When a request exists:
- First line: HTTP method and path, for example `POST /api/v1/sms/send`
- Second line: status code, duration, and client IP, for example `202 · 42 ms · 192.168.1.10`
Empty state copy: **No requests yet**
Useful visual semantics:
- 2xx: success
- 4xx: client/authentication/configuration issue
- 5xx: gateway failure
- Method may be represented by a compact badge.
#### Security setup warning
Condition: authentication is enabled but no API key has been configured.
Current copy:
> Security setup required: configure an API key before connecting a backend.
This warning should be prominent and actionable. Recommended action: **Configure security**, deep-linking to Security Settings.
### 4.3 Dashboard states
The design must cover:
- First launch: stopped, zero metrics, no last request, API-key warning
- Running normally
- Starting and stopping
- Server error with a potentially long error string
- IP unavailable
- Large counters
- Long IPv6 address plus port
- Authentication intentionally disabled
- Server running while SMS permissions are missing
## 5. Messages
### 5.1 Goal
Allow the operator to inspect recent incoming and outgoing SMS activity efficiently, including sender/recipient, body, time, and status.
### 5.2 Shared structure
- Two tabs: **Incoming** and **Outgoing**
- A single-line Search field below the tabs
- Lazy scrolling list below Search
- Search text is limited to 100 characters
- Search is case-insensitive
- Up to the most recent 200 records of each direction are loaded into the current UI
The selected tab and search query survive ordinary Compose state recreation.
### 5.3 Incoming tab
Search matches:
- Sender address/phone number
- Message body
Each row contains:
- Sender, emphasized
- Status, currently `received`
- Message preview, maximum three lines
- Localized date and time
### 5.4 Outgoing tab
Search matches:
- Recipient address/phone number
- Message body
- Status
Each row contains:
- Recipient, emphasized
- Status: `pending`, `sent`, or `failed`
- Message preview, maximum three lines
- Localized date and time
Status meanings:
- Pending: submitted to Android and awaiting its send result
- Sent: Android accepted the SMS operation; not a carrier delivery receipt
- Failed: Android reported or threw a sending failure
### 5.5 Required list states
The implementation explicitly provides:
- No incoming messages yet
- No outgoing messages yet
- No results for the current search
- Loading or refreshing
- Very long phone number/address
- Very long or multiline body
- Failed outgoing message with error indication
### 5.6 Recommended row interaction
Rows are currently not clickable. If the design introduces a detail view, it should be specified as a future enhancement rather than assumed to exist. A useful detail page could expose:
- Full message body
- Full sender/recipient
- Direction and status
- Created/requested/updated timestamps
- Message UUID
- Failure code for outgoing messages
- Copy actions
Do not add reply, resend, delete, or manual-send controls without a product decision; these actions do not currently exist.
## 6. Request Logs
### 6.1 Goal
Help the operator diagnose backend connectivity, authentication failures, invalid requests, server errors, and response time.
### 6.2 Current row
Each log row contains:
- HTTP method and path, emphasized
- Status code
- Client IP address
- Duration in milliseconds
- Localized timestamp
Example:
```text
POST /api/v1/sms/send
202 · 192.168.1.10 · 42 ms
8/25/26, 10:30 AM
```
Logs intentionally never include:
- API keys
- Authorization headers
- Request bodies
- SMS bodies
- Secrets or credentials
The local database retains the newest 10,000 request logs; the current UI loads the newest 500.
### 6.3 Required states
- No API requests yet
- Continuous high-volume traffic
- Long paths
- IPv6 client address
- Slow request
- 401 authentication failure
- 403 allowlist rejection
- 4xx validation error
- 5xx server failure
### 6.4 Implemented log tools and future boundary
- Numeric status badges use success, warning, and error semantics.
- Filter chips are provided for All, Success, 4xx, and 5xx.
- Search matches request path, client IP, and HTTP method.
- A row detail sheet remains a future option and must expose only already-stored safe metadata.
- Never introduce request-header or body display into logs without a separate security review.
## 7. Server Settings
### 7.1 Goal
Configure how the embedded HTTP server listens and whether it returns after reboot.
### 7.2 Networking section
#### HTTP port
- Numeric input only
- Maximum five entered digits
- Valid range: 1024–65535
- Default: 8080
Invalid save feedback:
> Port must be between 1024 and 65535
The design should use a numeric keyboard and show the allowed range near the field.
#### Bind address
- Single-line text input
- Maximum 45 characters to accommodate IPv6
- Must be a valid IPv4 or IPv6 literal
- Default: `0.0.0.0`
- Supporting copy: **Use 0.0.0.0 to listen on all IPv4 interfaces**
Invalid save feedback:
> Bind address must be a valid IP address
This is an advanced field. Consider adding an explanation or presets:
- All IPv4 interfaces — `0.0.0.0`
- Local device only — `127.0.0.1`
- Custom address
Do not imply that a bind address creates routing, port forwarding, a public IP, or TLS.
#### Start server after device reboot
- Switch
- When enabled, the server is restored after Android boot only if it was enabled before reboot.
- Vendor battery-management policies may still interfere.
#### Save and apply
- Full-width primary action
- Saves port, bind address, and reboot preference
- If the server is running, it restarts automatically so the new network configuration takes effect
- Success snackbar: **Server settings saved**
The restart consequence should be communicated. For example: **Saving will briefly restart the running server.**
### 7.3 Android access section
- Section heading: **Android access**
- Outlined action: **Open permissions screen**
- Navigates to the dedicated SMS Permissions page
### 7.4 Security warning
Current copy:
> Unencrypted HTTP should only be exposed on a trusted private network. Use a VPN or TLS reverse proxy for remote access.
This warning must remain visible. It should not look like a recoverable field error; an informational warning treatment is more appropriate than generic destructive red.
## 8. Security Settings
### 8.1 Goal
Control gateway-level API authentication and restrict which client IP addresses may reach API operations.
### 8.2 Gateway authentication section
#### Require API key
- Switch
- Enabled by default
- Changes take effect for subsequent HTTP requests without restarting the server
Turning this switch off exposes operational API routes to any network client that can reach the server, subject only to the optional allowlist. The implementation requires explicit confirmation before disabling authentication.
#### API-key status
Current states:
- **API key: not configured**
- **API key: configured (hidden)**
The stored value is a one-way SHA-256 hash. The original key cannot be shown or recovered.
#### New API key
- Single-line password input
- Characters are visually masked
- Maximum 256 characters
- Minimum accepted length: 16 characters
- Primary action: **Set API key**
- Success snackbar: **API key updated**
Important UX behavior:
- Never reveal an existing key.
- Do not offer a fake “show existing key” action.
- Clearly state that changing the key immediately invalidates the backend's old key.
- Consider a confirmation step because key rotation can disconnect integrations.
### 8.3 IP allowlist section
#### Enable allowlist
- Switch
- When enabled, only exact configured IP addresses may access operational API routes
- Documentation routes remain public
- CIDR ranges are not supported in the MVP
Enabling an empty allowlist blocks every operational API client. The implementation warns and requires confirmation before allowing that locked state.
#### Add address
- Single-line IP input
- Maximum 45 characters
- Accepts valid IPv4 or IPv6 literals
- Compact **Add** action beside the field
- Duplicate values collapse into one stored entry
- Success snackbar: **Allowed IP added**
#### Allowed-address list
- Sorted addresses
- Each row displays the complete IP and a **Remove** text action
- Removal currently has no confirmation
Recommended design considerations:
- Make long IPv6 values wrap or scroll without colliding with Remove.
- Confirm removal when the list contains only one address and allowlisting is enabled.
- Explain that the API log's client IP is the value operators should usually add.
### 8.4 Security footer
Current copy explains:
- CIDR and HMAC are future capabilities.
- API keys and authentication headers are never written to request logs.
This content can become a compact “Security notes” informational card.
## 9. SMS Permissions
### 9.1 Entry and navigation
- Entered from Server Settings
- Top title becomes **SMS Permissions**
- Bottom navigation is hidden
- A text action returns to Server Settings: **Back to server settings**
The implementation uses a standard back arrow in the page header and retains Android system-back behavior.
### 9.2 Introductory copy
> Permissions are requested only when you choose to grant them. SMS permissions are required for gateway operation.
Permissions must never be requested automatically without user context.
### 9.3 Permission cards
Always shown:
- Send SMS
- Receive SMS
Shown on Android 13 and newer:
- Gateway notification
Each card contains:
- Permission label
- Status: **Granted** or **Required**
- **Grant** button only when missing
Functional meanings:
- Send SMS: required for `/api/v1/sms/send`
- Receive SMS: required to persist incoming messages
- Gateway notification: lets Android display the foreground server notification normally
### 9.4 Android settings action
- Full-width outlined button: **Open Android app settings**
- Opens the OS-level application details page
- Necessary when a permission has been permanently denied or must be changed manually
### 9.5 Required states
- All granted
- One missing
- All missing on first run
- Permission denied once
- Permission permanently denied / “Don't ask again”
- User returns from Android Settings with changed permission state
The current UI does not distinguish an ordinary denial from permanent denial. The redesign should reserve space for rationale and a direct Settings action when Android will no longer show the permission prompt.
## 10. API Documentation Web Page
### 10.1 Location
```text
http://<device-ip>:<port>/docs
```
### 10.2 Purpose
Provide backend developers with interactive API documentation directly from the gateway, even without internet access.
### 10.3 Current experience
- Locally bundled Swagger UI
- No external CDN dependency
- Loads the packaged OpenAPI document from `/docs/openapi.yaml`
- Search/filter field for operations
- Expandable endpoint documentation
- Schemas, examples, error responses, and status codes
- Authorization dialog for Bearer API key or `X-API-Key`
- “Try it out” sends requests to the same gateway origin by default
- Request duration is displayed
The documentation page and raw OpenAPI contract are public. Calling operational API endpoints still requires the configured authentication and allowlist.
### 10.4 Design constraints
- This surface is primarily desktop-browser oriented but should remain usable on mobile.
- It must work offline from the gateway APK.
- Do not add analytics, external fonts, CDN scripts, or external image dependencies.
- API keys entered into Swagger UI are not persisted across reloads.
- The API documentation should remain visually distinct from the Android operator UI unless a future branded documentation theme is deliberately introduced.
## 11. Foreground Server Notification
### 11.1 Purpose
Android requires a foreground notification for the long-running embedded server. This is an operational surface, not a marketing notification.
### 11.2 Current content
- Title: **SMS Gateway**
- Live content based on server state
- Running example: **Listening on 192.168.1.50:8080**
- Error state: latest server error
- Other states: Starting, Stopping, or Stopped
- Tapping the notification opens the app
- Action: **Stop**
- Notification is ongoing, low importance, and silent
The notification must remain compact, clear, and non-alarming. The Stop action is consequential and should be visually distinct, but Android notification actions do not support complex confirmation flows.
## 12. Cross-Screen State and Behavior
### 12.1 Live updates
These values update reactively while the app is open:
- Server state
- Settings
- Request count
- Incoming/outgoing counts
- Last request
- Recent incoming and outgoing messages
- Recent request logs
Designs should not require manual refresh for ordinary updates.
### 12.2 Persistence
Persisted across app/process restarts:
- Device ID
- Port and bind address
- Desired server-enabled state
- Reboot setting
- Authentication and API-key hash
- Allowlist state and entries
- Incoming/outgoing SMS history
- Request logs
Not persisted as user data:
- Current page selection
- Temporary API-key input
- Temporary IP-address input
- Snackbar messages
- Current-process uptime
The selected page, message tab, and search query currently survive ordinary UI state recreation but are not durable product settings.
## 13. Accessibility and Responsive Requirements
The redesign should meet these minimum expectations:
- Minimum 48 dp interactive targets
- Visible text labels for navigation and critical actions
- WCAG-appropriate contrast in light and dark themes
- Status communicated by icon/text as well as color
- Support increased Android font sizes without clipped actions or overlapping metric cards
- Support long localized strings
- Support IPv6 and long device/network values
- Screen-reader labels for icons and status indicators
- Logical focus and reading order
- Password field announced without exposing entered characters
- Reduced-motion-friendly progress indicators
- Layout usable from compact phones through tablets
The current three-metric horizontal row and five-item navigation bar are likely pressure points at large font scales and narrow widths. Designers should provide responsive alternatives.
## 14. Content and Terminology
Preferred consistent terms:
- **Gateway**: the Android device/app as a service
- **Server**: the embedded HTTP listener
- **Incoming**: SMS received by the phone
- **Outgoing**: SMS submitted for sending
- **Sent**: Android accepted the send operation, not carrier delivery
- **API key**: gateway credential
- **Allowlist**: permitted exact client IP addresses
- **Client IP**: source address recorded for an HTTP request
Avoid:
- Calling the API key a user password
- Claiming a sent SMS was delivered
- Implying plaintext HTTP is secure on the public internet
- Showing secrets, authorization headers, or SMS bodies in request logs
## 15. Recommended Design Deliverables
For a complete handoff back to engineering, provide:
1. Navigation map and screen hierarchy
2. Light and dark high-fidelity screens
3. Dashboard variants for all five server states
4. Empty, loading, populated, search-empty, and error states
5. Compact-phone, large-font, and tablet layouts
6. Component definitions for status badges, metric cards, message rows, log rows, setting rows, warnings, and permission cards
7. Confirmation dialogs for disabling authentication, rotating an API key, enabling an empty allowlist, and stopping the server if desired
8. Snackbar and inline-validation specifications
9. Icon set and accessibility labels
10. Motion/transition behavior where it improves state comprehension
## 16. Engineering Boundaries for the Redesign
The visual redesign may freely improve hierarchy, navigation presentation, components, typography, spacing, icons, empty states, and feedback. The following behavior should not change without explicit product/engineering agreement:
- Starting/stopping the foreground HTTP server
- Port range and bind-address validation
- Automatic restart after applying network settings while running
- API-key minimum length and one-way storage
- Exact-IP-only allowlisting
- Android permission request context
- Message and log privacy rules
- Meaning of pending/sent/failed
- Public offline API documentation and protected operational endpoints
- Trusted-network warning for plaintext HTTP
+104
View File
@@ -0,0 +1,104 @@
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.ksp)
alias(libs.plugins.kotlin.compose)
alias(libs.plugins.kotlin.serialization)
}
abstract class GenerateOpenApiAsset : DefaultTask() {
@get:InputFile
abstract val inputFile: RegularFileProperty
@get:OutputDirectory
abstract val outputDirectory: DirectoryProperty
@TaskAction
fun generate() {
val destination = outputDirectory.file("openapi.yaml").get().asFile
destination.parentFile.mkdirs()
inputFile.get().asFile.copyTo(destination, overwrite = true)
}
}
android {
namespace = "com.androidsmsgateway"
compileSdk {
version = release(37)
}
defaultConfig {
applicationId = "com.androidsmsgateway"
minSdk = 26
targetSdk = 37
versionCode = 1
versionName = "0.1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro",
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
buildFeatures {
buildConfig = true
compose = true
}
}
dependencies {
implementation(platform(libs.androidx.compose.bom))
implementation(libs.androidx.activity.compose)
implementation(libs.androidx.compose.material3)
implementation(libs.androidx.compose.material.icons.extended)
implementation(libs.androidx.compose.ui)
implementation(libs.androidx.compose.ui.tooling.preview)
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.androidx.lifecycle.viewmodel.compose)
implementation(libs.androidx.room.ktx)
implementation(libs.androidx.room.runtime)
implementation(libs.kotlinx.coroutines.android)
implementation(libs.kotlinx.serialization.json)
implementation(libs.nanohttpd)
implementation(libs.swagger.ui)
ksp(libs.androidx.room.compiler)
testImplementation(libs.junit)
testImplementation(libs.kotlinx.coroutines.test)
androidTestImplementation(libs.androidx.test.espresso.core)
androidTestImplementation(libs.androidx.test.junit)
debugImplementation(libs.androidx.compose.ui.tooling)
}
ksp {
arg("room.schemaLocation", "$projectDir/schemas")
}
val generateOpenApiAsset = tasks.register<GenerateOpenApiAsset>("generateOpenApiAsset") {
inputFile.set(rootProject.layout.projectDirectory.file("openapi.yaml"))
outputDirectory.set(layout.buildDirectory.dir("generated/openapiAssets"))
}
androidComponents {
onVariants { variant ->
variant.sources.assets?.addGeneratedSourceDirectory(
generateOpenApiAsset,
GenerateOpenApiAsset::outputDirectory,
)
}
}
+2
View File
@@ -0,0 +1,2 @@
# Project-specific R8 rules belong here when release shrinking is enabled.
@@ -0,0 +1,297 @@
{
"formatVersion": 1,
"database": {
"version": 1,
"identityHash": "50a812bbacc079987084d208ae9a1a5a",
"entities": [
{
"tableName": "incoming_sms",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `sender` TEXT NOT NULL, `message` TEXT NOT NULL, `receivedAt` INTEGER NOT NULL, `status` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, PRIMARY KEY(`id`))",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "sender",
"columnName": "sender",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "message",
"columnName": "message",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "receivedAt",
"columnName": "receivedAt",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "status",
"columnName": "status",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "createdAt",
"columnName": "createdAt",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_incoming_sms_receivedAt",
"unique": false,
"columnNames": [
"receivedAt"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_incoming_sms_receivedAt` ON `${TABLE_NAME}` (`receivedAt`)"
},
{
"name": "index_incoming_sms_sender",
"unique": false,
"columnNames": [
"sender"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_incoming_sms_sender` ON `${TABLE_NAME}` (`sender`)"
}
]
},
{
"tableName": "outgoing_sms",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `recipient` TEXT NOT NULL, `message` TEXT NOT NULL, `requestedAt` INTEGER NOT NULL, `status` TEXT NOT NULL, `errorCode` TEXT, `updatedAt` INTEGER NOT NULL, PRIMARY KEY(`id`))",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "recipient",
"columnName": "recipient",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "message",
"columnName": "message",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "requestedAt",
"columnName": "requestedAt",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "status",
"columnName": "status",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "errorCode",
"columnName": "errorCode",
"affinity": "TEXT"
},
{
"fieldPath": "updatedAt",
"columnName": "updatedAt",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_outgoing_sms_requestedAt",
"unique": false,
"columnNames": [
"requestedAt"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_outgoing_sms_requestedAt` ON `${TABLE_NAME}` (`requestedAt`)"
},
{
"name": "index_outgoing_sms_recipient",
"unique": false,
"columnNames": [
"recipient"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_outgoing_sms_recipient` ON `${TABLE_NAME}` (`recipient`)"
}
]
},
{
"tableName": "request_logs",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `timestamp` INTEGER NOT NULL, `method` TEXT NOT NULL, `path` TEXT NOT NULL, `statusCode` INTEGER NOT NULL, `clientIp` TEXT NOT NULL, `durationMs` INTEGER NOT NULL, `success` INTEGER NOT NULL)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "timestamp",
"columnName": "timestamp",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "method",
"columnName": "method",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "path",
"columnName": "path",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "statusCode",
"columnName": "statusCode",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "clientIp",
"columnName": "clientIp",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "durationMs",
"columnName": "durationMs",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "success",
"columnName": "success",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": true,
"columnNames": [
"id"
]
},
"indices": [
{
"name": "index_request_logs_timestamp",
"unique": false,
"columnNames": [
"timestamp"
],
"orders": [],
"createSql": "CREATE INDEX IF NOT EXISTS `index_request_logs_timestamp` ON `${TABLE_NAME}` (`timestamp`)"
}
]
},
{
"tableName": "app_settings",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `deviceId` TEXT NOT NULL, `port` INTEGER NOT NULL, `bindAddress` TEXT NOT NULL, `serverEnabled` INTEGER NOT NULL, `startOnBoot` INTEGER NOT NULL, `authenticationEnabled` INTEGER NOT NULL, `apiKeyHash` TEXT NOT NULL, `allowlistEnabled` INTEGER NOT NULL, `allowedIps` TEXT NOT NULL, PRIMARY KEY(`id`))",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "deviceId",
"columnName": "deviceId",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "port",
"columnName": "port",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "bindAddress",
"columnName": "bindAddress",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "serverEnabled",
"columnName": "serverEnabled",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "startOnBoot",
"columnName": "startOnBoot",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "authenticationEnabled",
"columnName": "authenticationEnabled",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "apiKeyHash",
"columnName": "apiKeyHash",
"affinity": "TEXT",
"notNull": true
},
{
"fieldPath": "allowlistEnabled",
"columnName": "allowlistEnabled",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "allowedIps",
"columnName": "allowedIps",
"affinity": "TEXT",
"notNull": true
}
],
"primaryKey": {
"autoGenerate": false,
"columnNames": [
"id"
]
}
}
],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '50a812bbacc079987084d208ae9a1a5a')"
]
}
}
@@ -0,0 +1,42 @@
package com.androidsmsgateway.data.local
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class GatewayDatabaseTest {
private lateinit var database: GatewayDatabase
private lateinit var dao: GatewayDao
@Before
fun createDatabase() {
database = Room.inMemoryDatabaseBuilder(ApplicationProvider.getApplicationContext(), GatewayDatabase::class.java)
.allowMainThreadQueries()
.build()
dao = database.gatewayDao()
}
@After
fun closeDatabase() = database.close()
@Test
fun incomingOutgoingSettingsAndLogsPersist() = runBlocking {
dao.insertIncoming(IncomingSmsEntity("in-1", "+12025550123", "hello", 10, "RECEIVED", 10))
dao.insertOutgoing(OutgoingSmsEntity("out-1", "+12025550124", "world", 20, "PENDING", updatedAt = 20))
dao.saveSettings(AppSettingsEntity(deviceId = "device-1"))
dao.insertRequestLog(RequestLogEntity(timestamp = 30, method = "GET", path = "/api/v1/health", statusCode = 200, clientIp = "127.0.0.1", durationMs = 2, success = true))
assertEquals("hello", dao.incomingById("in-1")?.message)
assertEquals("world", dao.outgoingById("out-1")?.message)
assertEquals("device-1", dao.settings()?.deviceId)
assertEquals(1L, dao.observeRequestCount().first())
}
}
@@ -0,0 +1,90 @@
package com.androidsmsgateway.server
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.androidsmsgateway.data.GatewayRepository
import com.androidsmsgateway.data.SettingsRepository
import com.androidsmsgateway.data.local.AppSettingsEntity
import com.androidsmsgateway.data.local.GatewayDatabase
import com.androidsmsgateway.domain.ServerSnapshot
import com.androidsmsgateway.domain.ServerState
import com.androidsmsgateway.sms.SmsSender
import com.androidsmsgateway.sms.SmsSubmission
import java.net.HttpURLConnection
import java.net.ServerSocket
import java.net.URL
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.flow.first
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class GatewayHttpServerIntegrationTest {
private lateinit var database: GatewayDatabase
private var server: GatewayHttpServer? = null
@Before
fun createDatabase() {
database = Room.inMemoryDatabaseBuilder(ApplicationProvider.getApplicationContext(), GatewayDatabase::class.java).build()
}
@After
fun tearDown() {
server?.stop()
database.close()
}
@Test
fun healthEndpointRunsThroughEmbeddedTransportAndIsLogged() = runBlocking {
val port = ServerSocket(0).use { it.localPort }
val dao = database.gatewayDao()
dao.saveSettings(
AppSettingsEntity(
deviceId = "integration-device",
port = port,
bindAddress = "127.0.0.1",
authenticationEnabled = false,
),
)
val gatewayRepository = GatewayRepository(dao)
val router = ApiRouter(
repository = gatewayRepository,
settingsRepository = SettingsRepository(dao),
smsSender = object : SmsSender {
override suspend fun send(recipient: String, message: String) = SmsSubmission("fake-id", "pending")
},
serverSnapshot = { ServerSnapshot(ServerState.RUNNING, System.currentTimeMillis(), "127.0.0.1", port) },
documentationProvider = PackagedApiDocumentationProvider(ApplicationProvider.getApplicationContext()),
)
server = GatewayHttpServer("127.0.0.1", port, router).also { it.start(5_000, false) }
val connection = URL("http://127.0.0.1:$port/api/v1/health").openConnection() as HttpURLConnection
connection.connectTimeout = 3_000
connection.readTimeout = 3_000
assertEquals(200, connection.responseCode)
val body = connection.inputStream.bufferedReader().use { it.readText() }
assertTrue(body.contains("integration-device"))
assertTrue(body.contains("\"status\":\"ok\""))
assertEquals(1L, dao.observeRequestCount().first())
val docs = URL("http://127.0.0.1:$port/docs").openConnection() as HttpURLConnection
assertEquals(200, docs.responseCode)
assertTrue(docs.contentType.startsWith("text/html"))
assertTrue(docs.inputStream.bufferedReader().use { it.readText() }.contains("swagger-ui"))
assertEquals(2L, dao.observeRequestCount().first())
val contract = URL("http://127.0.0.1:$port/docs/openapi.yaml").openConnection() as HttpURLConnection
assertEquals(200, contract.responseCode)
assertTrue(contract.inputStream.bufferedReader().use { it.readText() }.startsWith("openapi: 3.1.0"))
val swaggerBundle = URL("http://127.0.0.1:$port/docs/swagger-ui-bundle.js").openConnection() as HttpURLConnection
assertEquals(200, swaggerBundle.responseCode)
assertTrue(swaggerBundle.inputStream.bufferedReader().use { it.readText() }.contains("SwaggerUIBundle"))
assertEquals(4L, dao.observeRequestCount().first())
}
}
+64
View File
@@ -0,0 +1,64 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-feature android:name="android.hardware.telephony" android:required="true" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
<application
android:name=".GatewayApplication"
android:allowBackup="false"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@drawable/ic_gateway"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.AndroidSmsGateway">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".server.GatewayServerService"
android:exported="false"
android:foregroundServiceType="specialUse">
<property
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
android:value="embedded HTTP SMS gateway for user-managed backend connections" />
</service>
<receiver
android:name=".sms.IncomingSmsReceiver"
android:exported="true"
android:permission="android.permission.BROADCAST_SMS">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<receiver
android:name=".sms.SmsStatusReceiver"
android:exported="false" />
<receiver
android:name=".server.BootReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
@@ -0,0 +1,8 @@
package com.androidsmsgateway
import android.app.Application
import com.androidsmsgateway.di.AppContainer
class GatewayApplication : Application() {
val container: AppContainer by lazy { AppContainer(this) }
}
@@ -0,0 +1,16 @@
package com.androidsmsgateway
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
SmsGatewayApp()
}
}
}
@@ -0,0 +1,183 @@
package com.androidsmsgateway
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.ReceiptLong
import androidx.compose.material.icons.outlined.Dashboard
import androidx.compose.material.icons.outlined.Dns
import androidx.compose.material.icons.outlined.Security
import androidx.compose.material.icons.outlined.Sms
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationRail
import androidx.compose.material3.NavigationRailItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.androidsmsgateway.ui.GatewayViewModel
import com.androidsmsgateway.ui.components.BrandMark
import com.androidsmsgateway.ui.screens.DashboardScreen
import com.androidsmsgateway.ui.screens.LogsScreen
import com.androidsmsgateway.ui.screens.MessagesScreen
import com.androidsmsgateway.ui.screens.PermissionsScreen
import com.androidsmsgateway.ui.screens.SecurityScreen
import com.androidsmsgateway.ui.screens.ServerSettingsScreen
import com.androidsmsgateway.ui.theme.GatewayTheme
private enum class Screen(val label: String, val icon: ImageVector) {
DASHBOARD("Dashboard", Icons.Outlined.Dashboard),
MESSAGES("Messages", Icons.Outlined.Sms),
LOGS("Logs", Icons.AutoMirrored.Outlined.ReceiptLong),
SERVER("Server", Icons.Outlined.Dns),
SECURITY("Security", Icons.Outlined.Security),
PERMISSIONS("Permissions", Icons.Outlined.Security),
}
@Composable
fun SmsGatewayApp(viewModel: GatewayViewModel = viewModel()) {
val state by viewModel.state.collectAsState()
var screenName by rememberSaveable { mutableStateOf(Screen.DASHBOARD.name) }
val screen = Screen.valueOf(screenName)
val snackbar = remember { SnackbarHostState() }
BackHandler(enabled = screen == Screen.PERMISSIONS) {
screenName = Screen.SERVER.name
}
LaunchedEffect(state.message) {
state.message?.let {
snackbar.showSnackbar(it)
viewModel.clearMessage()
}
}
GatewayTheme {
BoxWithConstraints(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background)) {
val expanded = maxWidth >= 840.dp
Scaffold(
containerColor = MaterialTheme.colorScheme.background,
snackbarHost = { SnackbarHost(snackbar) },
bottomBar = {
if (!expanded && screen != Screen.PERMISSIONS) {
MobileNavigation(screen) { screenName = it.name }
}
},
) { contentPadding ->
Row(Modifier.fillMaxSize().padding(contentPadding)) {
if (expanded && screen != Screen.PERMISSIONS) {
TabletNavigation(screen) { screenName = it.name }
}
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.TopCenter) {
Box(Modifier.fillMaxSize().widthIn(max = 1180.dp)) {
if (state.loading) {
LoadingScreen()
} else {
when (screen) {
Screen.DASHBOARD -> DashboardScreen(
state = state,
expanded = expanded,
start = viewModel::startServer,
stop = viewModel::stopServer,
openSecurity = { screenName = Screen.SECURITY.name },
openPermissions = { screenName = Screen.PERMISSIONS.name },
)
Screen.MESSAGES -> MessagesScreen(state)
Screen.LOGS -> LogsScreen(state)
Screen.SERVER -> ServerSettingsScreen(
state = state,
save = viewModel::saveServerSettings,
permissions = { screenName = Screen.PERMISSIONS.name },
)
Screen.SECURITY -> SecurityScreen(state, viewModel)
Screen.PERMISSIONS -> PermissionsScreen(onBack = { screenName = Screen.SERVER.name })
}
}
}
}
}
}
}
}
}
@Composable
private fun MobileNavigation(selected: Screen, onSelect: (Screen) -> Unit) {
NavigationBar(containerColor = MaterialTheme.colorScheme.surface) {
Screen.entries.filter { it != Screen.PERMISSIONS }.forEach { item ->
NavigationBarItem(
selected = selected == item,
onClick = { onSelect(item) },
icon = { Icon(item.icon, contentDescription = null) },
label = {
Text(
text = item.label,
style = MaterialTheme.typography.labelSmall,
maxLines = 1,
softWrap = false,
overflow = TextOverflow.Ellipsis,
)
},
)
}
}
}
@Composable
private fun TabletNavigation(selected: Screen, onSelect: (Screen) -> Unit) {
NavigationRail(
modifier = Modifier.fillMaxHeight(),
containerColor = MaterialTheme.colorScheme.surface,
header = { Box(Modifier.padding(vertical = 22.dp)) { BrandMark(Modifier.size(42.dp)) } },
) {
Column(verticalArrangement = Arrangement.spacedBy(7.dp)) {
Screen.entries.filter { it != Screen.PERMISSIONS }.forEach { item ->
NavigationRailItem(
selected = selected == item,
onClick = { onSelect(item) },
icon = { Icon(item.icon, contentDescription = null) },
label = { Text(item.label) },
)
}
}
}
}
@Composable
private fun LoadingScreen() {
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(16.dp)) {
BrandMark(Modifier.size(52.dp))
CircularProgressIndicator()
Text("Preparing gateway", style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
}
@@ -0,0 +1,33 @@
package com.androidsmsgateway.data
import com.androidsmsgateway.data.local.GatewayDao
import com.androidsmsgateway.data.local.IncomingSmsEntity
import com.androidsmsgateway.data.local.OutgoingSmsEntity
import com.androidsmsgateway.data.local.RequestLogEntity
class GatewayRepository(private val dao: GatewayDao) {
fun incomingMessages(limit: Int = 200) = dao.observeIncoming(limit)
fun outgoingMessages(limit: Int = 200) = dao.observeOutgoing(limit)
fun requestLogs(limit: Int = 500) = dao.observeRequestLogs(limit)
fun incomingCount() = dao.observeIncomingCount()
fun outgoingCount() = dao.observeOutgoingCount()
fun requestCount() = dao.observeRequestCount()
fun lastRequest() = dao.observeLastRequest()
suspend fun saveIncoming(message: IncomingSmsEntity) = dao.insertIncoming(message)
suspend fun saveOutgoing(message: OutgoingSmsEntity) = dao.insertOutgoing(message)
suspend fun updateOutgoing(message: OutgoingSmsEntity) = dao.updateOutgoing(message)
suspend fun incomingById(id: String) = dao.incomingById(id)
suspend fun outgoingById(id: String) = dao.outgoingById(id)
suspend fun incomingPage(query: String, page: Int, size: Int) =
dao.incomingPage(query, size, (page - 1) * size)
suspend fun outgoingPage(query: String, page: Int, size: Int) =
dao.outgoingPage(query, size, (page - 1) * size)
suspend fun messagePage(direction: String, query: String, page: Int, size: Int) =
dao.messagePage(direction, query, size, (page - 1) * size)
suspend fun logRequest(log: RequestLogEntity) {
dao.insertRequestLog(log)
dao.trimRequestLogs(10_000)
}
}
@@ -0,0 +1,31 @@
package com.androidsmsgateway.data
import com.androidsmsgateway.data.local.AppSettingsEntity
import com.androidsmsgateway.data.local.GatewayDao
import com.androidsmsgateway.domain.GatewaySettings
import com.androidsmsgateway.domain.toDomain
import java.util.UUID
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.map
class SettingsRepository(private val dao: GatewayDao) {
val settings: Flow<GatewaySettings> = dao.observeSettings().filterNotNull().map { it.toDomain() }
suspend fun ensureInitialized(): GatewaySettings {
val existing = dao.settings()
if (existing != null) return existing.toDomain()
val created = AppSettingsEntity(deviceId = UUID.randomUUID().toString())
dao.saveSettings(created)
return created.toDomain()
}
suspend fun current(): GatewaySettings = ensureInitialized()
suspend fun update(transform: (AppSettingsEntity) -> AppSettingsEntity): GatewaySettings {
val current = dao.settings() ?: AppSettingsEntity(deviceId = UUID.randomUUID().toString())
val updated = transform(current)
dao.saveSettings(updated)
return updated.toDomain()
}
}
@@ -0,0 +1,68 @@
package com.androidsmsgateway.data.local
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
@Entity(tableName = "incoming_sms", indices = [Index("receivedAt"), Index("sender")])
data class IncomingSmsEntity(
@PrimaryKey val id: String,
val sender: String,
val message: String,
val receivedAt: Long,
val status: String,
val createdAt: Long,
)
@Entity(tableName = "outgoing_sms", indices = [Index("requestedAt"), Index("recipient")])
data class OutgoingSmsEntity(
@PrimaryKey val id: String,
val recipient: String,
val message: String,
val requestedAt: Long,
val status: String,
val errorCode: String? = null,
val updatedAt: Long,
)
@Entity(tableName = "request_logs", indices = [Index("timestamp")])
data class RequestLogEntity(
@PrimaryKey(autoGenerate = true) val id: Long = 0,
val timestamp: Long,
val method: String,
val path: String,
val statusCode: Int,
val clientIp: String,
val durationMs: Long,
val success: Boolean,
)
@Entity(tableName = "app_settings")
data class AppSettingsEntity(
@PrimaryKey val id: Int = SINGLETON_ID,
val deviceId: String,
val port: Int = DEFAULT_PORT,
val bindAddress: String = DEFAULT_BIND_ADDRESS,
val serverEnabled: Boolean = false,
val startOnBoot: Boolean = false,
val authenticationEnabled: Boolean = true,
val apiKeyHash: String = "",
val allowlistEnabled: Boolean = false,
val allowedIps: String = "",
) {
companion object {
const val SINGLETON_ID = 1
const val DEFAULT_PORT = 8080
const val DEFAULT_BIND_ADDRESS = "0.0.0.0"
}
}
data class MessageRecord(
val id: String,
val direction: String,
val address: String,
val message: String,
val timestamp: Long,
val status: String,
val errorCode: String?,
)
@@ -0,0 +1,81 @@
package com.androidsmsgateway.data.local
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import kotlinx.coroutines.flow.Flow
@Dao
interface GatewayDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertIncoming(message: IncomingSmsEntity)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertOutgoing(message: OutgoingSmsEntity)
@Update
suspend fun updateOutgoing(message: OutgoingSmsEntity)
@Query("SELECT * FROM incoming_sms WHERE id = :id")
suspend fun incomingById(id: String): IncomingSmsEntity?
@Query("SELECT * FROM outgoing_sms WHERE id = :id")
suspend fun outgoingById(id: String): OutgoingSmsEntity?
@Query("SELECT * FROM incoming_sms WHERE (:query = '' OR sender LIKE '%' || :query || '%' OR message LIKE '%' || :query || '%') ORDER BY receivedAt DESC LIMIT :limit OFFSET :offset")
suspend fun incomingPage(query: String, limit: Int, offset: Int): List<IncomingSmsEntity>
@Query("SELECT * FROM outgoing_sms WHERE (:query = '' OR recipient LIKE '%' || :query || '%' OR message LIKE '%' || :query || '%' OR status LIKE '%' || :query || '%') ORDER BY requestedAt DESC LIMIT :limit OFFSET :offset")
suspend fun outgoingPage(query: String, limit: Int, offset: Int): List<OutgoingSmsEntity>
@Query("""
SELECT * FROM (
SELECT id, 'incoming' AS direction, sender AS address, message, receivedAt AS timestamp, status, NULL AS errorCode FROM incoming_sms
UNION ALL
SELECT id, 'outgoing' AS direction, recipient AS address, message, requestedAt AS timestamp, status, errorCode FROM outgoing_sms
)
WHERE (:direction = 'all' OR direction = :direction)
AND (:query = '' OR address LIKE '%' || :query || '%' OR message LIKE '%' || :query || '%' OR status LIKE '%' || :query || '%')
ORDER BY timestamp DESC
LIMIT :limit OFFSET :offset
""")
suspend fun messagePage(direction: String, query: String, limit: Int, offset: Int): List<MessageRecord>
@Query("SELECT * FROM incoming_sms ORDER BY receivedAt DESC LIMIT :limit")
fun observeIncoming(limit: Int): Flow<List<IncomingSmsEntity>>
@Query("SELECT * FROM outgoing_sms ORDER BY requestedAt DESC LIMIT :limit")
fun observeOutgoing(limit: Int): Flow<List<OutgoingSmsEntity>>
@Query("SELECT COUNT(*) FROM incoming_sms")
fun observeIncomingCount(): Flow<Long>
@Query("SELECT COUNT(*) FROM outgoing_sms")
fun observeOutgoingCount(): Flow<Long>
@Insert
suspend fun insertRequestLog(log: RequestLogEntity)
@Query("SELECT * FROM request_logs ORDER BY timestamp DESC LIMIT :limit")
fun observeRequestLogs(limit: Int): Flow<List<RequestLogEntity>>
@Query("SELECT COUNT(*) FROM request_logs")
fun observeRequestCount(): Flow<Long>
@Query("SELECT * FROM request_logs ORDER BY timestamp DESC LIMIT 1")
fun observeLastRequest(): Flow<RequestLogEntity?>
@Query("DELETE FROM request_logs WHERE id NOT IN (SELECT id FROM request_logs ORDER BY timestamp DESC LIMIT :keep)")
suspend fun trimRequestLogs(keep: Int)
@Query("SELECT * FROM app_settings WHERE id = 1")
fun observeSettings(): Flow<AppSettingsEntity?>
@Query("SELECT * FROM app_settings WHERE id = 1")
suspend fun settings(): AppSettingsEntity?
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun saveSettings(settings: AppSettingsEntity)
}
@@ -0,0 +1,19 @@
package com.androidsmsgateway.data.local
import androidx.room.Database
import androidx.room.RoomDatabase
@Database(
entities = [
IncomingSmsEntity::class,
OutgoingSmsEntity::class,
RequestLogEntity::class,
AppSettingsEntity::class,
],
version = 1,
exportSchema = true,
)
abstract class GatewayDatabase : RoomDatabase() {
abstract fun gatewayDao(): GatewayDao
}
@@ -0,0 +1,20 @@
package com.androidsmsgateway.di
import android.content.Context
import androidx.room.Room
import com.androidsmsgateway.data.GatewayRepository
import com.androidsmsgateway.data.SettingsRepository
import com.androidsmsgateway.data.local.GatewayDatabase
import com.androidsmsgateway.server.GatewayServerController
import com.androidsmsgateway.sms.AndroidSmsSender
class AppContainer(context: Context) {
val database: GatewayDatabase by lazy {
Room.databaseBuilder(context, GatewayDatabase::class.java, "sms-gateway.db").build()
}
val gatewayRepository: GatewayRepository by lazy { GatewayRepository(database.gatewayDao()) }
val settingsRepository: SettingsRepository by lazy { SettingsRepository(database.gatewayDao()) }
val smsSender by lazy { AndroidSmsSender(context.applicationContext, gatewayRepository) }
val serverController by lazy { GatewayServerController(context.applicationContext, settingsRepository, gatewayRepository, smsSender) }
}
@@ -0,0 +1,53 @@
package com.androidsmsgateway.domain
import com.androidsmsgateway.data.local.AppSettingsEntity
import kotlinx.serialization.Serializable
enum class MessageDirection { INCOMING, OUTGOING }
enum class MessageStatus { RECEIVED, PENDING, SENT, FAILED }
enum class ServerState { STOPPED, STARTING, RUNNING, STOPPING, ERROR }
data class ServerSnapshot(
val state: ServerState = ServerState.STOPPED,
val startedAt: Long? = null,
val ipAddress: String = "Unavailable",
val port: Int = AppSettingsEntity.DEFAULT_PORT,
val lastError: String? = null,
) {
fun uptimeMillis(now: Long = System.currentTimeMillis()): Long =
startedAt?.let { (now - it).coerceAtLeast(0) } ?: 0
}
@Serializable
data class ErrorBody(val code: String, val message: String)
@Serializable
data class ErrorResponse(val success: Boolean = false, val error: ErrorBody)
@Serializable
data class SuccessResponse<T>(val success: Boolean = true, val data: T)
data class GatewaySettings(
val deviceId: String,
val port: Int,
val bindAddress: String,
val serverEnabled: Boolean,
val startOnBoot: Boolean,
val authenticationEnabled: Boolean,
val apiKeyHash: String,
val allowlistEnabled: Boolean,
val allowedIps: Set<String>,
)
fun AppSettingsEntity.toDomain() = GatewaySettings(
deviceId = deviceId,
port = port,
bindAddress = bindAddress,
serverEnabled = serverEnabled,
startOnBoot = startOnBoot,
authenticationEnabled = authenticationEnabled,
apiKeyHash = apiKeyHash,
allowlistEnabled = allowlistEnabled,
allowedIps = allowedIps.lineSequence().map(String::trim).filter(String::isNotEmpty).toSet(),
)
@@ -0,0 +1,46 @@
package com.androidsmsgateway.security
import com.androidsmsgateway.domain.GatewaySettings
import java.net.InetAddress
import java.security.MessageDigest
enum class AccessDecision { ALLOWED, IP_DENIED, MISSING_CREDENTIALS, INVALID_CREDENTIALS, NOT_CONFIGURED }
object SecurityPolicy {
fun evaluate(settings: GatewaySettings, clientIp: String, headers: Map<String, String>): AccessDecision {
val normalizedIp = normalizeIp(clientIp)
if (settings.allowlistEnabled && normalizedIp !in settings.allowedIps.map(::normalizeIp)) {
return AccessDecision.IP_DENIED
}
if (!settings.authenticationEnabled) return AccessDecision.ALLOWED
if (settings.apiKeyHash.isBlank()) return AccessDecision.NOT_CONFIGURED
val authorization = headers.entries.firstOrNull { it.key.equals("authorization", true) }?.value
val headerKey = headers.entries.firstOrNull { it.key.equals("x-api-key", true) }?.value
val apiKey = authorization?.takeIf { it.startsWith("Bearer ", true) }?.substringAfter(' ') ?: headerKey
if (apiKey.isNullOrBlank()) return AccessDecision.MISSING_CREDENTIALS
return if (constantTimeEquals(settings.apiKeyHash, hashApiKey(apiKey))) {
AccessDecision.ALLOWED
} else {
AccessDecision.INVALID_CREDENTIALS
}
}
fun hashApiKey(apiKey: String): String = MessageDigest.getInstance("SHA-256")
.digest(apiKey.toByteArray(Charsets.UTF_8))
.joinToString("") { "%02x".format(it) }
fun isValidIp(value: String): Boolean {
val candidate = value.trim()
if (candidate.isEmpty() || candidate.any { it !in "0123456789abcdefABCDEF:." }) return false
return runCatching { InetAddress.getByName(candidate) }.isSuccess
}
private fun normalizeIp(value: String): String = runCatching {
InetAddress.getByName(value.substringBefore('%')).hostAddress
}.getOrDefault(value.trim())
private fun constantTimeEquals(expected: String, actual: String): Boolean =
MessageDigest.isEqual(expected.toByteArray(), actual.toByteArray())
}
@@ -0,0 +1,60 @@
package com.androidsmsgateway.server
import android.content.Context
interface ApiDocumentationProvider {
fun openApi(): String
fun indexHtml(): String
fun initializerJavaScript(): String
fun swaggerUiAsset(name: String): String
}
class PackagedApiDocumentationProvider(private val context: Context) : ApiDocumentationProvider {
override fun openApi(): String = context.assets.open("openapi.yaml").bufferedReader().use { it.readText() }
override fun indexHtml(): String = """
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="referrer" content="no-referrer">
<title>Android SMS Gateway API</title>
<link rel="stylesheet" href="/docs/swagger-ui.css">
</head>
<body>
<div id="swagger-ui"></div>
<script src="/docs/swagger-ui-bundle.js"></script>
<script src="/docs/swagger-initializer.js"></script>
</body>
</html>
""".trimIndent()
override fun initializerJavaScript(): String = """
window.onload = function () {
window.ui = SwaggerUIBundle({
url: "/docs/openapi.yaml",
dom_id: "#swagger-ui",
deepLinking: true,
displayRequestDuration: true,
filter: true,
persistAuthorization: false,
presets: [SwaggerUIBundle.presets.apis],
layout: "BaseLayout"
});
};
""".trimIndent()
override fun swaggerUiAsset(name: String): String {
require(name in ALLOWED_ASSETS) { "Unsupported documentation asset" }
val path = "META-INF/resources/webjars/swagger-ui/$SWAGGER_UI_VERSION/$name"
val stream = javaClass.classLoader?.getResourceAsStream(path)
?: error("Packaged Swagger UI asset is missing: $name")
return stream.bufferedReader().use { it.readText() }
}
companion object {
private const val SWAGGER_UI_VERSION = "5.32.1"
private val ALLOWED_ASSETS = setOf("swagger-ui.css", "swagger-ui-bundle.js")
}
}
@@ -0,0 +1,66 @@
package com.androidsmsgateway.server
import kotlinx.serialization.Serializable
@Serializable
data class ApiInfoResponse(
val api_version: String = "v1",
val gateway_version: String,
val capabilities: List<String>,
val endpoints: List<String>,
)
@Serializable
data class HealthResponse(
val status: String,
val device_id: String,
val app_version: String,
val android_version: String,
val device_model: String,
val ip: String,
val port: Int,
val uptime: Long,
)
@Serializable
data class SendSmsRequest(val to: String = "", val message: String = "")
@Serializable
data class SendSmsResponse(
val success: Boolean,
val id: String,
val status: String,
)
@Serializable
data class ApiMessage(
val id: String,
val direction: String,
val sender: String? = null,
val recipient: String? = null,
val message: String,
val timestamp: Long,
val status: String,
val error_code: String? = null,
)
@Serializable
data class MessagePage(
val success: Boolean = true,
val page: Int,
val page_size: Int,
val messages: List<ApiMessage>,
)
@Serializable
data class StatusResponse(
val success: Boolean = true,
val server_status: String,
val ip: String,
val port: Int,
val uptime: Long,
val requests: Long,
val sent_sms: Long,
val received_sms: Long,
)
@@ -0,0 +1,231 @@
package com.androidsmsgateway.server
import android.os.Build
import com.androidsmsgateway.BuildConfig
import com.androidsmsgateway.data.GatewayRepository
import com.androidsmsgateway.data.SettingsRepository
import com.androidsmsgateway.data.local.RequestLogEntity
import com.androidsmsgateway.domain.ErrorBody
import com.androidsmsgateway.domain.ErrorResponse
import com.androidsmsgateway.domain.ServerSnapshot
import com.androidsmsgateway.security.AccessDecision
import com.androidsmsgateway.security.SecurityPolicy
import com.androidsmsgateway.sms.SmsSender
import com.androidsmsgateway.sms.SmsSubmissionException
import fi.iki.elonen.NanoHTTPD
import kotlinx.coroutines.flow.first
import kotlinx.serialization.SerializationException
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
class ApiRouter(
private val repository: GatewayRepository,
private val settingsRepository: SettingsRepository,
private val smsSender: SmsSender,
private val serverSnapshot: () -> ServerSnapshot,
private val documentationProvider: ApiDocumentationProvider,
) {
private val json = Json { ignoreUnknownKeys = false; explicitNulls = false; encodeDefaults = true }
suspend fun route(session: NanoHTTPD.IHTTPSession): ApiResult {
val started = System.nanoTime()
val method = session.method.name
val path = session.uri.substringBefore('?')
val clientIp = session.remoteIpAddress ?: "unknown"
var result = ApiResult(500, error("INTERNAL_ERROR", "The request could not be completed"))
try {
if (path == DOCS_PATH || path.startsWith("$DOCS_PATH/")) {
result = dispatch(session, path)
return result
}
if (!path.startsWith("/api/v1")) {
result = ApiResult(404, error("NOT_FOUND", "Endpoint not found"))
return result
}
val settings = settingsRepository.current()
result = when (SecurityPolicy.evaluate(settings, clientIp, session.headers)) {
AccessDecision.ALLOWED -> dispatch(session, path)
AccessDecision.IP_DENIED -> ApiResult(403, error("IP_NOT_ALLOWED", "Client IP is not allowed"))
AccessDecision.MISSING_CREDENTIALS -> ApiResult(401, error("AUTHENTICATION_REQUIRED", "API credentials are required"))
AccessDecision.INVALID_CREDENTIALS -> ApiResult(401, error("INVALID_API_KEY", "API credentials are invalid"))
AccessDecision.NOT_CONFIGURED -> ApiResult(503, error("AUTHENTICATION_NOT_CONFIGURED", "Set an API key in the app before using the API"))
}
return result
} catch (_: SerializationException) {
result = ApiResult(400, error("INVALID_JSON", "Request body must be valid JSON"))
return result
} catch (exception: SmsSubmissionException) {
result = ApiResult(503, error(exception.code, exception.message))
return result
} catch (_: Exception) {
result = ApiResult(500, error("INTERNAL_ERROR", "The request could not be completed"))
return result
} finally {
val durationMs = (System.nanoTime() - started) / 1_000_000
runCatching {
repository.logRequest(
RequestLogEntity(
timestamp = System.currentTimeMillis(),
method = method,
path = path.take(512),
statusCode = result.status,
clientIp = clientIp.take(128),
durationMs = durationMs,
success = result.status in 200..299,
),
)
}
}
}
private suspend fun dispatch(session: NanoHTTPD.IHTTPSession, path: String): ApiResult {
return when {
session.method == NanoHTTPD.Method.GET && path in setOf(DOCS_PATH, "$DOCS_PATH/") ->
ApiResult(
200,
documentationProvider.indexHtml(),
"text/html; charset=utf-8",
mapOf(
"Content-Security-Policy" to "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:",
"Referrer-Policy" to "no-referrer",
),
)
session.method == NanoHTTPD.Method.GET && path == OPENAPI_PATH ->
ApiResult(200, documentationProvider.openApi(), "application/yaml; charset=utf-8")
session.method == NanoHTTPD.Method.GET && path == SWAGGER_CSS_PATH ->
ApiResult(200, documentationProvider.swaggerUiAsset("swagger-ui.css"), "text/css; charset=utf-8")
session.method == NanoHTTPD.Method.GET && path == SWAGGER_BUNDLE_PATH ->
ApiResult(200, documentationProvider.swaggerUiAsset("swagger-ui-bundle.js"), "application/javascript; charset=utf-8")
session.method == NanoHTTPD.Method.GET && path == SWAGGER_INITIALIZER_PATH ->
ApiResult(200, documentationProvider.initializerJavaScript(), "application/javascript; charset=utf-8")
session.method == NanoHTTPD.Method.GET && path == "/api/v1" -> apiInfo()
session.method == NanoHTTPD.Method.GET && path == "/api/v1/health" -> health()
session.method == NanoHTTPD.Method.GET && path == "/api/v1/status" -> status()
session.method == NanoHTTPD.Method.POST && path == "/api/v1/sms/send" -> sendSms(session)
session.method == NanoHTTPD.Method.GET && path == "/api/v1/sms/messages" -> listMessages(session)
session.method == NanoHTTPD.Method.GET && path.startsWith("/api/v1/sms/messages/") ->
messageDetails(path.substringAfterLast('/'))
path in KNOWN_PATHS -> ApiResult(405, error("METHOD_NOT_ALLOWED", "HTTP method is not allowed for this endpoint"))
else -> ApiResult(404, error("NOT_FOUND", "Endpoint not found"))
}
}
private fun apiInfo() = ApiResult(
200,
json.encodeToString(
ApiInfoResponse(
gateway_version = BuildConfig.VERSION_NAME,
capabilities = listOf("health", "status", "send_sms", "receive_sms", "message_history", "api_key", "ip_allowlist"),
endpoints = KNOWN_PATHS.sorted(),
),
),
)
private suspend fun health(): ApiResult {
val settings = settingsRepository.current()
val snapshot = serverSnapshot()
return ApiResult(
200,
json.encodeToString(
HealthResponse(
status = "ok",
device_id = settings.deviceId,
app_version = BuildConfig.VERSION_NAME,
android_version = Build.VERSION.RELEASE,
device_model = "${Build.MANUFACTURER} ${Build.MODEL}".trim(),
ip = snapshot.ipAddress,
port = snapshot.port,
uptime = snapshot.uptimeMillis() / 1000,
),
),
)
}
private suspend fun status(): ApiResult {
val snapshot = serverSnapshot()
return ApiResult(
200,
json.encodeToString(
StatusResponse(
server_status = snapshot.state.name.lowercase(),
ip = snapshot.ipAddress,
port = snapshot.port,
uptime = snapshot.uptimeMillis() / 1000,
requests = repository.requestCount().first(),
sent_sms = repository.outgoingCount().first(),
received_sms = repository.incomingCount().first(),
),
),
)
}
private suspend fun sendSms(session: NanoHTTPD.IHTTPSession): ApiResult {
val length = session.headers["content-length"]?.toLongOrNull()
if (length == null) return ApiResult(411, error("LENGTH_REQUIRED", "Content-Length is required"))
if (length > MAX_BODY_BYTES) return ApiResult(413, error("PAYLOAD_TOO_LARGE", "Request body exceeds $MAX_BODY_BYTES bytes"))
val files = mutableMapOf<String, String>()
session.parseBody(files)
val body = files["postData"] ?: ""
if (body.toByteArray().size > MAX_BODY_BYTES) return ApiResult(413, error("PAYLOAD_TOO_LARGE", "Request body exceeds $MAX_BODY_BYTES bytes"))
val request = json.decodeFromString<SendSmsRequest>(body)
if (!PHONE_REGEX.matches(request.to.trim())) return ApiResult(422, error("INVALID_RECIPIENT", "Recipient phone number is invalid"))
if (request.message.isBlank()) return ApiResult(422, error("EMPTY_MESSAGE", "Message must not be empty"))
if (request.message.length > MAX_SMS_CHARACTERS) return ApiResult(422, error("MESSAGE_TOO_LONG", "MVP messages are limited to $MAX_SMS_CHARACTERS characters"))
val submission = smsSender.send(request.to.trim(), request.message)
return ApiResult(202, json.encodeToString(SendSmsResponse(true, submission.id, submission.status)))
}
private suspend fun listMessages(session: NanoHTTPD.IHTTPSession): ApiResult {
val page = session.parameters["page"]?.firstOrNull()?.toIntOrNull()?.coerceAtLeast(1) ?: 1
val pageSize = session.parameters["page_size"]?.firstOrNull()?.toIntOrNull()?.coerceIn(1, 100) ?: 50
val query = session.parameters["search"]?.firstOrNull()?.trim()?.take(200).orEmpty()
val direction = session.parameters["direction"]?.firstOrNull()?.lowercase() ?: "all"
if (direction !in setOf("all", "incoming", "outgoing")) return ApiResult(422, error("INVALID_DIRECTION", "Direction must be all, incoming, or outgoing"))
val messages = repository.messagePage(direction, query, page, pageSize).map {
ApiMessage(
id = it.id,
direction = it.direction,
sender = it.address.takeIf { _ -> it.direction == "incoming" },
recipient = it.address.takeIf { _ -> it.direction == "outgoing" },
message = it.message,
timestamp = it.timestamp,
status = it.status.lowercase(),
error_code = it.errorCode,
)
}
return ApiResult(200, json.encodeToString(MessagePage(page = page, page_size = pageSize, messages = messages)))
}
private suspend fun messageDetails(id: String): ApiResult {
if (id.length !in 1..100) return ApiResult(404, error("MESSAGE_NOT_FOUND", "Message was not found"))
val incoming = repository.incomingById(id)
val message = incoming?.let {
ApiMessage(it.id, "incoming", sender = it.sender, message = it.message, timestamp = it.receivedAt, status = it.status.lowercase())
} ?: repository.outgoingById(id)?.let {
ApiMessage(it.id, "outgoing", recipient = it.recipient, message = it.message, timestamp = it.requestedAt, status = it.status.lowercase(), error_code = it.errorCode)
} ?: return ApiResult(404, error("MESSAGE_NOT_FOUND", "Message was not found"))
return ApiResult(200, json.encodeToString(message))
}
private fun error(code: String, message: String): String = json.encodeToString(ErrorResponse(error = ErrorBody(code, message)))
companion object {
const val MAX_BODY_BYTES = 16_384L
const val MAX_SMS_CHARACTERS = 160
val PHONE_REGEX = Regex("^\\+?[0-9]{3,20}$")
const val DOCS_PATH = "/docs"
const val OPENAPI_PATH = "/docs/openapi.yaml"
const val SWAGGER_CSS_PATH = "/docs/swagger-ui.css"
const val SWAGGER_BUNDLE_PATH = "/docs/swagger-ui-bundle.js"
const val SWAGGER_INITIALIZER_PATH = "/docs/swagger-initializer.js"
val KNOWN_PATHS = setOf(DOCS_PATH, OPENAPI_PATH, "/api/v1", "/api/v1/health", "/api/v1/status", "/api/v1/sms/send", "/api/v1/sms/messages")
}
}
data class ApiResult(
val status: Int,
val body: String,
val contentType: String = "application/json; charset=utf-8",
val headers: Map<String, String> = emptyMap(),
)
@@ -0,0 +1,33 @@
package com.androidsmsgateway.server
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import androidx.core.content.ContextCompat
import com.androidsmsgateway.GatewayApplication
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class BootReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action != Intent.ACTION_BOOT_COMPLETED) return
val pendingResult = goAsync()
val settingsRepository = (context.applicationContext as GatewayApplication).container.settingsRepository
CoroutineScope(Dispatchers.IO).launch {
try {
runCatching {
val settings = settingsRepository.current()
if (settings.startOnBoot && settings.serverEnabled) {
ContextCompat.startForegroundService(
context,
Intent(context, GatewayServerService::class.java).setAction(GatewayServerService.ACTION_START),
)
}
}
} finally {
pendingResult.finish()
}
}
}
}
@@ -0,0 +1,21 @@
package com.androidsmsgateway.server
import fi.iki.elonen.NanoHTTPD
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
class GatewayHttpServer(
bindAddress: String,
port: Int,
private val router: ApiRouter,
) : NanoHTTPD(bindAddress, port) {
override fun serve(session: IHTTPSession): Response {
val result = runBlocking(Dispatchers.IO) { router.route(session) }
val status = Response.Status.lookup(result.status) ?: Response.Status.INTERNAL_ERROR
return newFixedLengthResponse(status, result.contentType, result.body).apply {
addHeader("Cache-Control", "no-store")
addHeader("X-Content-Type-Options", "nosniff")
result.headers.forEach(::addHeader)
}
}
}
@@ -0,0 +1,85 @@
package com.androidsmsgateway.server
import android.content.Context
import com.androidsmsgateway.data.GatewayRepository
import com.androidsmsgateway.data.SettingsRepository
import com.androidsmsgateway.domain.ServerSnapshot
import com.androidsmsgateway.domain.ServerState
import com.androidsmsgateway.sms.SmsSender
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
class GatewayServerController(
context: Context,
private val settingsRepository: SettingsRepository,
private val repository: GatewayRepository,
private val smsSender: SmsSender,
) {
private val documentationProvider = PackagedApiDocumentationProvider(context.applicationContext)
private val mutex = Mutex()
private var server: GatewayHttpServer? = null
private val mutableSnapshot = MutableStateFlow(ServerSnapshot())
val snapshot: StateFlow<ServerSnapshot> = mutableSnapshot.asStateFlow()
suspend fun start(): Result<Unit> = mutex.withLock {
if (server?.isAlive == true) return Result.success(Unit)
runCatching {
val settings = settingsRepository.current()
require(settings.port in 1024..65535) { "Configured port is invalid" }
mutableSnapshot.value = ServerSnapshot(ServerState.STARTING, port = settings.port, ipAddress = NetworkAddressProvider.currentIpv4())
val router = ApiRouter(
repository = repository,
settingsRepository = settingsRepository,
smsSender = smsSender,
serverSnapshot = { mutableSnapshot.value },
documentationProvider = documentationProvider,
)
GatewayHttpServer(settings.bindAddress, settings.port, router).also {
it.start(10_000, false)
server = it
}
mutableSnapshot.value = ServerSnapshot(
state = ServerState.RUNNING,
startedAt = System.currentTimeMillis(),
ipAddress = NetworkAddressProvider.currentIpv4(),
port = settings.port,
)
settingsRepository.update { it.copy(serverEnabled = true) }
Unit
}.onFailure { exception ->
server = null
mutableSnapshot.value = ServerSnapshot(
state = ServerState.ERROR,
port = mutableSnapshot.value.port,
ipAddress = NetworkAddressProvider.currentIpv4(),
lastError = exception.message ?: "Server failed to start",
)
}
}
suspend fun stop(): Result<Unit> = mutex.withLock {
mutableSnapshot.value = mutableSnapshot.value.copy(state = ServerState.STOPPING)
val stopResult = runCatching {
server?.stop()
Unit
}
server = null
val settingsResult = runCatching { settingsRepository.update { settings -> settings.copy(serverEnabled = false) } }
val failure = stopResult.exceptionOrNull() ?: settingsResult.exceptionOrNull()
mutableSnapshot.value = ServerSnapshot(
state = if (failure == null) ServerState.STOPPED else ServerState.ERROR,
port = mutableSnapshot.value.port,
ipAddress = NetworkAddressProvider.currentIpv4(),
lastError = failure?.message,
)
failure?.let { Result.failure(it) } ?: Result.success(Unit)
}
suspend fun restart(): Result<Unit> {
stop()
return start()
}
}
@@ -0,0 +1,116 @@
package com.androidsmsgateway.server
import android.Manifest
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.content.pm.PackageManager
import android.os.IBinder
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import com.androidsmsgateway.GatewayApplication
import com.androidsmsgateway.MainActivity
import com.androidsmsgateway.R
import com.androidsmsgateway.domain.ServerState
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
class GatewayServerService : Service() {
private val serviceJob = SupervisorJob()
private val scope = CoroutineScope(serviceJob + Dispatchers.IO)
private val controller by lazy { (application as GatewayApplication).container.serverController }
private var notificationJob: Job? = null
override fun onCreate() {
super.onCreate()
createNotificationChannel()
startForeground(NOTIFICATION_ID, notification("Starting gateway…"))
notificationJob = scope.launch {
controller.snapshot.collectLatest { snapshot ->
val text = when (snapshot.state) {
ServerState.RUNNING -> "Listening on ${snapshot.ipAddress}:${snapshot.port}"
ServerState.ERROR -> snapshot.lastError ?: "Gateway server error"
else -> snapshot.state.name.lowercase().replaceFirstChar(Char::uppercase)
}
if (
android.os.Build.VERSION.SDK_INT < 33 ||
ContextCompat.checkSelfPermission(this@GatewayServerService, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED
) {
NotificationManagerCompat.from(this@GatewayServerService).notify(NOTIFICATION_ID, notification(text))
}
}
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
scope.launch {
when (intent?.action ?: ACTION_START) {
ACTION_STOP -> {
controller.stop()
stopSelf()
}
ACTION_RESTART -> controller.restart()
else -> controller.start()
}
}
return START_STICKY
}
override fun onDestroy() {
notificationJob?.cancel()
runBlocking(Dispatchers.IO) { controller.stop() }
serviceJob.cancel()
super.onDestroy()
}
override fun onBind(intent: Intent?): IBinder? = null
private fun notification(content: String) = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(android.R.drawable.stat_notify_sync_noanim)
.setContentTitle(getString(R.string.app_name))
.setContentText(content)
.setOngoing(true)
.setSilent(true)
.setContentIntent(
PendingIntent.getActivity(
this,
0,
Intent(this, MainActivity::class.java),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
),
)
.addAction(
0,
"Stop",
PendingIntent.getService(
this,
1,
Intent(this, GatewayServerService::class.java).setAction(ACTION_STOP),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
),
)
.build()
private fun createNotificationChannel() {
val channel = NotificationChannel(CHANNEL_ID, "Gateway server", NotificationManager.IMPORTANCE_LOW).apply {
description = "Keeps the local SMS gateway server running"
}
getSystemService(NotificationManager::class.java).createNotificationChannel(channel)
}
companion object {
const val ACTION_START = "com.androidsmsgateway.server.START"
const val ACTION_STOP = "com.androidsmsgateway.server.STOP"
const val ACTION_RESTART = "com.androidsmsgateway.server.RESTART"
private const val CHANNEL_ID = "gateway_server"
private const val NOTIFICATION_ID = 1001
}
}
@@ -0,0 +1,15 @@
package com.androidsmsgateway.server
import java.net.Inet4Address
import java.net.NetworkInterface
object NetworkAddressProvider {
fun currentIpv4(): String = runCatching {
NetworkInterface.getNetworkInterfaces().toList()
.flatMap { it.inetAddresses.toList() }
.firstOrNull { it is Inet4Address && !it.isLoopbackAddress && !it.isLinkLocalAddress }
?.hostAddress
?: "Unavailable"
}.getOrDefault("Unavailable")
}
@@ -0,0 +1,69 @@
package com.androidsmsgateway.sms
import android.Manifest
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.telephony.SmsManager
import androidx.core.content.ContextCompat
import com.androidsmsgateway.data.GatewayRepository
import com.androidsmsgateway.data.local.OutgoingSmsEntity
import com.androidsmsgateway.domain.MessageStatus
import java.util.UUID
class AndroidSmsSender(
private val context: Context,
private val repository: GatewayRepository,
) : SmsSender {
override suspend fun send(recipient: String, message: String): SmsSubmission {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
throw SmsSubmissionException("SMS_PERMISSION_DENIED", "Send SMS permission is not granted")
}
val id = UUID.randomUUID().toString()
val now = System.currentTimeMillis()
val outgoing = OutgoingSmsEntity(
id = id,
recipient = recipient,
message = message,
requestedAt = now,
status = MessageStatus.PENDING.name,
updatedAt = now,
)
repository.saveOutgoing(outgoing)
val sentIntent = Intent(context, SmsStatusReceiver::class.java).apply {
action = SmsStatusReceiver.ACTION_SENT
putExtra(SmsStatusReceiver.EXTRA_MESSAGE_ID, id)
}
val sentPendingIntent = PendingIntent.getBroadcast(
context,
id.hashCode(),
sentIntent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
try {
smsManager().sendTextMessage(recipient, null, message, sentPendingIntent, null)
} catch (exception: Exception) {
repository.updateOutgoing(
outgoing.copy(
status = MessageStatus.FAILED.name,
errorCode = "SMS_SEND_FAILED",
updatedAt = System.currentTimeMillis(),
),
)
throw SmsSubmissionException("SMS_SEND_FAILED", exception.message ?: "Android rejected the SMS request")
}
return SmsSubmission(id, MessageStatus.PENDING.name.lowercase())
}
@Suppress("DEPRECATION")
private fun smsManager(): SmsManager = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
context.getSystemService(SmsManager::class.java)
} else {
SmsManager.getDefault()
}
}
@@ -0,0 +1,45 @@
package com.androidsmsgateway.sms
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.provider.Telephony
import com.androidsmsgateway.GatewayApplication
import com.androidsmsgateway.data.local.IncomingSmsEntity
import com.androidsmsgateway.domain.MessageStatus
import java.util.UUID
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class IncomingSmsReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action != Telephony.Sms.Intents.SMS_RECEIVED_ACTION) return
val pendingResult = goAsync()
val repository = (context.applicationContext as GatewayApplication).container.gatewayRepository
CoroutineScope(Dispatchers.IO).launch {
try {
runCatching {
val parts = runCatching { Telephony.Sms.Intents.getMessagesFromIntent(intent).toList() }.getOrDefault(emptyList())
parts.groupBy { it.originatingAddress.orEmpty() }.forEach { (sender, messages) ->
if (sender.isBlank()) return@forEach
val receivedAt = messages.minOfOrNull { it.timestampMillis } ?: System.currentTimeMillis()
val body = messages.joinToString("") { it.messageBody.orEmpty() }
repository.saveIncoming(
IncomingSmsEntity(
id = UUID.randomUUID().toString(),
sender = sender,
message = body,
receivedAt = receivedAt,
status = MessageStatus.RECEIVED.name,
createdAt = System.currentTimeMillis(),
),
)
}
}
} finally {
pendingResult.finish()
}
}
}
}
@@ -0,0 +1,10 @@
package com.androidsmsgateway.sms
data class SmsSubmission(val id: String, val status: String)
interface SmsSender {
suspend fun send(recipient: String, message: String): SmsSubmission
}
class SmsSubmissionException(val code: String, override val message: String) : Exception(message)
@@ -0,0 +1,48 @@
package com.androidsmsgateway.sms
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.telephony.SmsManager
import com.androidsmsgateway.GatewayApplication
import com.androidsmsgateway.domain.MessageStatus
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class SmsStatusReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action != ACTION_SENT) return
val id = intent.getStringExtra(EXTRA_MESSAGE_ID) ?: return
val pendingResult = goAsync()
val repository = (context.applicationContext as GatewayApplication).container.gatewayRepository
val result = resultCode
val succeeded = isSuccessfulResult(result)
CoroutineScope(Dispatchers.IO).launch {
try {
runCatching {
repository.outgoingById(id)?.let { message ->
repository.updateOutgoing(
message.copy(
status = if (succeeded) MessageStatus.SENT.name else MessageStatus.FAILED.name,
errorCode = if (succeeded) null else "ANDROID_SMS_ERROR_$result",
updatedAt = System.currentTimeMillis(),
),
)
}
}
} finally {
pendingResult.finish()
}
}
}
companion object {
const val ACTION_SENT = "com.androidsmsgateway.SMS_SENT"
const val EXTRA_MESSAGE_ID = "message_id"
internal fun isSuccessfulResult(resultCode: Int): Boolean =
resultCode == Activity.RESULT_OK || resultCode == SmsManager.RESULT_ERROR_NONE
}
}
@@ -0,0 +1,122 @@
package com.androidsmsgateway.ui
import android.app.Application
import android.content.Intent
import androidx.core.content.ContextCompat
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.androidsmsgateway.GatewayApplication
import com.androidsmsgateway.data.local.IncomingSmsEntity
import com.androidsmsgateway.data.local.OutgoingSmsEntity
import com.androidsmsgateway.data.local.RequestLogEntity
import com.androidsmsgateway.domain.GatewaySettings
import com.androidsmsgateway.domain.ServerSnapshot
import com.androidsmsgateway.security.SecurityPolicy
import com.androidsmsgateway.server.GatewayServerService
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
data class GatewayUiState(
val loading: Boolean = true,
val server: ServerSnapshot = ServerSnapshot(),
val settings: GatewaySettings? = null,
val requestCount: Long = 0,
val sentCount: Long = 0,
val receivedCount: Long = 0,
val lastRequest: RequestLogEntity? = null,
val incoming: List<IncomingSmsEntity> = emptyList(),
val outgoing: List<OutgoingSmsEntity> = emptyList(),
val logs: List<RequestLogEntity> = emptyList(),
val message: String? = null,
)
class GatewayViewModel(application: Application) : AndroidViewModel(application) {
private val app = application as GatewayApplication
private val container = app.container
private val mutableState = MutableStateFlow(GatewayUiState())
val state: StateFlow<GatewayUiState> = mutableState.asStateFlow()
init {
observeState()
viewModelScope.launch {
val settings = container.settingsRepository.ensureInitialized()
mutableState.value = mutableState.value.copy(settings = settings, loading = false)
if (settings.serverEnabled) startServer()
}
}
private fun observeState() {
viewModelScope.launch { container.serverController.snapshot.collect { update { copy(server = it) } } }
viewModelScope.launch { container.settingsRepository.settings.collect { update { copy(settings = it, loading = false) } } }
viewModelScope.launch { container.gatewayRepository.requestCount().collect { update { copy(requestCount = it) } } }
viewModelScope.launch { container.gatewayRepository.outgoingCount().collect { update { copy(sentCount = it) } } }
viewModelScope.launch { container.gatewayRepository.incomingCount().collect { update { copy(receivedCount = it) } } }
viewModelScope.launch { container.gatewayRepository.lastRequest().collect { update { copy(lastRequest = it) } } }
viewModelScope.launch { container.gatewayRepository.incomingMessages().collect { update { copy(incoming = it) } } }
viewModelScope.launch { container.gatewayRepository.outgoingMessages().collect { update { copy(outgoing = it) } } }
viewModelScope.launch { container.gatewayRepository.requestLogs().collect { update { copy(logs = it) } } }
}
fun startServer() {
ContextCompat.startForegroundService(app, Intent(app, GatewayServerService::class.java).setAction(GatewayServerService.ACTION_START))
}
fun stopServer() {
app.startService(Intent(app, GatewayServerService::class.java).setAction(GatewayServerService.ACTION_STOP))
}
fun saveServerSettings(portText: String, bindAddress: String, startOnBoot: Boolean) {
val port = portText.toIntOrNull()
if (port == null || port !in 1024..65535) return showMessage("Port must be between 1024 and 65535")
val bind = bindAddress.trim()
if (!SecurityPolicy.isValidIp(bind)) return showMessage("Bind address must be a valid IP address")
viewModelScope.launch {
container.settingsRepository.update { it.copy(port = port, bindAddress = bind, startOnBoot = startOnBoot) }
if (state.value.server.state.name == "RUNNING") {
ContextCompat.startForegroundService(app, Intent(app, GatewayServerService::class.java).setAction(GatewayServerService.ACTION_RESTART))
}
showMessage("Server settings saved")
}
}
fun setAuthenticationEnabled(enabled: Boolean) = updateSettings(transform = { it.copy(authenticationEnabled = enabled) })
fun setAllowlistEnabled(enabled: Boolean) = updateSettings(transform = { it.copy(allowlistEnabled = enabled) })
fun setApiKey(apiKey: String) {
if (apiKey.length < 16) return showMessage("API key must contain at least 16 characters")
updateSettings({ it.copy(apiKeyHash = SecurityPolicy.hashApiKey(apiKey)) }, "API key updated")
}
fun addAllowedIp(ip: String) {
val value = ip.trim()
if (!SecurityPolicy.isValidIp(value)) return showMessage("Enter a valid IPv4 or IPv6 address")
updateSettings({ current ->
val values = current.allowedIps.lineSequence().map(String::trim).filter(String::isNotEmpty).toMutableSet()
values += value
current.copy(allowedIps = values.sorted().joinToString("\n"))
}, "Allowed IP added")
}
fun removeAllowedIp(ip: String) = updateSettings(transform = { current ->
current.copy(allowedIps = current.allowedIps.lineSequence().filter { it.trim() != ip }.joinToString("\n"))
})
fun clearMessage() = update { copy(message = null) }
private fun updateSettings(
transform: (com.androidsmsgateway.data.local.AppSettingsEntity) -> com.androidsmsgateway.data.local.AppSettingsEntity,
confirmation: String? = null,
) {
viewModelScope.launch {
container.settingsRepository.update(transform)
confirmation?.let(::showMessage)
}
}
private fun showMessage(message: String) = update { copy(message = message) }
private inline fun update(transform: GatewayUiState.() -> GatewayUiState) {
mutableState.value = mutableState.value.transform()
}
}
@@ -0,0 +1,313 @@
package com.androidsmsgateway.ui.components
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.ChatBubbleOutline
import androidx.compose.material.icons.outlined.Info
import androidx.compose.material.icons.outlined.Search
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Switch
import androidx.compose.material3.SwitchDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.androidsmsgateway.ui.theme.GatewayInfo
import com.androidsmsgateway.ui.theme.GatewayInfoBackground
import com.androidsmsgateway.ui.theme.GatewayMint
import com.androidsmsgateway.ui.theme.GatewayPrimary
import com.androidsmsgateway.ui.theme.GatewaySignal
import com.androidsmsgateway.ui.theme.GatewayWarning
import com.androidsmsgateway.ui.theme.GatewayWarningBackground
val GatewayCardShape = RoundedCornerShape(18.dp)
val GatewayControlShape = RoundedCornerShape(13.dp)
enum class BadgeTone { SUCCESS, INFO, WARNING, ERROR, NEUTRAL }
@Composable
fun BrandMark(modifier: Modifier = Modifier) {
Box(
modifier
.size(34.dp)
.clip(RoundedCornerShape(10.dp))
.background(GatewayMint),
contentAlignment = Alignment.Center,
) {
Icon(
Icons.Outlined.ChatBubbleOutline,
contentDescription = null,
tint = GatewayPrimary,
modifier = Modifier.size(19.dp),
)
}
}
@Composable
fun ScreenHeader(
title: String,
subtitle: String,
modifier: Modifier = Modifier,
leading: @Composable (() -> Unit)? = null,
trailing: @Composable (() -> Unit)? = null,
) {
Row(
modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
if (leading != null) leading() else BrandMark()
Column(Modifier.weight(1f)) {
Text(title, style = MaterialTheme.typography.titleLarge)
Text(
subtitle.uppercase(),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
trailing?.invoke()
}
}
@Composable
fun GatewayCard(
modifier: Modifier = Modifier,
containerColor: Color = MaterialTheme.colorScheme.surface,
contentPadding: PaddingValues = PaddingValues(16.dp),
content: @Composable () -> Unit,
) {
Card(
modifier = modifier,
shape = GatewayCardShape,
colors = CardDefaults.cardColors(containerColor = containerColor),
elevation = CardDefaults.cardElevation(defaultElevation = 0.dp),
border = androidx.compose.foundation.BorderStroke(1.dp, MaterialTheme.colorScheme.outline.copy(alpha = 0.72f)),
) {
Box(Modifier.padding(contentPadding)) { content() }
}
}
@Composable
fun StatusBadge(
text: String,
tone: BadgeTone,
modifier: Modifier = Modifier,
) {
val (background, foreground) = when (tone) {
BadgeTone.SUCCESS -> GatewayMint to GatewayPrimary
BadgeTone.INFO -> GatewayInfoBackground to GatewayInfo
BadgeTone.WARNING -> GatewayWarningBackground to GatewayWarning
BadgeTone.ERROR -> MaterialTheme.colorScheme.errorContainer to MaterialTheme.colorScheme.onErrorContainer
BadgeTone.NEUTRAL -> MaterialTheme.colorScheme.surfaceVariant to MaterialTheme.colorScheme.onSurfaceVariant
}
Text(
text.uppercase(),
modifier = modifier
.clip(CircleShape)
.background(background)
.padding(horizontal = 10.dp, vertical = 5.dp),
color = foreground,
style = MaterialTheme.typography.labelSmall,
maxLines = 1,
)
}
@Composable
fun GatewaySearchField(
value: String,
onValueChange: (String) -> Unit,
placeholder: String,
modifier: Modifier = Modifier,
) {
OutlinedTextField(
value = value,
onValueChange = onValueChange,
modifier = modifier.fillMaxWidth(),
placeholder = { Text(placeholder) },
leadingIcon = { Icon(Icons.Outlined.Search, contentDescription = null) },
singleLine = true,
shape = GatewayControlShape,
colors = OutlinedTextFieldDefaults.colors(
focusedContainerColor = MaterialTheme.colorScheme.surface,
unfocusedContainerColor = MaterialTheme.colorScheme.surface,
focusedBorderColor = GatewayPrimary,
unfocusedBorderColor = MaterialTheme.colorScheme.outline,
),
)
}
@Composable
fun SettingToggleRow(
title: String,
description: String,
checked: Boolean,
onCheckedChange: (Boolean) -> Unit,
modifier: Modifier = Modifier,
) {
Row(
modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(16.dp),
) {
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
Text(title, style = MaterialTheme.typography.titleMedium)
Text(description, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
Switch(
checked = checked,
onCheckedChange = onCheckedChange,
colors = SwitchDefaults.colors(
checkedThumbColor = Color.White,
checkedTrackColor = GatewayPrimary,
uncheckedThumbColor = MaterialTheme.colorScheme.onSurfaceVariant,
uncheckedTrackColor = MaterialTheme.colorScheme.surfaceVariant,
),
)
}
}
@Composable
fun InfoBanner(
title: String,
body: String,
modifier: Modifier = Modifier,
warning: Boolean = false,
) {
val background = if (warning) GatewayWarningBackground else GatewayInfoBackground
val foreground = if (warning) GatewayWarning else GatewayInfo
Row(
modifier
.fillMaxWidth()
.clip(GatewayControlShape)
.background(background)
.padding(14.dp),
horizontalArrangement = Arrangement.spacedBy(12.dp),
verticalAlignment = Alignment.Top,
) {
Icon(Icons.Outlined.Info, contentDescription = null, tint = foreground, modifier = Modifier.size(20.dp))
Column(verticalArrangement = Arrangement.spacedBy(3.dp)) {
Text(title, style = MaterialTheme.typography.labelLarge, color = foreground)
Text(body, style = MaterialTheme.typography.bodySmall, color = foreground)
}
}
}
@Composable
fun EmptyState(
icon: ImageVector,
title: String,
body: String,
modifier: Modifier = Modifier,
actionLabel: String? = null,
onAction: (() -> Unit)? = null,
) {
Column(
modifier.fillMaxWidth().padding(horizontal = 28.dp, vertical = 54.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
Box(
Modifier.size(72.dp).clip(CircleShape).background(MaterialTheme.colorScheme.primaryContainer),
contentAlignment = Alignment.Center,
) {
Icon(icon, contentDescription = null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(32.dp))
}
Spacer(Modifier.height(2.dp))
Text(title, style = MaterialTheme.typography.titleMedium)
Text(
body,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 3,
overflow = TextOverflow.Ellipsis,
)
if (actionLabel != null && onAction != null) {
Button(
onClick = onAction,
colors = ButtonDefaults.buttonColors(containerColor = GatewayPrimary),
shape = GatewayControlShape,
) { Text(actionLabel) }
}
}
}
@Composable
fun SectionLabel(text: String, modifier: Modifier = Modifier) {
Text(
text.uppercase(),
modifier = modifier,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
@Composable
fun ClickableSettingRow(
title: String,
description: String,
icon: ImageVector,
onClick: () -> Unit,
modifier: Modifier = Modifier,
) {
Row(
modifier
.fillMaxWidth()
.clip(GatewayControlShape)
.clickable(onClick = onClick)
.border(1.dp, MaterialTheme.colorScheme.outline, GatewayControlShape)
.padding(16.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(14.dp),
) {
Box(
Modifier.size(38.dp).clip(CircleShape).background(MaterialTheme.colorScheme.primaryContainer),
contentAlignment = Alignment.Center,
) {
Icon(icon, contentDescription = null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(20.dp))
}
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(title, style = MaterialTheme.typography.titleMedium)
Text(description, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
Text("›", style = MaterialTheme.typography.headlineMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
@Composable
fun LiveBadge() {
Row(
Modifier.clip(CircleShape).background(GatewayMint).padding(horizontal = 10.dp, vertical = 5.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(6.dp),
) {
Box(Modifier.size(6.dp).clip(CircleShape).background(GatewaySignal))
Text("LIVE", color = GatewayPrimary, style = MaterialTheme.typography.labelSmall, fontWeight = FontWeight.Bold)
}
}
@@ -0,0 +1,338 @@
package com.androidsmsgateway.ui.screens
import android.Manifest
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.CheckCircle
import androidx.compose.material.icons.outlined.ContentCopy
import androidx.compose.material.icons.outlined.Description
import androidx.compose.material.icons.outlined.ErrorOutline
import androidx.compose.material.icons.outlined.Language
import androidx.compose.material.icons.outlined.Security
import androidx.compose.material.icons.outlined.StopCircle
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import androidx.core.net.toUri
import com.androidsmsgateway.domain.ServerState
import com.androidsmsgateway.ui.GatewayUiState
import com.androidsmsgateway.ui.components.BadgeTone
import com.androidsmsgateway.ui.components.GatewayCard
import com.androidsmsgateway.ui.components.GatewayCardShape
import com.androidsmsgateway.ui.components.InfoBanner
import com.androidsmsgateway.ui.components.ScreenHeader
import com.androidsmsgateway.ui.components.StatusBadge
import com.androidsmsgateway.ui.theme.GatewayErrorBackground
import com.androidsmsgateway.ui.theme.GatewayMint
import com.androidsmsgateway.ui.theme.GatewayPrimary
import com.androidsmsgateway.ui.theme.GatewayPrimaryDark
import com.androidsmsgateway.ui.theme.GatewaySignal
import kotlinx.coroutines.delay
@Composable
fun DashboardScreen(
state: GatewayUiState,
expanded: Boolean,
start: () -> Unit,
stop: () -> Unit,
openSecurity: () -> Unit,
openPermissions: () -> Unit,
) {
val context = LocalContext.current
val running = state.server.state == ServerState.RUNNING
var now by remember { mutableLongStateOf(System.currentTimeMillis()) }
var confirmStop by remember { mutableStateOf(false) }
LaunchedEffect(running) {
while (running) {
now = System.currentTimeMillis()
delay(1_000)
}
}
val hasSend = ContextCompat.checkSelfPermission(context, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED
val hasReceive = ContextCompat.checkSelfPermission(context, Manifest.permission.RECEIVE_SMS) == PackageManager.PERMISSION_GRANTED
val authenticationReady = state.settings?.let { !it.authenticationEnabled || it.apiKeyHash.isNotBlank() } ?: true
Column(
Modifier.verticalScroll(rememberScrollState()).padding(horizontal = if (expanded) 28.dp else 16.dp, vertical = 18.dp),
verticalArrangement = Arrangement.spacedBy(14.dp),
) {
ScreenHeader("SMS Gateway", "Operations console")
if (expanded) {
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(16.dp), verticalAlignment = Alignment.Top) {
Column(Modifier.weight(1.15f), verticalArrangement = Arrangement.spacedBy(14.dp)) {
ServerHeroCard(state, now, start)
MetricsRow(state)
}
Column(Modifier.weight(0.85f), verticalArrangement = Arrangement.spacedBy(14.dp)) {
LastRequestCard(state)
SecuritySummaryCard(state, openSecurity)
}
}
} else {
ServerHeroCard(state, now, start)
MetricsRow(state)
LastRequestCard(state)
SecuritySummaryCard(state, openSecurity)
}
if (!authenticationReady) {
InfoBanner(
title = "Security setup required",
body = "Configure an API key before connecting a backend.",
warning = true,
modifier = Modifier.clip(RoundedCornerShape(13.dp)),
)
}
if (!hasSend || !hasReceive) {
OutlinedButton(onClick = openPermissions, modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(13.dp)) {
Icon(Icons.Outlined.ErrorOutline, contentDescription = null)
Spacer(Modifier.size(8.dp))
Text("Review missing SMS permissions")
}
}
if (running) {
Button(
onClick = { confirmStop = true },
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(13.dp),
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.errorContainer,
contentColor = MaterialTheme.colorScheme.onErrorContainer,
),
) {
Icon(Icons.Outlined.StopCircle, contentDescription = null)
Spacer(Modifier.size(8.dp))
Text("Stop server")
}
}
Spacer(Modifier.height(4.dp))
}
if (confirmStop) {
AlertDialog(
onDismissRequest = { confirmStop = false },
icon = { Icon(Icons.Outlined.StopCircle, contentDescription = null) },
title = { Text("Stop the gateway?") },
text = { Text("API clients will immediately lose access until the server is started again.") },
confirmButton = {
Button(
onClick = { confirmStop = false; stop() },
colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.error),
) { Text("Stop server") }
},
dismissButton = { TextButton(onClick = { confirmStop = false }) { Text("Keep running") } },
)
}
}
@Composable
private fun ServerHeroCard(state: GatewayUiState, now: Long, start: () -> Unit) {
val context = LocalContext.current
val status = state.server.state
val running = status == ServerState.RUNNING
val busy = status == ServerState.STARTING || status == ServerState.STOPPING
val error = status == ServerState.ERROR
val container = when {
running -> GatewayPrimaryDark
error -> MaterialTheme.colorScheme.errorContainer
else -> MaterialTheme.colorScheme.surface
}
val foreground = when {
running -> Color.White
error -> MaterialTheme.colorScheme.onErrorContainer
else -> MaterialTheme.colorScheme.onSurface
}
val muted = foreground.copy(alpha = 0.72f)
val title = when (status) {
ServerState.RUNNING -> "Gateway online"
ServerState.STARTING -> "Bringing gateway online"
ServerState.STOPPING -> "Stopping gateway"
ServerState.ERROR -> "Server failed to start"
ServerState.STOPPED -> "Ready when you are"
}
val summary = when (status) {
ServerState.RUNNING -> "Secure and reachable on your network"
ServerState.STARTING -> "Opening the HTTP listener"
ServerState.STOPPING -> "Closing active gateway resources"
ServerState.ERROR -> state.server.lastError ?: "The HTTP listener could not be started"
ServerState.STOPPED -> "Start the server when permissions and security are ready"
}
GatewayCard(
modifier = Modifier.fillMaxWidth(),
containerColor = container,
contentPadding = androidx.compose.foundation.layout.PaddingValues(18.dp),
) {
Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
StatusBadge(
text = status.name,
tone = when (status) {
ServerState.RUNNING -> BadgeTone.SUCCESS
ServerState.STARTING, ServerState.STOPPING -> BadgeTone.INFO
ServerState.ERROR -> BadgeTone.ERROR
ServerState.STOPPED -> BadgeTone.NEUTRAL
},
)
if (running) Icon(Icons.Outlined.CheckCircle, "Server is healthy", tint = GatewaySignal)
}
Column(verticalArrangement = Arrangement.spacedBy(3.dp)) {
Text(title, style = MaterialTheme.typography.headlineMedium, color = foreground)
Text(summary, style = MaterialTheme.typography.bodyMedium, color = muted, maxLines = 2, overflow = TextOverflow.Ellipsis)
}
Row(
Modifier.fillMaxWidth().clip(RoundedCornerShape(12.dp)).background(foreground.copy(alpha = 0.08f)).padding(horizontal = 12.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(Icons.Outlined.Language, contentDescription = null, tint = if (running) GatewaySignal else GatewayPrimary, modifier = Modifier.size(19.dp))
Text(
"${state.server.ipAddress}:${state.server.port}",
modifier = Modifier.weight(1f).padding(horizontal = 9.dp),
color = foreground,
style = MaterialTheme.typography.labelLarge,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
IconButton(
onClick = {
val address = "${state.server.ipAddress}:${state.server.port}"
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
clipboard.setPrimaryClip(ClipData.newPlainText("Gateway address", address))
Toast.makeText(context, "Gateway address copied", Toast.LENGTH_SHORT).show()
},
modifier = Modifier.size(34.dp),
) { Icon(Icons.Outlined.ContentCopy, "Copy gateway address", tint = muted, modifier = Modifier.size(17.dp)) }
}
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
Column {
Text("UPTIME", style = MaterialTheme.typography.labelSmall, color = muted)
Text(formatDuration(state.server.uptimeMillis(now)), style = MaterialTheme.typography.labelLarge, color = foreground)
}
if (running) {
TextButton(
onClick = {
val host = state.server.ipAddress.takeUnless { it == "Unavailable" } ?: "127.0.0.1"
context.startActivity(Intent(Intent.ACTION_VIEW, "http://$host:${state.server.port}/docs".toUri()))
},
colors = ButtonDefaults.textButtonColors(contentColor = GatewaySignal),
) {
Icon(Icons.Outlined.Description, contentDescription = null, modifier = Modifier.size(17.dp))
Spacer(Modifier.size(6.dp))
Text("Open API docs")
}
} else {
Button(onClick = start, enabled = !busy, shape = RoundedCornerShape(11.dp)) {
Text(if (error) "Retry" else if (busy) status.name.lowercase().replaceFirstChar(Char::uppercase) else "Start server")
}
}
}
}
}
}
@Composable
private fun MetricsRow(state: GatewayUiState) {
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
MetricCard("Requests", state.requestCount, Modifier.weight(1f))
MetricCard("Outgoing", state.sentCount, Modifier.weight(1f))
MetricCard("Incoming", state.receivedCount, Modifier.weight(1f))
}
}
@Composable
private fun MetricCard(label: String, value: Long, modifier: Modifier) {
GatewayCard(modifier = modifier, contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 12.dp, vertical = 14.dp)) {
Column(verticalArrangement = Arrangement.spacedBy(5.dp)) {
Text(formatCount(value), style = MaterialTheme.typography.headlineMedium, maxLines = 1)
Text(label, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
}
@Composable
private fun LastRequestCard(state: GatewayUiState) {
GatewayCard(Modifier.fillMaxWidth()) {
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
Text("Last request", style = MaterialTheme.typography.titleMedium)
state.lastRequest?.let {
StatusBadge(it.statusCode.toString(), if (it.statusCode in 200..299) BadgeTone.SUCCESS else if (it.statusCode >= 500) BadgeTone.ERROR else BadgeTone.WARNING)
}
}
state.lastRequest?.let {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
StatusBadge(it.method, BadgeTone.INFO)
Text(it.path, style = MaterialTheme.typography.labelLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
Text("${it.durationMs} ms · ${it.clientIp} · ${formatTime(it.timestamp)}", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
} ?: Text("No API requests yet", color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
}
@Composable
private fun SecuritySummaryCard(state: GatewayUiState, openSecurity: () -> Unit) {
val settings = state.settings
val authenticationReady = settings != null && settings.authenticationEnabled && settings.apiKeyHash.isNotBlank()
val protected = authenticationReady && settings.allowlistEnabled && settings.allowedIps.isNotEmpty()
GatewayCard(Modifier.fillMaxWidth()) {
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(9.dp)) {
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
Icon(Icons.Outlined.Security, contentDescription = null, tint = if (authenticationReady) GatewayPrimary else MaterialTheme.colorScheme.error)
Column {
Text(if (protected) "Protected" else if (authenticationReady) "API key protected" else "Needs attention", style = MaterialTheme.typography.titleMedium)
Text(
if (settings?.allowlistEnabled == true) "Allowlist · ${settings.allowedIps.size} trusted clients" else "Allowlist is disabled",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
StatusBadge(if (protected) "Healthy" else "Review", if (protected) BadgeTone.SUCCESS else BadgeTone.WARNING)
}
TextButton(onClick = openSecurity, modifier = Modifier.align(Alignment.End)) { Text("Review security") }
}
}
}
@@ -0,0 +1,18 @@
package com.androidsmsgateway.ui.screens
import java.text.DateFormat
import java.text.NumberFormat
import java.util.Date
internal fun formatTimestamp(value: Long): String =
DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(Date(value))
internal fun formatTime(value: Long): String =
DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(value))
internal fun formatDuration(milliseconds: Long): String {
val seconds = milliseconds / 1000
return "%02d:%02d:%02d".format(seconds / 3600, seconds % 3600 / 60, seconds % 60)
}
internal fun formatCount(value: Long): String = NumberFormat.getIntegerInstance().format(value)
@@ -0,0 +1,125 @@
package com.androidsmsgateway.ui.screens
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.ReceiptLong
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FilterChipDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.androidsmsgateway.data.local.RequestLogEntity
import com.androidsmsgateway.ui.GatewayUiState
import com.androidsmsgateway.ui.components.BadgeTone
import com.androidsmsgateway.ui.components.EmptyState
import com.androidsmsgateway.ui.components.GatewayCard
import com.androidsmsgateway.ui.components.GatewaySearchField
import com.androidsmsgateway.ui.components.LiveBadge
import com.androidsmsgateway.ui.components.ScreenHeader
import com.androidsmsgateway.ui.components.StatusBadge
import com.androidsmsgateway.ui.theme.GatewayPrimary
private data class LogFilter(val label: String, val accepts: (Int) -> Boolean)
private val filters = listOf(
LogFilter("All") { true },
LogFilter("Success") { it in 200..399 },
LogFilter("4xx") { it in 400..499 },
LogFilter("5xx") { it >= 500 },
)
@Composable
fun LogsScreen(state: GatewayUiState) {
var selectedFilter by rememberSaveable { mutableIntStateOf(0) }
var query by rememberSaveable { mutableStateOf("") }
val visibleLogs = remember(state.logs, selectedFilter, query) {
state.logs.filter {
filters[selectedFilter].accepts(it.statusCode) &&
(query.isBlank() || it.path.contains(query, true) || it.clientIp.contains(query, true) || it.method.contains(query, true))
}
}
val listState = rememberLazyListState()
Column(Modifier.fillMaxSize()) {
Column(
Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 18.dp),
verticalArrangement = Arrangement.spacedBy(13.dp),
) {
ScreenHeader("Request logs", "HTTP traffic", trailing = { LiveBadge() })
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(7.dp)) {
filters.forEachIndexed { index, filter ->
FilterChip(
selected = selectedFilter == index,
onClick = { selectedFilter = index },
label = { Text(filter.label) },
shape = RoundedCornerShape(50),
colors = FilterChipDefaults.filterChipColors(
selectedContainerColor = MaterialTheme.colorScheme.onSurface,
selectedLabelColor = MaterialTheme.colorScheme.surface,
),
)
}
}
GatewaySearchField(query, { query = it.take(100) }, "Search path or client IP")
}
if (visibleLogs.isEmpty()) {
EmptyState(
icon = Icons.AutoMirrored.Outlined.ReceiptLong,
title = if (state.logs.isEmpty()) "No API requests yet" else "No matching requests",
body = if (state.logs.isEmpty()) "Requests will appear here as clients use the gateway." else "Try a different response filter, path, or client IP.",
modifier = Modifier.fillMaxSize(),
)
} else {
LazyColumn(
Modifier.fillMaxSize(),
state = listState,
contentPadding = PaddingValues(start = 16.dp, end = 16.dp, bottom = 20.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
items(visibleLogs, key = { it.id }) { log -> LogCard(log) }
}
}
}
}
@Composable
private fun LogCard(log: RequestLogEntity) {
val tone = when (log.statusCode) {
in 200..399 -> BadgeTone.SUCCESS
in 400..499 -> BadgeTone.WARNING
else -> BadgeTone.ERROR
}
GatewayCard(Modifier.fillMaxWidth()) {
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(9.dp)) {
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(9.dp)) {
StatusBadge(log.method, if (log.method == "GET") BadgeTone.SUCCESS else BadgeTone.INFO)
Text(log.path, modifier = Modifier.weight(1f), style = MaterialTheme.typography.labelLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
StatusBadge(log.statusCode.toString(), tone)
}
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
Text("${log.durationMs} ms · ${log.clientIp}", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
Text(formatTime(log.timestamp), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
}
}
}
@@ -0,0 +1,179 @@
package com.androidsmsgateway.ui.screens
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Inbox
import androidx.compose.material.icons.outlined.MarkEmailRead
import androidx.compose.material.icons.outlined.Outbox
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.androidsmsgateway.data.local.IncomingSmsEntity
import com.androidsmsgateway.data.local.OutgoingSmsEntity
import com.androidsmsgateway.ui.GatewayUiState
import com.androidsmsgateway.ui.components.BadgeTone
import com.androidsmsgateway.ui.components.EmptyState
import com.androidsmsgateway.ui.components.GatewayCard
import com.androidsmsgateway.ui.components.GatewaySearchField
import com.androidsmsgateway.ui.components.LiveBadge
import com.androidsmsgateway.ui.components.ScreenHeader
import com.androidsmsgateway.ui.components.StatusBadge
import com.androidsmsgateway.ui.theme.GatewayInfoBackground
import com.androidsmsgateway.ui.theme.GatewayMint
import com.androidsmsgateway.ui.theme.GatewayPrimary
@Composable
fun MessagesScreen(state: GatewayUiState) {
var tab by rememberSaveable { mutableIntStateOf(0) }
var query by rememberSaveable { mutableStateOf("") }
val incoming = remember(state.incoming, query) {
state.incoming.filter { query.isBlank() || it.sender.contains(query, true) || it.message.contains(query, true) }
}
val outgoing = remember(state.outgoing, query) {
state.outgoing.filter {
query.isBlank() || it.recipient.contains(query, true) || it.message.contains(query, true) || it.status.contains(query, true)
}
}
Column(Modifier.fillMaxSize()) {
Column(
Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 18.dp),
verticalArrangement = Arrangement.spacedBy(14.dp),
) {
ScreenHeader("Messages", "Live SMS activity", trailing = { LiveBadge() })
MessageTabs(tab) { tab = it }
GatewaySearchField(
value = query,
onValueChange = { query = it.take(100) },
placeholder = "Search sender or message",
)
}
when {
tab == 0 && incoming.isEmpty() -> EmptyState(
icon = Icons.Outlined.Inbox,
title = if (query.isBlank()) "No incoming messages" else "No matching messages",
body = if (query.isBlank()) "Messages received by this device will appear here." else "Try another sender, number, or phrase.",
modifier = Modifier.fillMaxSize(),
)
tab == 1 && outgoing.isEmpty() -> EmptyState(
icon = Icons.Outlined.Outbox,
title = if (query.isBlank()) "No outgoing messages" else "No matching messages",
body = if (query.isBlank()) "SMS requests submitted through the API will appear here." else "Try another recipient, status, or phrase.",
modifier = Modifier.fillMaxSize(),
)
tab == 0 -> IncomingList(incoming)
else -> OutgoingList(outgoing)
}
}
}
@Composable
private fun MessageTabs(selected: Int, onSelected: (Int) -> Unit) {
Row(
Modifier.fillMaxWidth().clip(RoundedCornerShape(14.dp)).background(MaterialTheme.colorScheme.surfaceVariant).padding(4.dp),
) {
listOf("Incoming", "Outgoing").forEachIndexed { index, label ->
Box(
Modifier.weight(1f).clip(RoundedCornerShape(11.dp))
.background(if (selected == index) MaterialTheme.colorScheme.surface else MaterialTheme.colorScheme.surfaceVariant)
.clickable { onSelected(index) }
.padding(vertical = 10.dp),
contentAlignment = Alignment.Center,
) {
Text(
label,
style = MaterialTheme.typography.labelLarge,
color = if (selected == index) GatewayPrimary else MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
}
@Composable
private fun IncomingList(messages: List<IncomingSmsEntity>) {
LazyColumn(
Modifier.fillMaxSize(),
contentPadding = PaddingValues(start = 16.dp, end = 16.dp, bottom = 20.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
items(messages, key = { it.id }) { item ->
MessageCard(item.sender, item.message, item.status, item.receivedAt, incoming = true)
}
}
}
@Composable
private fun OutgoingList(messages: List<OutgoingSmsEntity>) {
LazyColumn(
Modifier.fillMaxSize(),
contentPadding = PaddingValues(start = 16.dp, end = 16.dp, bottom = 20.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
items(messages, key = { it.id }) { item ->
MessageCard(item.recipient, item.message, item.status, item.requestedAt, incoming = false)
}
}
}
@Composable
private fun MessageCard(address: String, body: String, status: String, timestamp: Long, incoming: Boolean) {
val normalized = status.lowercase()
val tone = when (normalized) {
"received", "sent" -> BadgeTone.SUCCESS
"pending" -> BadgeTone.INFO
"failed" -> BadgeTone.ERROR
else -> BadgeTone.NEUTRAL
}
val avatarColor = if (incoming) GatewayMint else GatewayInfoBackground
GatewayCard(Modifier.fillMaxWidth()) {
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(11.dp)) {
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(11.dp)) {
Box(Modifier.size(38.dp).clip(CircleShape).background(avatarColor), contentAlignment = Alignment.Center) {
Text(initials(address), style = MaterialTheme.typography.labelMedium, color = GatewayPrimary, fontWeight = FontWeight.Bold)
}
Column(Modifier.weight(1f)) {
Text(address, style = MaterialTheme.typography.titleMedium, maxLines = 1, overflow = TextOverflow.Ellipsis)
StatusBadge(normalized, tone)
}
Text(formatTime(timestamp), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
Text(body, style = MaterialTheme.typography.bodyMedium, maxLines = 4, overflow = TextOverflow.Ellipsis)
}
}
}
private fun initials(value: String): String {
val letters = value.trim().split(Regex("\\s+")).mapNotNull { it.firstOrNull()?.takeIf(Char::isLetterOrDigit) }
return when {
letters.size >= 2 -> "${letters[0]}${letters[1]}".uppercase()
letters.size == 1 -> letters[0].uppercase()
else -> "SMS"
}
}
@@ -0,0 +1,155 @@
package com.androidsmsgateway.ui.screens
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.provider.Settings
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.LocalActivity
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
import androidx.compose.material.icons.outlined.Check
import androidx.compose.material.icons.outlined.Lock
import androidx.compose.material.icons.outlined.WarningAmber
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import androidx.core.net.toUri
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import com.androidsmsgateway.ui.components.BadgeTone
import com.androidsmsgateway.ui.components.GatewayCard
import com.androidsmsgateway.ui.components.InfoBanner
import com.androidsmsgateway.ui.components.ScreenHeader
import com.androidsmsgateway.ui.components.StatusBadge
import com.androidsmsgateway.ui.theme.GatewayMint
import com.androidsmsgateway.ui.theme.GatewayPrimary
import com.androidsmsgateway.ui.theme.GatewayWarning
import com.androidsmsgateway.ui.theme.GatewayWarningBackground
private data class PermissionItem(val title: String, val permission: String, val description: String)
@Composable
fun PermissionsScreen(onBack: () -> Unit) {
val context = LocalContext.current
val activity = LocalActivity.current
val lifecycleOwner = activity as? LifecycleOwner
var refresh by remember { mutableIntStateOf(0) }
val launcher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { refresh++ }
val permissions = buildList {
add(PermissionItem("Send SMS", Manifest.permission.SEND_SMS, "Required to send messages through the API"))
add(PermissionItem("Receive SMS", Manifest.permission.RECEIVE_SMS, "Required to persist incoming messages"))
if (Build.VERSION.SDK_INT >= 33) {
add(PermissionItem("Gateway notification", Manifest.permission.POST_NOTIFICATIONS, "Keeps the foreground server visible"))
}
}
val grantState = permissions.associateWith {
refresh
ContextCompat.checkSelfPermission(context, it.permission) == PackageManager.PERMISSION_GRANTED
}
val granted = grantState.count { it.value }
DisposableEffect(lifecycleOwner) {
val observer = LifecycleEventObserver { _, event -> if (event == Lifecycle.Event.ON_RESUME) refresh++ }
lifecycleOwner?.lifecycle?.addObserver(observer)
onDispose { lifecycleOwner?.lifecycle?.removeObserver(observer) }
}
Column(
Modifier.verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 18.dp),
verticalArrangement = Arrangement.spacedBy(14.dp),
) {
ScreenHeader(
title = "SMS permissions",
subtitle = "Android access",
leading = {
IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Outlined.ArrowBack, contentDescription = "Back to server settings") }
},
)
GatewayCard(Modifier.fillMaxWidth()) {
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text("Gateway readiness", style = MaterialTheme.typography.labelLarge)
Text("$granted of ${permissions.size} permissions granted", style = MaterialTheme.typography.titleLarge)
LinearProgressIndicator(
progress = { granted.toFloat() / permissions.size.coerceAtLeast(1) },
modifier = Modifier.fillMaxWidth().clip(CircleShape),
color = GatewayPrimary,
trackColor = MaterialTheme.colorScheme.surfaceVariant,
drawStopIndicator = {},
)
}
}
Text(
"Permissions are requested only when you choose to grant them.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
permissions.forEach { item ->
PermissionCard(item, grantState.getValue(item)) { launcher.launch(item.permission) }
}
OutlinedButton(
onClick = { context.startActivity(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, "package:${context.packageName}".toUri())) },
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(13.dp),
) { Text("Open Android app settings") }
InfoBanner(
title = "Your privacy",
body = "SMS access stays on this device and is never requested without context.",
)
}
}
@Composable
private fun PermissionCard(item: PermissionItem, granted: Boolean, grant: () -> Unit) {
GatewayCard(Modifier.fillMaxWidth()) {
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(13.dp)) {
Box(
Modifier.size(40.dp).clip(CircleShape).background(if (granted) GatewayMint else GatewayWarningBackground),
contentAlignment = Alignment.Center,
) {
Icon(
if (granted) Icons.Outlined.Check else Icons.Outlined.WarningAmber,
contentDescription = null,
tint = if (granted) GatewayPrimary else GatewayWarning,
)
}
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
Text(item.title, style = MaterialTheme.typography.titleMedium)
StatusBadge(if (granted) "Granted" else "Required", if (granted) BadgeTone.SUCCESS else BadgeTone.WARNING)
Text(item.description, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
if (!granted) Button(onClick = grant, shape = RoundedCornerShape(50)) { Text("Grant") }
}
}
}
@@ -0,0 +1,282 @@
package com.androidsmsgateway.ui.screens
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Key
import androidx.compose.material.icons.outlined.Security
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.androidsmsgateway.ui.GatewayUiState
import com.androidsmsgateway.ui.GatewayViewModel
import com.androidsmsgateway.security.SecurityPolicy
import com.androidsmsgateway.ui.components.BadgeTone
import com.androidsmsgateway.ui.components.GatewayCard
import com.androidsmsgateway.ui.components.GatewayControlShape
import com.androidsmsgateway.ui.components.InfoBanner
import com.androidsmsgateway.ui.components.ScreenHeader
import com.androidsmsgateway.ui.components.SectionLabel
import com.androidsmsgateway.ui.components.SettingToggleRow
import com.androidsmsgateway.ui.components.StatusBadge
import com.androidsmsgateway.ui.theme.GatewayMint
import com.androidsmsgateway.ui.theme.GatewayPrimary
import com.androidsmsgateway.ui.theme.GatewayPrimaryDark
import com.androidsmsgateway.ui.theme.GatewaySignal
@Composable
fun SecurityScreen(state: GatewayUiState, viewModel: GatewayViewModel) {
val settings = state.settings ?: return
var newKey by remember { mutableStateOf("") }
var ip by remember { mutableStateOf("") }
var confirmDisableAuth by remember { mutableStateOf(false) }
var confirmEmptyAllowlist by remember { mutableStateOf(false) }
var showKeyDialog by remember { mutableStateOf(false) }
var pendingRemoval by remember { mutableStateOf<String?>(null) }
val keyConfigured = settings.apiKeyHash.isNotBlank()
val protected = settings.authenticationEnabled && keyConfigured
val score = when {
protected && settings.allowlistEnabled && settings.allowedIps.isNotEmpty() -> 82
protected -> 62
settings.authenticationEnabled -> 34
else -> 12
}
Column(
Modifier.verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 18.dp),
verticalArrangement = Arrangement.spacedBy(14.dp),
) {
ScreenHeader("Security", "Access control")
SecurityHero(protected, settings.allowlistEnabled, settings.allowedIps.size, score)
SectionLabel("Gateway authentication")
GatewayCard(Modifier.fillMaxWidth()) {
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(14.dp)) {
SettingToggleRow(
title = "Require API key",
description = "Authenticate every operational API request",
checked = settings.authenticationEnabled,
onCheckedChange = { enabled ->
if (!enabled && settings.authenticationEnabled) confirmDisableAuth = true
else viewModel.setAuthenticationEnabled(enabled)
},
)
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
Icon(Icons.Outlined.Key, contentDescription = null, tint = if (keyConfigured) GatewayPrimary else MaterialTheme.colorScheme.error)
Column(Modifier.weight(1f)) {
Text(if (keyConfigured) "API key configured" else "API key not configured", style = MaterialTheme.typography.labelLarge)
Text(
if (keyConfigured) "Stored securely as a one-way hash" else "A key of at least 16 characters is required",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
StatusBadge(if (keyConfigured) "Hidden" else "Required", if (keyConfigured) BadgeTone.SUCCESS else BadgeTone.WARNING)
}
if (!keyConfigured) {
OutlinedTextField(
value = newKey,
onValueChange = { newKey = it.take(256) },
label = { Text("New API key") },
supportingText = { Text("Minimum 16 characters") },
visualTransformation = PasswordVisualTransformation(),
singleLine = true,
shape = GatewayControlShape,
modifier = Modifier.fillMaxWidth(),
)
Button(
onClick = { viewModel.setApiKey(newKey); if (newKey.length >= 16) newKey = "" },
modifier = Modifier.fillMaxWidth(),
shape = GatewayControlShape,
) { Text("Set API key") }
} else {
OutlinedButton(onClick = { showKeyDialog = true }, modifier = Modifier.fillMaxWidth(), shape = GatewayControlShape) {
Text("Rotate API key")
}
}
}
}
SectionLabel("IP allowlist")
GatewayCard(Modifier.fillMaxWidth()) {
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(13.dp)) {
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
Column(Modifier.weight(1f)) {
Text("IP allowlist", style = MaterialTheme.typography.titleMedium)
Text("Only exact client IPs can call operations", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
StatusBadge(if (settings.allowlistEnabled) "Enabled" else "Off", if (settings.allowlistEnabled) BadgeTone.SUCCESS else BadgeTone.NEUTRAL)
}
SettingToggleRow(
title = "Enable allowlist",
description = "Documentation stays public; API operations are restricted",
checked = settings.allowlistEnabled,
onCheckedChange = { enabled ->
if (enabled && settings.allowedIps.isEmpty()) confirmEmptyAllowlist = true
else viewModel.setAllowlistEnabled(enabled)
},
)
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
OutlinedTextField(
value = ip,
onValueChange = { ip = it.take(45) },
label = { Text("IP address") },
singleLine = true,
shape = GatewayControlShape,
modifier = Modifier.weight(1f),
)
Button(
onClick = {
viewModel.addAllowedIp(ip)
if (SecurityPolicy.isValidIp(ip.trim())) ip = ""
},
shape = GatewayControlShape,
) { Text("Add") }
}
if (settings.allowedIps.isEmpty()) {
Text("No trusted client IPs added", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
} else {
settings.allowedIps.sorted().forEach { allowed ->
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(allowed, modifier = Modifier.weight(1f), style = MaterialTheme.typography.labelLarge, maxLines = 1, overflow = TextOverflow.Ellipsis)
TextButton(onClick = {
if (settings.allowlistEnabled && settings.allowedIps.size == 1) pendingRemoval = allowed
else viewModel.removeAllowedIp(allowed)
}) { Text("Remove", color = MaterialTheme.colorScheme.error) }
}
}
}
}
}
InfoBanner(
title = "Security notes",
body = "API keys and authentication headers are never written to logs. CIDR and HMAC signing can be added in a later phase.",
)
}
if (confirmDisableAuth) {
AlertDialog(
onDismissRequest = { confirmDisableAuth = false },
icon = { Icon(Icons.Outlined.Security, contentDescription = null) },
title = { Text("Disable API authentication?") },
text = { Text("Any client that can reach this device may call the API unless the IP allowlist blocks it.") },
confirmButton = {
Button(
onClick = { confirmDisableAuth = false; viewModel.setAuthenticationEnabled(false) },
colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.error),
) { Text("Disable") }
},
dismissButton = { TextButton(onClick = { confirmDisableAuth = false }) { Text("Keep enabled") } },
)
}
if (confirmEmptyAllowlist) {
AlertDialog(
onDismissRequest = { confirmEmptyAllowlist = false },
title = { Text("Enable an empty allowlist?") },
text = { Text("Every operational API client will be blocked until at least one IP address is added.") },
confirmButton = {
Button(onClick = { confirmEmptyAllowlist = false; viewModel.setAllowlistEnabled(true) }) { Text("Enable") }
},
dismissButton = { TextButton(onClick = { confirmEmptyAllowlist = false }) { Text("Cancel") } },
)
}
if (showKeyDialog) {
AlertDialog(
onDismissRequest = { showKeyDialog = false; newKey = "" },
title = { Text("Rotate API key") },
text = {
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text("The current backend key will stop working immediately.")
OutlinedTextField(
value = newKey,
onValueChange = { newKey = it.take(256) },
label = { Text("New API key") },
supportingText = { Text("Minimum 16 characters") },
visualTransformation = PasswordVisualTransformation(),
singleLine = true,
)
}
},
confirmButton = {
Button(onClick = {
viewModel.setApiKey(newKey)
if (newKey.length >= 16) { showKeyDialog = false; newKey = "" }
}) { Text("Rotate key") }
},
dismissButton = { TextButton(onClick = { showKeyDialog = false; newKey = "" }) { Text("Cancel") } },
)
}
pendingRemoval?.let { address ->
AlertDialog(
onDismissRequest = { pendingRemoval = null },
title = { Text("Remove the last allowed IP?") },
text = { Text("The allowlist will stay enabled and every operational API client will be blocked.") },
confirmButton = {
Button(
onClick = { viewModel.removeAllowedIp(address); pendingRemoval = null },
colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.error),
) { Text("Remove") }
},
dismissButton = { TextButton(onClick = { pendingRemoval = null }) { Text("Keep address") } },
)
}
}
@Composable
private fun SecurityHero(protected: Boolean, allowlist: Boolean, trustedClients: Int, score: Int) {
GatewayCard(
Modifier.fillMaxWidth(),
containerColor = GatewayPrimaryDark,
contentPadding = androidx.compose.foundation.layout.PaddingValues(18.dp),
) {
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(13.dp)) {
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
Box(Modifier.size(38.dp).clip(RoundedCornerShape(12.dp)).background(Color.White.copy(alpha = 0.08f)), contentAlignment = Alignment.Center) {
Icon(Icons.Outlined.Security, contentDescription = null, tint = GatewaySignal)
}
Column {
Text("Security posture", style = MaterialTheme.typography.bodySmall, color = Color.White.copy(alpha = 0.7f))
Text(if (protected) "Protected" else "Needs attention", style = MaterialTheme.typography.headlineMedium, color = Color.White)
}
}
Column(horizontalAlignment = Alignment.End) {
Text(score.toString(), style = MaterialTheme.typography.headlineLarge, color = GatewaySignal)
Text("/100", style = MaterialTheme.typography.labelSmall, color = Color.White.copy(alpha = 0.65f))
}
}
Text(
"Authentication ${if (protected) "active" else "needs setup"} · ${if (allowlist) "$trustedClients trusted clients" else "allowlist disabled"}",
style = MaterialTheme.typography.bodySmall,
color = Color.White.copy(alpha = 0.72f),
)
}
}
}
@@ -0,0 +1,156 @@
package com.androidsmsgateway.ui.screens
import android.content.Intent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.AdminPanelSettings
import androidx.compose.material.icons.outlined.Description
import androidx.compose.material.icons.outlined.Language
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.core.net.toUri
import com.androidsmsgateway.domain.ServerState
import com.androidsmsgateway.security.SecurityPolicy
import com.androidsmsgateway.ui.GatewayUiState
import com.androidsmsgateway.ui.components.BadgeTone
import com.androidsmsgateway.ui.components.ClickableSettingRow
import com.androidsmsgateway.ui.components.GatewayCard
import com.androidsmsgateway.ui.components.GatewayControlShape
import com.androidsmsgateway.ui.components.InfoBanner
import com.androidsmsgateway.ui.components.ScreenHeader
import com.androidsmsgateway.ui.components.SectionLabel
import com.androidsmsgateway.ui.components.SettingToggleRow
import com.androidsmsgateway.ui.components.StatusBadge
@Composable
fun ServerSettingsScreen(
state: GatewayUiState,
save: (String, String, Boolean) -> Unit,
permissions: () -> Unit,
) {
val settings = state.settings ?: return
val context = LocalContext.current
var port by remember(settings.port) { mutableStateOf(settings.port.toString()) }
var bind by remember(settings.bindAddress) { mutableStateOf(settings.bindAddress) }
var boot by remember(settings.startOnBoot) { mutableStateOf(settings.startOnBoot) }
var attempted by remember { mutableStateOf(false) }
val portValid = port.toIntOrNull()?.let { it in 1024..65535 } == true
val bindValid = SecurityPolicy.isValidIp(bind.trim())
val running = state.server.state == ServerState.RUNNING
Column(
Modifier.verticalScroll(rememberScrollState()).padding(horizontal = 16.dp, vertical = 18.dp),
verticalArrangement = Arrangement.spacedBy(14.dp),
) {
ScreenHeader("Server", "Network configuration")
GatewayCard(Modifier.fillMaxWidth()) {
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
Icon(Icons.Outlined.Language, contentDescription = null, tint = MaterialTheme.colorScheme.primary)
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
Text(if (running) "Listening now" else "HTTP listener", style = MaterialTheme.typography.titleMedium)
Text("${state.server.ipAddress}:${state.server.port}", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
StatusBadge(state.server.state.name, if (running) BadgeTone.SUCCESS else BadgeTone.NEUTRAL)
}
}
SectionLabel("Networking")
GatewayCard(Modifier.fillMaxWidth()) {
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(14.dp)) {
OutlinedTextField(
value = port,
onValueChange = { port = it.filter(Char::isDigit).take(5) },
label = { Text("HTTP port") },
supportingText = { Text(if (attempted && !portValid) "Enter a port from 1024 to 65535" else "Allowed range: 1024–65535") },
isError = attempted && !portValid,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
singleLine = true,
shape = GatewayControlShape,
modifier = Modifier.fillMaxWidth(),
)
OutlinedTextField(
value = bind,
onValueChange = { bind = it.take(45) },
label = { Text("Bind address") },
supportingText = { Text(if (attempted && !bindValid) "Enter a valid IPv4 or IPv6 address" else "Use 0.0.0.0 for all IPv4 interfaces") },
isError = attempted && !bindValid,
singleLine = true,
shape = GatewayControlShape,
modifier = Modifier.fillMaxWidth(),
)
SettingToggleRow(
title = "Start after device reboot",
description = "Restore the gateway when Android finishes booting",
checked = boot,
onCheckedChange = { boot = it },
)
Button(
onClick = {
attempted = true
if (portValid && bindValid) save(port, bind, boot)
},
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(13.dp),
) { Text(if (running) "Save, apply, and restart" else "Save and apply") }
if (running) {
Text(
"Saving network changes briefly restarts the running server.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
SectionLabel("Android access")
ClickableSettingRow(
title = "SMS permissions",
description = "Review Send SMS, Receive SMS, and notification access",
icon = Icons.Outlined.AdminPanelSettings,
onClick = permissions,
)
if (running) {
OutlinedButton(
onClick = {
val host = state.server.ipAddress.takeUnless { it == "Unavailable" } ?: "127.0.0.1"
context.startActivity(Intent(Intent.ACTION_VIEW, "http://$host:${state.server.port}/docs".toUri()))
},
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(13.dp),
) {
Icon(Icons.Outlined.Description, contentDescription = null)
Spacer(Modifier.size(8.dp))
Text("Open interactive API documentation")
}
}
InfoBanner(
title = "Trusted networks only",
body = "Plain HTTP is not encrypted. Use a private network, VPN, or TLS reverse proxy for remote access.",
warning = true,
)
}
}
@@ -0,0 +1,160 @@
package com.androidsmsgateway.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
val GatewayInk = Color(0xFF0B1F1B)
val GatewayPrimary = Color(0xFF246B57)
val GatewayPrimaryDark = Color(0xFF123E34)
val GatewaySignal = Color(0xFF59C8A5)
val GatewayMint = Color(0xFFD8F7EB)
val GatewayNetwork = Color(0xFF43A5BA)
val GatewayInfo = Color(0xFF2C6FB7)
val GatewayInfoBackground = Color(0xFFDCEBFF)
val GatewayWarning = Color(0xFFA06400)
val GatewayWarningBackground = Color(0xFFFFF0C8)
val GatewayError = Color(0xFFBA3A34)
val GatewayErrorBackground = Color(0xFFFFDAD6)
val GatewaySurface = Color(0xFFF5F8F6)
val GatewaySurfaceHigh = Color(0xFFEAF0ED)
val GatewayOutline = Color(0xFFD6DFDA)
val GatewayTextMuted = Color(0xFF63736E)
private val LightColors = lightColorScheme(
primary = GatewayPrimary,
onPrimary = Color.White,
primaryContainer = GatewayMint,
onPrimaryContainer = GatewayPrimaryDark,
secondary = GatewayNetwork,
onSecondary = Color.White,
secondaryContainer = GatewayInfoBackground,
onSecondaryContainer = Color(0xFF173F5C),
tertiary = GatewaySignal,
onTertiary = GatewayInk,
background = GatewaySurface,
onBackground = GatewayInk,
surface = Color.White,
onSurface = GatewayInk,
surfaceVariant = GatewaySurfaceHigh,
onSurfaceVariant = GatewayTextMuted,
outline = GatewayOutline,
error = GatewayError,
onError = Color.White,
errorContainer = GatewayErrorBackground,
onErrorContainer = Color(0xFF6C1714),
)
private val DarkColors = darkColorScheme(
primary = Color(0xFF77DDB8),
onPrimary = Color(0xFF00382B),
primaryContainer = Color(0xFF185240),
onPrimaryContainer = Color(0xFFAAF3D5),
secondary = Color(0xFF82D1DF),
onSecondary = Color(0xFF00363E),
secondaryContainer = Color(0xFF164C55),
onSecondaryContainer = Color(0xFFB5EBF3),
tertiary = Color(0xFF59C8A5),
onTertiary = Color(0xFF00382B),
background = Color(0xFF071814),
onBackground = Color(0xFFE1EEE8),
surface = Color(0xFF0D211C),
onSurface = Color(0xFFE1EEE8),
surfaceVariant = Color(0xFF17302A),
onSurfaceVariant = Color(0xFFB6C9C1),
outline = Color(0xFF38544B),
error = Color(0xFFFFB4AB),
onError = Color(0xFF690005),
errorContainer = Color(0xFF5B211F),
onErrorContainer = Color(0xFFFFDAD6),
)
private val GatewayTypography = androidx.compose.material3.Typography(
displaySmall = TextStyle(
fontFamily = FontFamily.SansSerif,
fontWeight = FontWeight.Bold,
fontSize = 36.sp,
lineHeight = 42.sp,
),
headlineLarge = TextStyle(
fontFamily = FontFamily.SansSerif,
fontWeight = FontWeight.Bold,
fontSize = 30.sp,
lineHeight = 36.sp,
),
headlineMedium = TextStyle(
fontFamily = FontFamily.SansSerif,
fontWeight = FontWeight.Bold,
fontSize = 24.sp,
lineHeight = 30.sp,
),
titleLarge = TextStyle(
fontFamily = FontFamily.SansSerif,
fontWeight = FontWeight.Bold,
fontSize = 20.sp,
lineHeight = 26.sp,
),
titleMedium = TextStyle(
fontFamily = FontFamily.SansSerif,
fontWeight = FontWeight.SemiBold,
fontSize = 16.sp,
lineHeight = 22.sp,
),
bodyLarge = TextStyle(
fontFamily = FontFamily.SansSerif,
fontWeight = FontWeight.Normal,
fontSize = 15.sp,
lineHeight = 22.sp,
),
bodyMedium = TextStyle(
fontFamily = FontFamily.SansSerif,
fontWeight = FontWeight.Normal,
fontSize = 14.sp,
lineHeight = 20.sp,
),
bodySmall = TextStyle(
fontFamily = FontFamily.SansSerif,
fontWeight = FontWeight.Normal,
fontSize = 12.sp,
lineHeight = 17.sp,
),
labelLarge = TextStyle(
fontFamily = FontFamily.SansSerif,
fontWeight = FontWeight.SemiBold,
fontSize = 14.sp,
lineHeight = 20.sp,
),
labelMedium = TextStyle(
fontFamily = FontFamily.SansSerif,
fontWeight = FontWeight.SemiBold,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.2.sp,
),
labelSmall = TextStyle(
fontFamily = FontFamily.SansSerif,
fontWeight = FontWeight.Medium,
fontSize = 10.sp,
lineHeight = 14.sp,
letterSpacing = 0.35.sp,
),
)
@Composable
fun GatewayTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable () -> Unit,
) {
MaterialTheme(
colorScheme = if (darkTheme) DarkColors else LightColors,
typography = GatewayTypography,
content = content,
)
}
+13
View File
@@ -0,0 +1,13 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="48dp"
android:height="48dp"
android:viewportWidth="48"
android:viewportHeight="48">
<path
android:fillColor="#006C4C"
android:pathData="M8,6h32a4,4 0,0 1,4 4v22a4,4 0,0 1,-4 4H20l-10,8v-8H8a4,4 0,0 1,-4 -4V10a4,4 0,0 1,4 -4z" />
<path
android:fillColor="#FFFFFF"
android:pathData="M12,16h24v4H12zM12,24h18v4H12z" />
</vector>
+4
View File
@@ -0,0 +1,4 @@
<resources>
<string name="app_name">SMS Gateway</string>
</resources>
+9
View File
@@ -0,0 +1,9 @@
<resources>
<style name="Theme.AndroidSmsGateway" parent="android:style/Theme.Material.Light.NoActionBar">
<item name="android:fontFamily">sans</item>
<item name="android:windowLightStatusBar">true</item>
<item name="android:statusBarColor">@android:color/transparent</item>
<item name="android:navigationBarColor">@android:color/white</item>
</style>
</resources>
+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<full-backup-content>
<exclude domain="root" path="." />
</full-backup-content>
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<data-extraction-rules>
<cloud-backup>
<exclude domain="root" path="." />
</cloud-backup>
<device-transfer>
<exclude domain="root" path="." />
</device-transfer>
</data-extraction-rules>
@@ -0,0 +1,66 @@
package com.androidsmsgateway.security
import com.androidsmsgateway.domain.GatewaySettings
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Test
class SecurityPolicyTest {
@Test
fun validBearerKeyIsAccepted() {
val settings = settings(apiKeyHash = SecurityPolicy.hashApiKey("a-secure-test-key"))
val result = SecurityPolicy.evaluate(
settings,
clientIp = "192.168.1.10",
headers = mapOf("authorization" to "Bearer a-secure-test-key"),
)
assertEquals(AccessDecision.ALLOWED, result)
}
@Test
fun missingAndInvalidKeysAreDifferentStableDecisions() {
val settings = settings(apiKeyHash = SecurityPolicy.hashApiKey("a-secure-test-key"))
assertEquals(AccessDecision.MISSING_CREDENTIALS, SecurityPolicy.evaluate(settings, "127.0.0.1", emptyMap()))
assertEquals(
AccessDecision.INVALID_CREDENTIALS,
SecurityPolicy.evaluate(settings, "127.0.0.1", mapOf("X-API-Key" to "wrong-key")),
)
}
@Test
fun allowlistRejectsAddressBeforeAuthentication() {
val settings = settings(
apiKeyHash = SecurityPolicy.hashApiKey("a-secure-test-key"),
allowlistEnabled = true,
allowedIps = setOf("10.0.0.5"),
)
assertEquals(
AccessDecision.IP_DENIED,
SecurityPolicy.evaluate(settings, "10.0.0.6", mapOf("X-API-Key" to "a-secure-test-key")),
)
}
@Test
fun hashesDoNotRevealOriginalKey() {
val hash = SecurityPolicy.hashApiKey("a-secure-test-key")
assertNotEquals("a-secure-test-key", hash)
assertEquals(64, hash.length)
}
private fun settings(
apiKeyHash: String,
allowlistEnabled: Boolean = false,
allowedIps: Set<String> = emptySet(),
) = GatewaySettings(
deviceId = "test-device",
port = 8080,
bindAddress = "127.0.0.1",
serverEnabled = false,
startOnBoot = false,
authenticationEnabled = true,
apiKeyHash = apiKeyHash,
allowlistEnabled = allowlistEnabled,
allowedIps = allowedIps,
)
}
@@ -0,0 +1,27 @@
package com.androidsmsgateway.server
import org.junit.Assert.assertFalse
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class ApiContractValidationTest {
@Test
fun phoneValidationAcceptsInternationalAndLocalDigits() {
assertTrue(ApiRouter.PHONE_REGEX.matches("+989121234567"))
assertTrue(ApiRouter.PHONE_REGEX.matches("09121234567"))
}
@Test
fun phoneValidationRejectsFormattingAndInjectionCharacters() {
assertFalse(ApiRouter.PHONE_REGEX.matches("+98 912 123 4567"))
assertFalse(ApiRouter.PHONE_REGEX.matches("+98912;DROP"))
assertFalse(ApiRouter.PHONE_REGEX.matches("12"))
}
@Test
fun requestLimitsRemainBounded() {
assertTrue(ApiRouter.MAX_BODY_BYTES <= 16_384)
assertEquals(160, ApiRouter.MAX_SMS_CHARACTERS)
}
}
@@ -0,0 +1,24 @@
package com.androidsmsgateway.sms
import android.app.Activity
import android.telephony.SmsManager
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class SmsStatusReceiverTest {
@Test
fun `activity result ok is successful`() {
assertTrue(SmsStatusReceiver.isSuccessfulResult(Activity.RESULT_OK))
}
@Test
fun `sms manager no error is successful`() {
assertTrue(SmsStatusReceiver.isSuccessfulResult(SmsManager.RESULT_ERROR_NONE))
}
@Test
fun `sms manager error is not successful`() {
assertFalse(SmsStatusReceiver.isSuccessfulResult(SmsManager.RESULT_ERROR_GENERIC_FAILURE))
}
}
+6
View File
@@ -0,0 +1,6 @@
plugins {
alias(libs.plugins.android.application) apply false
alias(libs.plugins.ksp) apply false
alias(libs.plugins.kotlin.compose) apply false
alias(libs.plugins.kotlin.serialization) apply false
}
+5
View File
@@ -0,0 +1,5 @@
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
android.useAndroidX=true
kotlin.code.style=official
android.nonTransitiveRClass=true
+12
View File
@@ -0,0 +1,12 @@
#This file is generated by updateDaemonJvm
toolchainUrl.FREE_BSD.AARCH64=https\://api.foojay.io/disco/v3.0/ids/ec7520a1e057cd116f9544c42142a16b/redirect
toolchainUrl.FREE_BSD.X86_64=https\://api.foojay.io/disco/v3.0/ids/4c4f879899012ff0a8b2e2117df03b0e/redirect
toolchainUrl.LINUX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/ec7520a1e057cd116f9544c42142a16b/redirect
toolchainUrl.LINUX.X86_64=https\://api.foojay.io/disco/v3.0/ids/4c4f879899012ff0a8b2e2117df03b0e/redirect
toolchainUrl.MAC_OS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/73bcfb608d1fde9fb62e462f834a3299/redirect
toolchainUrl.MAC_OS.X86_64=https\://api.foojay.io/disco/v3.0/ids/846ee0d876d26a26f37aa1ce8de73224/redirect
toolchainUrl.UNIX.AARCH64=https\://api.foojay.io/disco/v3.0/ids/ec7520a1e057cd116f9544c42142a16b/redirect
toolchainUrl.UNIX.X86_64=https\://api.foojay.io/disco/v3.0/ids/4c4f879899012ff0a8b2e2117df03b0e/redirect
toolchainUrl.WINDOWS.AARCH64=https\://api.foojay.io/disco/v3.0/ids/9482ddec596298c84656d31d16652665/redirect
toolchainUrl.WINDOWS.X86_64=https\://api.foojay.io/disco/v3.0/ids/39701d92e1756bb2f141eb67cd4c660e/redirect
toolchainVersion=21
+45
View File
@@ -0,0 +1,45 @@
[versions]
agp = "9.2.1"
kotlin = "2.3.21"
coreKtx = "1.19.0"
activityCompose = "1.13.0"
composeBom = "2026.06.00"
junit = "4.13.2"
ksp = "2.3.10"
room = "2.8.4"
lifecycle = "2.11.0"
coroutines = "1.11.0"
serialization = "1.11.0"
nanohttpd = "2.3.1"
swaggerUi = "5.32.1"
androidxTest = "1.3.0"
espresso = "3.7.0"
[libraries]
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3" }
androidx-compose-material-icons-extended = { group = "androidx.compose.material", name = "material-icons-extended" }
androidx-compose-ui = { group = "androidx.compose.ui", name = "ui" }
androidx-compose-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }
androidx-compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
junit = { group = "junit", name = "junit", version.ref = "junit" }
androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycle" }
androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycle" }
androidx-room-runtime = { group = "androidx.room", name = "room-runtime", version.ref = "room" }
androidx-room-ktx = { group = "androidx.room", name = "room-ktx", version.ref = "room" }
androidx-room-compiler = { group = "androidx.room", name = "room-compiler", version.ref = "room" }
androidx-test-junit = { group = "androidx.test.ext", name = "junit", version.ref = "androidxTest" }
androidx-test-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espresso" }
kotlinx-coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-android", version.ref = "coroutines" }
kotlinx-coroutines-test = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-test", version.ref = "coroutines" }
kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "serialization" }
nanohttpd = { group = "org.nanohttpd", name = "nanohttpd", version.ref = "nanohttpd" }
swagger-ui = { group = "org.webjars", name = "swagger-ui", version.ref = "swaggerUi" }
[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }
ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
Binary file not shown.
+7
View File
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+248
View File
@@ -0,0 +1,248 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/2d6327017519d23b96af35865dc997fcb544fb40/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
Vendored
+93
View File
@@ -0,0 +1,93 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+344
View File
@@ -0,0 +1,344 @@
openapi: 3.1.0
info:
title: Android SMS Gateway API
version: 1.0.0
description: |
Direct HTTP API exposed by the Android SMS Gateway. Authentication is configurable
on the device and enabled by default. Plain HTTP must only be used on trusted networks.
servers:
- url: /
description: Gateway currently serving this documentation
- url: http://{device_ip}:{port}
description: Explicit gateway address for generated clients
variables:
device_ip:
default: 192.168.1.50
port:
default: '8080'
security:
- bearerAuth: []
- apiKeyAuth: []
tags:
- name: Gateway
- name: SMS
paths:
/docs:
get:
tags: [Gateway]
summary: Open interactive API documentation
description: Returns the locally bundled Swagger UI. This documentation page is public; API operations remain protected.
operationId: getApiDocumentation
security: []
responses:
'200':
description: Interactive Swagger UI page
content:
text/html:
schema:
type: string
/docs/openapi.yaml:
get:
tags: [Gateway]
summary: Download the OpenAPI contract
description: Returns the exact OpenAPI YAML document packaged with the installed app.
operationId: getOpenApiDocument
security: []
responses:
'200':
description: OpenAPI 3.1 YAML contract
content:
application/yaml:
schema:
type: string
/api/v1:
get:
tags: [Gateway]
summary: Get API information
operationId: getApiInfo
responses:
'200':
description: API capabilities and endpoints
content:
application/json:
schema: { $ref: '#/components/schemas/ApiInfo' }
'401': { $ref: '#/components/responses/Unauthorized' }
'403': { $ref: '#/components/responses/Forbidden' }
'503': { $ref: '#/components/responses/Unavailable' }
/api/v1/health:
get:
tags: [Gateway]
summary: Check gateway health
operationId: getHealth
responses:
'200':
description: Healthy gateway
content:
application/json:
schema: { $ref: '#/components/schemas/Health' }
example:
status: ok
device_id: 897d0bd6-e29d-4a65-a07a-e73f01b0056c
app_version: 0.1.0
android_version: '16'
device_model: Google Pixel
ip: 192.168.1.50
port: 8080
uptime: 12345
'401': { $ref: '#/components/responses/Unauthorized' }
'403': { $ref: '#/components/responses/Forbidden' }
'503': { $ref: '#/components/responses/Unavailable' }
/api/v1/status:
get:
tags: [Gateway]
summary: Get operational status and counters
operationId: getStatus
responses:
'200':
description: Current gateway status
content:
application/json:
schema: { $ref: '#/components/schemas/GatewayStatus' }
'401': { $ref: '#/components/responses/Unauthorized' }
'403': { $ref: '#/components/responses/Forbidden' }
'503': { $ref: '#/components/responses/Unavailable' }
/api/v1/sms/send:
post:
tags: [SMS]
summary: Submit an SMS
description: Accepts one message of at most 160 characters. HTTP 202 does not mean carrier delivery.
operationId: sendSms
requestBody:
required: true
content:
application/json:
schema: { $ref: '#/components/schemas/SendSmsRequest' }
example:
to: '+989121234567'
message: Hello
responses:
'202':
description: Accepted for Android submission
content:
application/json:
schema: { $ref: '#/components/schemas/SendSmsResponse' }
example:
success: true
id: 243fdc31-874a-4be1-823d-5c08575805ca
status: pending
'400': { $ref: '#/components/responses/BadRequest' }
'401': { $ref: '#/components/responses/Unauthorized' }
'403': { $ref: '#/components/responses/Forbidden' }
'411':
description: Content-Length header is required
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
'413':
description: Request exceeds 16 KiB
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
'422':
description: Invalid recipient or message
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
'503': { $ref: '#/components/responses/Unavailable' }
/api/v1/sms/messages:
get:
tags: [SMS]
summary: List persisted SMS messages
operationId: listMessages
parameters:
- name: page
in: query
schema: { type: integer, minimum: 1, default: 1 }
- name: page_size
in: query
schema: { type: integer, minimum: 1, maximum: 100, default: 50 }
- name: direction
in: query
schema: { type: string, enum: [all, incoming, outgoing], default: all }
- name: search
in: query
schema: { type: string, maxLength: 200 }
responses:
'200':
description: Message page ordered newest first
content:
application/json:
schema: { $ref: '#/components/schemas/MessagePage' }
'401': { $ref: '#/components/responses/Unauthorized' }
'403': { $ref: '#/components/responses/Forbidden' }
'422':
description: Invalid direction
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
'503': { $ref: '#/components/responses/Unavailable' }
/api/v1/sms/messages/{id}:
get:
tags: [SMS]
summary: Get a persisted message
operationId: getMessage
parameters:
- name: id
in: path
required: true
schema: { type: string, minLength: 1, maxLength: 100 }
responses:
'200':
description: Message details
content:
application/json:
schema: { $ref: '#/components/schemas/SmsMessage' }
'401': { $ref: '#/components/responses/Unauthorized' }
'403': { $ref: '#/components/responses/Forbidden' }
'404':
description: Message not found
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
'503': { $ref: '#/components/responses/Unavailable' }
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: API key
apiKeyAuth:
type: apiKey
in: header
name: X-API-Key
responses:
BadRequest:
description: Malformed JSON request
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
Unauthorized:
description: Missing or invalid API key
headers:
WWW-Authenticate:
schema: { type: string }
description: Authentication challenge may be omitted by the MVP transport
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
example:
success: false
error: { code: INVALID_API_KEY, message: API credentials are invalid }
Forbidden:
description: Client IP is outside the allowlist
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
Unavailable:
description: Gateway security or SMS subsystem is unavailable
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
schemas:
ApiInfo:
type: object
required: [api_version, gateway_version, capabilities, endpoints]
properties:
api_version: { type: string, const: v1 }
gateway_version: { type: string }
capabilities: { type: array, items: { type: string } }
endpoints: { type: array, items: { type: string } }
Health:
type: object
required: [status, device_id, app_version, android_version, device_model, ip, port, uptime]
properties:
status: { type: string, const: ok }
device_id: { type: string, format: uuid }
app_version: { type: string }
android_version: { type: string }
device_model: { type: string }
ip: { type: string }
port: { type: integer, minimum: 1024, maximum: 65535 }
uptime: { type: integer, minimum: 0, description: Seconds }
GatewayStatus:
type: object
required: [success, server_status, ip, port, uptime, requests, sent_sms, received_sms]
properties:
success: { type: boolean, const: true }
server_status: { type: string, enum: [stopped, starting, running, stopping, error] }
ip: { type: string }
port: { type: integer }
uptime: { type: integer, minimum: 0, description: Seconds }
requests: { type: integer, minimum: 0 }
sent_sms: { type: integer, minimum: 0, description: Total outgoing rows, including pending and failed }
received_sms: { type: integer, minimum: 0 }
SendSmsRequest:
type: object
additionalProperties: false
required: [to, message]
properties:
to:
type: string
pattern: '^\+?[0-9]{3,20}$'
message:
type: string
minLength: 1
maxLength: 160
SendSmsResponse:
type: object
required: [success, id, status]
properties:
success: { type: boolean, const: true }
id: { type: string, format: uuid }
status: { type: string, const: pending }
SmsMessage:
type: object
required: [id, direction, message, timestamp, status]
properties:
id: { type: string, format: uuid }
direction: { type: string, enum: [incoming, outgoing] }
sender: { type: [string, 'null'] }
recipient: { type: [string, 'null'] }
message: { type: string }
timestamp: { type: integer, description: Unix epoch milliseconds }
status: { type: string, enum: [received, pending, sent, failed] }
error_code: { type: [string, 'null'] }
MessagePage:
type: object
required: [success, page, page_size, messages]
properties:
success: { type: boolean, const: true }
page: { type: integer, minimum: 1 }
page_size: { type: integer, minimum: 1, maximum: 100 }
messages:
type: array
items: { $ref: '#/components/schemas/SmsMessage' }
ErrorResponse:
type: object
required: [success, error]
properties:
success: { type: boolean, const: false }
error:
type: object
required: [code, message]
properties:
code:
type: string
enum:
- INVALID_JSON
- INVALID_RECIPIENT
- EMPTY_MESSAGE
- MESSAGE_TOO_LONG
- INVALID_DIRECTION
- LENGTH_REQUIRED
- PAYLOAD_TOO_LARGE
- AUTHENTICATION_REQUIRED
- INVALID_API_KEY
- AUTHENTICATION_NOT_CONFIGURED
- IP_NOT_ALLOWED
- SMS_PERMISSION_DENIED
- SMS_SEND_FAILED
- MESSAGE_NOT_FOUND
- NOT_FOUND
- METHOD_NOT_ALLOWED
- INTERNAL_ERROR
message: { type: string }
+19
View File
@@ -0,0 +1,19 @@
pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "AndroidSmsGateway"
include(":app")