Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,7 @@ gradle.properties
COOKIES.txt
HTTP_FUNDAMENTALS.txt
ROUTING.txt

# Spec-driven planning files -- kept local
.specify/
specs/
18 changes: 13 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

**Aviary is live — just open it in your browser:**

### 👉 https://aviarist-d300b0c36379.herokuapp.com/login
### 👉 https://aviary.danielibarra.com

No install, no setup, nothing to download. Register a username + password and you're in. Everything below is for people who want to *develop* Aviary; if you just want to *use* it, the link above is all you need.

Expand All @@ -13,8 +13,8 @@ No install, no setup, nothing to download. Register a username + password and yo
A multi-user maintenance and flight-hours tracker for general-aviation aircraft owners:

- **Service timeline** — track every recurring maintenance item (annual, transponder/pitot-static tests, VOR checks, oil changes, etc.) on a **calendar cycle** (days/months/years) *or* an **engine-hours cycle**. Each row shows last-done, next-due, and live "time left," and a one-click **Complete Maintenance** button rolls the dates and hours forward automatically.
- **Hours tracking** — Hobbs and Tach meters with a manual baseline "floor," so log-book activity can only ever raise the displayed hours, never silently lower them.
- **Log book** — record flights by hand (from/to airport, Hobbs/Tach out and in) **or import a Garmin avionics CSV** and let the app derive block time (oil pressure > 15 psi) and airborne time (groundspeed > 35 kt) for you.
- **Hours tracking** — block time and time in service, each with a manual baseline "floor," so log-book activity can only ever raise the displayed hours, never silently lower them.
- **Log book** — record flights by hand (from/to airport, block time and time in service out and in) **or import a Garmin avionics CSV** and let the app derive block time (oil pressure > 15 psi) and airborne time (groundspeed > 35 kt) for you.
- **Aircraft info card** — make/model, tail number, owner, and serial number, editable inline.

Each account is fully isolated — its own aircraft, service timeline, flight logs, and custom maintenance descriptions. Ownership is enforced server-side on every write.
Expand All @@ -24,9 +24,17 @@ Each account is fully isolated — its own aircraft, service timeline, flight lo
1. **Register** at the link above (or **log in**).
2. **Fill in your aircraft info** — make/model, tail number, owner, serial.
3. **Build your service timeline** — add maintenance items with a calendar or hours cycle. Rows are drag-reorderable, and you can insert title rows to group them.
4. **Set your hours** — enter current Hobbs and Tach manually, or let the log book keep them current.
4. **Set your hours** — enter current block time and time in service manually, or let the log book keep them current.
5. **Log flights** — add entries by hand, or upload a Garmin CSV and Aviary computes the times and updates your meters.

## Connect an AI assistant

Aviary is also an MCP server, so an AI assistant can import your existing maintenance records — a spreadsheet, a typed list, another tracker's export — into your service timeline.

Add `https://aviary.danielibarra.com/mcp` as a remote (HTTP) MCP server in any assistant that supports MCP, then sign in when it asks.

You sign in on Aviary's own login page and approve access; the assistant never sees your password. Then hand it your records and ask it to import them. It shows you a **proposal** first — the items it will add, anything it isn't sure about, and any rows it couldn't use and why. Nothing is added until you tell it to go ahead, and it never changes or deletes items you already have. See or disconnect assistants any time under the robot icon on the dashboard (**Connected assistants**).

---

## Local development
Expand Down Expand Up @@ -84,7 +92,7 @@ push to main
```

- **Staging** (`aviarist-staging`) is deployed on every push to `main`, authenticated with the `HEROKU_API_KEY` GitHub Actions secret.
- **Production** (`aviarist-d300b0c36379`, the link at the top) is a separate app, promoted from staging deliberately once it looks good.
- **Production** (Heroku app `aviarist-d300b0c36379`, served at the link at the top) is a separate app, promoted from staging deliberately once it looks good.
- Heroku runs the app from the `Procfile` (`java -jar build/libs/AviaryService-0.0.1-SNAPSHOT.jar`) on Java 21 (`system.properties`). Schema changes apply via Hibernate `ddl-auto=update`.

## Architecture
Expand Down
4 changes: 4 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ dependencies {
implementation 'com.h2database:h2:2.2.224'
implementation 'org.apache.poi:poi:5.4.1'
implementation 'org.springframework.ai:spring-ai-starter-mcp-server-webmvc'
// OAuth sign-in for MCP clients: Aviary issues the tokens (authorization server)
// and /mcp checks them (resource server).
implementation 'org.springframework.boot:spring-boot-starter-oauth2-authorization-server'
implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
// Source: https://mvnrepository.com/artifact/software.amazon.awssdk/ses
implementation("software.amazon.awssdk:sesv2:2.56.0")
// Server-side PDF rendering for Download PDF (docs/specs/SHARE_EXPORT_SPEC.md) --
Expand Down
5 changes: 3 additions & 2 deletions docs/architecture/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,13 @@ Spring Boot 3.4.3 · Java 21 · Spring MVC + Security + Data JPA · Thymeleaf ·
1. Browser loads `GET /dashboard` → `UserController` fetches the user's timelines, flight logs, hours, aircraft info → Thymeleaf renders `dashboard.html`.
2. User edits a cell → `dashboard.js` debounces and `POST`s JSON via axios (with the Spring CSRF token from `<meta>`) to an endpoint like `/update/{id}`.
3. Controller updates the entity via the repository and returns JSON.
4. "Time Left" is computed **client-side** from the due date + current Tach hours.
4. "Time Left" is computed **client-side** from the due date + current time in service hours.

## Cross-cutting concerns
- **Auth:** Spring Security form login, BCrypt passwords, single `USER` role. See [BACKEND](BACKEND.md#auth).
- **Per-user scoping:** every entity has a `user_id`; queries filter by the authenticated user. See [DATABASE](DATABASE.md).
- **Hours model:** flight logs roll up into `User.hobbsHours` / `tachHours`, which maintenance due-dates count against.
- **AI assistants (MCP):** `/mcp` is an MCP server secured by Aviary's own OAuth authorization server (CIMD clients, PKCE, opaque hashed tokens). Assistants preview and import service timeline items; nothing is saved until the owner confirms. See [BACKEND](BACKEND.md#mcp-server--ai-assistant-sign-in).
- **Hours model:** flight logs roll up into `User.blockTimeHours` / `timeInServiceHours`, which maintenance due-dates count against.

## Known issues (high level — details in the area maps)
- Local dev uses **in-memory H2** (data is lost on restart). See [DATABASE](DATABASE.md).
Expand Down
15 changes: 11 additions & 4 deletions docs/architecture/BACKEND.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
`SecurityConfig`:
- `BCryptPasswordEncoder` bean.
- `UserDetailsService` looks up `UserRepository.findByUsername`, builds a Spring user with role `USER`. Throws `UsernameNotFoundException` if missing.
- Filter chain: `/register`, `/login`, `/css/**`, `/js/**`, `/images/**` are public; **everything else requires auth**. Form login at `/login`, success → `/dashboard`. Logout at `POST /logout` → `/login?logout`.
- Filter chains, in order: (0) OAuth authorization server endpoints (`oauth/AuthorizationServerConfig`), (1) `/mcp` bearer-token resource server, (2) static assets, (3) everything else. In the main chain `/register`, `/login`, `/css/**`, `/js/**`, `/images/**`, `/.well-known/oauth-protected-resource` are public; **everything else requires auth**. Form login at `/login`, success → `/dashboard` (or back to `/oauth2/authorize` when the login interrupted an assistant's sign-in). Logout at `POST /logout` → `/login?logout`.
- CSRF is on (Spring default); the frontend sends the token from `<meta name="_csrf">`. Exempt: `POST /alerts/confirm|decline|unsubscribe` (their unguessable token is the auth).
- **Login lockout:** `LoginAttemptService` counts wrong passwords per username (5 in 15 min). `UserDetailsService` then builds the user with `accountLocked(true)`, so Spring refuses before checking the password; a custom failure handler sends a `LockedException` to `/login?locked` (other failures → `/login?error`). A successful login clears the count. In memory: resets on restart, per dyno.
- **Emailed alert links:** `GET /alerts/confirm|decline|unsubscribe?token=` only renders a one-button page; the button POSTs to the same path to change state. Mail scanners open every link, so a state-changing GET would confirm/unsubscribe people on its own.
Expand All @@ -34,16 +34,16 @@
| DELETE | `/delete/{id}` | — | 200 / 403 / 404 | deletes a timeline row. Ownership checked (403 if not owner) |
| POST | `/updateOrder` | `List<Long>` ids | void | reorders timelines; user-scoped, matches ids with `.equals` |
| POST | `/updateUserInfo` | JSON aircraft fields | status JSON | updates makeModel/tailNumber/ownerName/makeModelSN for auth user |
| POST | `/updateHours` | `hobbsTimeToAdd`/`tachTimeToAdd`/`newHobbsTime`/`newTachTime` | hours JSON | set-or-add Hobbs/Tach. 400 for NaN/Infinity, a negative set value, or an add that would go below 0 (checked before anything changes) |
| POST | `/updateHours` | `blockTimeToAdd`/`timeInServiceToAdd`/`newBlockTime`/`newTimeInService` | hours JSON | set-or-add block time / time in service. 400 for NaN/Infinity, a negative set value, or an add that would go below 0 (checked before anything changes) |
| GET | `/flightlogs` | — | `List<FlightLog>` JSON | auth user's logs |
| POST | `/addflightlog` | `FlightLog` JSON | log + new totals JSON | recomputes hours via `calculateMergedHours` |
| DELETE | `/deleteflightlog/{id}` | — | status + new totals | **ownership checked** (403 if not owner) |
| DELETE | `/deleteOption/{id}` | — | text | description option; **ownership checked** (403 if not owner) |

## Key logic
- **`calculateMergedHours(logs, useHobbs)`** — sums flight time across all logs by **merging overlapping intervals** so overlapping flights don't double-count. Hobbs uses `hobbsOut`/`hobbsIn`; Tach uses `tachIn`/`tachOut`. Result is written back to `User.hobbsHours`/`tachHours` on add/delete of a log.
- **`calculateMergedHours(logs, useBlockTime)`** — sums flight time across all logs by **merging overlapping intervals** so overlapping flights don't double-count. Block time uses `blockTimeOut`/`blockTimeIn`; time in service uses `timeInServiceOut`/`timeInServiceIn`. Result is written back to `User.blockTimeHours`/`timeInServiceHours` on add/delete of a log.
- **`saveCustomDescriptionOption`** — persists a user's custom Service Timeline "Description" values so they reappear in the dropdown.
- **Hours "last updated" stamps:** `/updateHours` sets `hobbsUpdatedAt`/`tachUpdatedAt` (UTC `Instant`) + `*UpdatedSource = "manual"` for whichever value changed; `/addflightlog` and `/deleteflightlog` set both with source `"flightlog"`. `GET /dashboard` passes the 4 values (timestamps as ISO strings) to the view, which renders them in the browser's local time.
- **Hours "last updated" stamps:** `/updateHours` sets `blockTimeUpdatedAt`/`timeInServiceUpdatedAt` (UTC `Instant`) + `*UpdatedSource = "manual"` for whichever value changed; `/addflightlog` and `/deleteflightlog` set both with source `"flightlog"`. `GET /dashboard` passes the 4 values (timestamps as ISO strings) to the view, which renders them in the browser's local time.

## Time Left + PDF
- `DueDates.formatTimeLeft(dueDate, dueHours, today, currentTimeInService)` is the one server-side Time Left formatter (smart format, see [FRONTEND](FRONTEND.md)). Used by `PdfExportService` (computed at render time — the stored `timeLeft` column goes stale) and `/completeMaintenance/{id}`.
Expand All @@ -52,6 +52,13 @@
## Local demo data
`config/DemoDataSeeder` (`@Profile({"h2","main"})`, never Heroku/tests) creates **demo / Demo-pass-123** once: section titles, items due at every Time Left scale, 6 chained flight logs, 3 pending + 1 dismissed AeroAPI suggestions. Delete the `demo` user to regenerate with fresh relative dates.

## MCP server + AI assistant sign-in
Aviary is an MCP server at `POST /mcp` (Spring AI, Streamable HTTP, SYNC) and its own OAuth authorization server, so AI assistants sign in as an owner.
- **Sign-in:** authorization code + PKCE (S256 only), public clients only. Assistants identify with a **Client ID Metadata Document**: `client_id` is an https URL that `CimdFetcher` downloads (SSRF-guarded: https, no IP literals, no private/loopback/link-local DNS, no redirects, 5 KB, 5 s) and `CimdRegisteredClientRepository` turns into a client (cached 1 h). Dynamic Client Registration is off. Loopback redirect URIs may use any port (`AuthorizationServerConfig.validateRedirectUri`). Owner approves on `/oauth2/consent` (`ConsentController`).
- **Tokens:** opaque, 7 days, no refresh tokens (Spring Authorization Server 1.4 gives public clients none). Stored by `JpaOAuth2AuthorizationService` in `oauth_authorizations` with token values **SHA-256 hashed**. `LocalOpaqueTokenIntrospector` checks every `/mcp` call against that table, so **Disconnect** (`/account/connections`, deletes the row) cuts an assistant off on its next request. No/dead token → 401 with `WWW-Authenticate: Bearer resource_metadata=…`; token without `aviary.read` → 403.
- **Tools** (`mcp/`): `list_flights`, `get_import_format`, `list_service_timeline`, `propose_timeline_import`, `continue_poor_fit`, `confirm_timeline_import`. Each checks its scope and gets the owner from `McpCurrentUser` (the token's user — never a parameter).
- **Import:** `TimelineImportService` + pure `util/TimelineImportRules`. Propose stores an `import_proposals` row (24 h, one open per owner) and changes nothing; confirm adds exactly the proposed rows after the existing ones in one transaction (all or nothing), never edits existing rows, skips name matches unless the owner opts in, and writes a `timeline_import_records` row. Rate limits: 30 proposals / 10 confirms per owner per hour.

## Input limits & rate limits
- **Text length:** every text column is varchar(255). `Validation.maxLength` checks item/description/aircraft fields/airports/description options up front and returns a 400 with a readable message; `GlobalExceptionHandler` catches anything missed. The AeroAPI key is capped at 100 chars (it's stored encrypted, which roughly doubles its length).
- **Outbound email:** `OutboundEmailLimiter` allows 10 user-triggered emails per user per hour — alert recipient invites/resends and `POST /pdf/email` — then 429. Scheduled digests and "Send alert now" aren't counted (the latter has per-recipient limits in `sendDigest`). Max 10 alert recipients per user.
Expand Down
12 changes: 12 additions & 0 deletions docs/architecture/DATABASE.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,18 @@ One-to-many (cascade ALL) → `serviceTimeline`, `flightLogs`.
### `flight_suggestions` (`FlightSuggestion`)
`id`, `tailNumber`, `faFlightId` (unique per user), `departureTime`, `arrivalTime` (`Instant`), `origin`, `destination`, `status` (String "pending" | "accepted" | "dismissed"), `createdAt`, `user_id`. AeroAPI-detected flights awaiting a user decision — see `docs/ADSB_SYNC_SPEC.md`.

### `import_proposals` (`ImportProposal`)
`id`, `user_id` (not null), `status` ("OPEN" | "NEEDS_FIT_CONFIRMATION" | "CONFIRMED" | "REPLACED" | "EXPIRED"), `itemsJson` / `rejectedJson` (TEXT, JSON lists), `submittedCount`, `createdAt`, `expiresAt` (+24 h), `confirmedAt`, `connectionClientId`. An AI assistant's previewed timeline import; at most one OPEN/NEEDS_FIT_CONFIRMATION per user.

### `timeline_import_records` (`TimelineImportRecord`)
`id`, `user_id` (not null), `proposalId`, `clientId`, `clientName`, `itemCount`, `importedAt`. One row per confirmed import; shown on Connected assistants.

### `oauth_authorizations` (`OAuthAuthorizationEntity`) — no `user_id`
String `id`, `registeredClientId` (assistant's CIMD URL), `principalName` (username), scopes, attributes (TEXT), and the authorization code / access token / refresh token **SHA-256 hashes** with issued/expires/metadata, plus `clientName`, `lastUsedAt`. One row = one connected assistant; deleting it disconnects. Keyed by username rather than FK because Spring Authorization Server works in principal names.

### `oauth_consents` (`OAuthConsentEntity`) — no `user_id`
Composite key (`registeredClientId`, `principalName`), `authorities`. Approved scopes per assistant per owner.

## Relationships
`User` 1—* `ServiceTimeline`, `FlightLog` (both cascade ALL, JSON managed/back references to avoid serialization loops). `User` 1—* `DescriptionOption`, `FlightSuggestion` (FK only, no mapped collection on `User` — accessed via repository query).

Expand Down
Loading
Loading