29 Commits
Author SHA1 Message Date
rickyandClaude Opus 5.5 a5ca534fd1 2026.11.7: flight correction, configurable roles, invitations, read-only records viewer
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 20:09:41 -05:00
rickyandClaude Opus 5.5 d956cfbe83 Records package viewer: read-only, no account needed
SAM_VIEWER=true (set only by the records package's
viewer/docker-compose.yml) makes the app a read-only copy of an archive,
for whoever receives the records: `docker compose up`, then open
http://localhost:3000.

- At start (bin/docker-entrypoint → sam:viewer:prepare) the package's
  .sam.zip, mounted read-only, is imported once.
- No sign-in: everyone browses as a built-in account. Nothing can be
  changed: any request but GET/HEAD is refused, no role permission
  applies (so no edit buttons), and there's no sign-out or profile. A
  banner names the archive and when it was exported.
- It refuses to start, and every page answers 503, when the database
  has any other account, so turning it on for a real installation stops
  the app instead of exposing its records.
- The viewer listens on 127.0.0.1 only, and skips scheduled jobs
  (reminders, backups, AD searches).
- Docs: the package README (three steps now), Access & sharing, README
  settings and features, the suggested recordkeeping procedures.

Checked end to end with a built image and a real records package: the
archive imported at start, pages browsed without an account, a change
refused, and the container refusing to start once an account existed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 20:03:56 -05:00
rickyandClaude Opus 5.5 34e3232350 Records package viewer: setup code, release image
The viewer/docker-compose.yml in the records package (and the package's
README) said to just create an account, but first-run setup asks for a
one-time code from the log since 2026.11.5; both now say how to get it,
and the right menu for importing. The viewer runs the published image at
the release that made the package (each release is published under its
version), so whoever opens it later gets that version, not whatever
:latest is then. APP_IMAGE, for a fork, is used as it is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 19:40:01 -05:00
rickyandClaude Opus 5.5 3ad6b9493a Compose files and .env.example catch up
- The compose files' steps say where the first-run setup code is (it's
  asked for since 2026.11.5), that new accounts come from the admin, and
  who adds aircraft; the published image's release tags are mentioned.
- docker-compose.yml passes APP_REVISION/APP_BUILT_AT to the build when
  set, so a locally built image shows its build on Admin → About.
- .env.example lists the optional push notification keys, APP_LOCALE and
  APP_IMAGE, which the README documented but it didn't.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 19:35:45 -05:00
rickyandClaude Opus 5.5 9adbc3d0a8 Docs: maintenance pages follow roles, adding aircraft
The guide pages written before roles said "owners" for work Mechanics
now do too (logbook entries, corrections, asking someone to sign,
components, resolving squawks, reminders), and the Fleet page didn't say
who can add aircraft. The index lists roles, invitations and the new
setting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 19:30:29 -05:00
rickyandClaude Opus 5.5 c360edfce0 One way to add people on an aircraft
Since invitations from an aircraft's Access page only worked for existing
accounts, they did almost what "Add by email" does. The Access page keeps
adding people by email; new people come through the administrator (Admin
→ Users or Admin → Invitations), and outside mechanics through an Owner's
signing invitation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 19:18:19 -05:00
rickyandClaude Opus 5.5 9a20c91f5e Owners can invite mechanics again; who adds aircraft is an admin setting
- Admin → Settings → Who can add aircraft: administrators only (the
  default) or everyone. Adding an aircraft or importing a .sam.zip makes
  you its Owner, so this decides who can become one.
- A signing invitation from an Owner of the aircraft (or an
  administrator) lets the outside mechanic create an account for the
  invited address again, with a password or by signing in with SSO;
  checked when it's used. Others' signing invitations still need an
  existing account, and say so.
- Docs: who makes accounts, the new setting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 19:09:49 -05:00
rickyandClaude Opus 5.5 19bc3efa19 New accounts only from an administrator or an administrator's invitation
Anyone can add an aircraft and so manage its people, so invitations from
non-administrators could bring in new accounts without an administrator.

- An invitation makes a new account only if whoever made it is still an
  administrator when it's used; an aircraft's Access page invitations are
  for people who already have an account (its welcome page says so).
- Signing invitations no longer make accounts: the mechanic needs one
  first, and the owner is told when they don't have one.
- With SSO, "Continue with <provider>" on an administrator's invitation
  makes the account and accepts the invitation (only for its address when
  it has one), so invitations work without OIDC_AUTO_CREATE_USERS. That
  setting stays, documented as giving accounts without an invitation; the
  Authentik example now leaves it off.
- Docs: who makes accounts (guide, README, Authentik, .env.example, API).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 19:00:45 -05:00
rickyandClaude Opus 5.5 b4c7aaa3ff Invitation codes: a link that gives an account and roles
Ported from the original (InvitationCode), adapted to configurable roles.

- Admin → Invitations: a label, optionally one email address (only it can
  use the link, and it's emailed) and a name, how many uses (or
  unlimited), an expiry (or never), and a role on any aircraft (or none,
  for an account only).
- An aircraft's Access page: whoever manages its people invites to that
  aircraft, with only the roles they can give; they see and revoke its
  invitations.
- /join/<code>: shows what it gives; create an account (when password
  sign-in is on) or sign in, then accept. Existing accounts and SSO users
  accept too. A role someone already has on an aircraft stays.
- Roles are given as the invitation's creator (AircraftAccess), and only
  while they can still manage that aircraft's people. Codes are kept as
  digests and shown once; uses are counted under a lock; account creation
  and accepting are rate-limited; any invalid link gets the same answer.
- Docs: guide (Administration, Access & sharing), README, and why /join
  isn't on the Authentik bypass list. The README's not-yet-ported list
  now names Prometheus metrics, and no longer claims oil analysis import
  as new.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 18:50:58 -05:00
rickyandClaude Opus 5.5 a645778f26 Docs catch up with today's changes
- User guide: the connection status (red top bar, the ring), a weak
  signal counting as none for flights and squawks, the offline page for
  any other page, PDFs on phones, the activity log loading as you scroll,
  What's new on About, Aircraft access on Admin → Users, and grounding
  squawks notifying everyone on the aircraft.
- README: the configurable roles table, feature rows for phones and
  offline and the REST API, and rows that said "Owners can…".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 18:32:42 -05:00
rickyandClaude Opus 5.5 3e5d896662 Locked flight readings look locked
The tach and Hobbs fields of an earlier flight were disabled but looked
like any other field. Disabled fields now look it everywhere (grey,
muted text, a not-allowed cursor), and the flight form marks its locked
readings "Locked".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 17:58:47 -05:00
rickyandClaude Opus 5.5 d8cd462194 Configurable roles: Owner, Mechanic, Pilot, Viewer and custom roles
What people can do on an aircraft now comes from their role there, and
administrators set what each role allows (Admin → Roles).

- Roles are installation-wide sets of permissions (31, grouped as flying,
  squawks and notes, maintenance records, imports and exports, the
  aircraft, notifications). Seeing an aircraft's records needs none.
- Built in: Owner (always every permission, so an aircraft can always be
  managed), Mechanic (shop maintenance: logbook, signing, components,
  inspections, ADs, squawks, reminders), Pilot (what pilots could do
  before) and Viewer (view only). Administrators can change all but
  Owner's, and add their own; a role can be deleted once nobody has it.
- Existing owners and pilots keep exactly what they could do.
- Admin → Users → a user lists their role on every aircraft, to change,
  remove or add. On the aircraft's Access page, anyone who manages people
  hands out roles, but only an Owner can give or take away Owner, nobody
  changes their own (except administrators), and an aircraft always
  keeps an Owner (AircraftAccess).
- Controllers declare the permission each action needs; a request that
  changes something with none declared is refused (and raises in
  development and tests), and a test walks every route to check.
- Weekly reminders and overdue alerts go to roles that get reminders;
  the DRS reminder also needs Manage ADs. The API follows the person's
  role; its owners_only error is now not_permitted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 17:43:38 -05:00
rickyandClaude Opus 5.5 d2cd60c6a7 Flights can be corrected after they're saved
- Edit on a flight: owners can correct any flight; a pilot, the flights
  they logged (the same rule as its engine data).
- Date, airports, route, notes, oil and fuel (its oil and fuel records
  follow) and the attached files can always be changed.
- The meter readings only on the latest flight, while its tach in is
  still the aircraft's tach: the aircraft and installed components move
  by the difference, and with both readings the duration is worked out
  from them. On earlier flights they're locked (later flights started
  from them), pointing to Update Hours; the server ignores them too.
- Each correction is in the activity log with what changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 17:12:05 -05:00
rickyandClaude Opus 5.5 34879e7310 2026.11.6: PDFs on phones, connection status, weak signal, activity paging, REST API
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:40:10 -05:00
rickyandClaude Opus 5.5 e8b0cd030e What's new stays short as releases pile up
- Admin → About shows the running version's release notes, with a link
  to all releases.
- The What's new page keeps the running version (and any newer) open and
  folds each older release to one line, grouped by month: its version
  and a count of its changes, fixes and notes for administrators.
- CHANGELOG.md itself is unchanged and reads the same on GitHub; the
  app splits it into releases when shown (Changelog).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:38:45 -05:00
rickyandClaude Opus 5.5 e4bc3a5b7b Weak signal counts as no signal
With a signal so weak requests hang, the phone still says it's online, so
nothing fell back: Log Flight waited minutes with no feedback, and pages
never reached the offline page.

- Log Flight and Report Squawk say "Sending…" and, after 10 seconds
  without an answer (60 with photos), keep the entry on the device as
  with no signal. When the top bar is already red they keep it right
  away. If it got through after all, the copy sent later is dropped
  (same client_key).
- What's kept on the device isn't sent while the top bar is red, gives
  up after 15 seconds, and goes again as soon as the server answers.
- Every page of the app falls back to its kept copy or the offline page:
  after 10 seconds, then 3 while requests keep failing, and at once right
  after a failure. Downloads made while you wait (.sam.zip, records
  package, PDFs) have no time limit.

Checked on an Android 14 emulator with a connection that accepts
requests and never answers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:34:13 -05:00
rickyandClaude Opus 5.5 d9de1be562 Connection status in the top bar, as SilverBullet does
- The top bar (and the phone's status bar) turns red when the server
  can't be reached: the device is offline, or a request failed (signal
  but no internet, or the proxy answering for the app). While red it
  checks /up every 15 seconds and turns back on its own.
- A ring fills while pages are saved for offline use or flights and
  squawks logged offline are sent, with the percentage in its middle,
  and hides when done. While some wait to send, it's amber with how many.

Checked on an Android 14 emulator: airplane mode on and off, saving for
offline, and a flight logged offline then sent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:15:50 -05:00
rickyandClaude Opus 5.5 66fa5f4423 PDFs show on phones, drawn with PDF.js
Android shows nothing for a PDF in a frame and iPhones only its first
page. On touch screens the document viewer now draws every page with
PDF.js 6.5.438 (vendored in public/pdfjs/<version>/, loaded only there);
desktop browsers keep their own viewer in the frame.

- Pages are drawn as they come near the screen and let go once far from
  it, so a long manual doesn't use up a phone's memory.
- Only the parts of the file those pages need are downloaded: uploaded
  files now send Accept-Ranges, and PDF.js's background fetch of the
  whole file is off.
- JBIG2/JPEG 2000 scans decode (wasm, with JS fallbacks).

Checked on an Android 14 emulator with Chromium 160 (which reports
pdfViewerEnabled but can't show a PDF in a frame).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:15:45 -05:00
rickyandClaude Opus 5.5 2e8d789975 Activity log loads as you scroll
The activity log stopped at 200 events. It now loads 50 at a time, the
next page coming in a lazy frame as it scrolls into view (as Oil & Fuel
does), keeping the category filter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:15:33 -05:00
rickyandClaude Opus 5.5 e4c27c6ff7 API: draft logbook entries for signing
- POST /aircraft/:id/draft_batches turns a visit's work items into one
  unsigned entry per logbook, signed in the app (by a user with a
  certificate, or a mechanic through a returned or emailed invitation link).
- The squawks they resolve and inspections they complete (with their result)
  are held until every entry is signed, then applied, attributed to the last
  signer; draft_batch.completed webhook. A draft never clears a squawk alone.
- Drafts are for owners (integrations act for one, drafts:write scope);
  unsigned drafts can be withdrawn; lookup by external_ref.
- The signing and entry pages show where a draft came from and what signing
  will do.
- The suggested recordkeeping procedures describe the API once it's in use.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 19:11:38 -05:00
rickyandClaude Opus 5.5 bffdea937c REST API v1: tokens, read endpoints, squawks, webhooks
- Personal tokens (Profile → API tokens) act as their owner; integration
  tokens (Admin → Integrations) reach chosen aircraft and scopes, and their
  writes name the person they're for (SAM-On-Behalf-Of). Tokens are stored
  hashed, shown once, revocable, with last use recorded.
- GET aircraft, components, due list, inspections, ADs, logbook entries and
  squawks; POST/PATCH squawks with external_ref links to the other system.
- Idempotency-Key for safe retries, paging, JSON errors, rate limits.
- Record history keeps the token with each change (in the hashed payload).
- Webhooks (squawk created/updated/resolved, entry signed), HMAC-signed,
  retried, never sent to the server itself; deliveries listed for admins.
- The outbound address check is shared by AirTrail and webhooks; reporting a
  squawk is announced the same way from the form and the API.
- docs/guide/api.md: the API reference.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 19:05:10 -05:00
rickyandClaude Opus 5.5 ec0f43019f Favicon matches the app icon
The white plane in a blue ring on the dark rounded square, tuned to read
at 16 px, instead of the plane emoji (which looked different everywhere).
Adds favicon.ico (16/32/48) for browsers and tools that ask for it, busts
the cached SVG with ?v=2, and keeps it with the offline page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 14:37:30 -05:00
rickyandClaude Opus 5.5 291990412e 2026.11.5: faster photos, phone-friendly cards, profile layout, push diagnostics, hardening
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 13:33:22 -05:00
rickyandClaude Opus 5.5 a2672b99a3 Restore thumbnails for photos recorded without dimensions
Photos uploaded before image processing was installed are marked analyzed
with no width, so the "unreadable image" check showed them as file links.
Every resizable image gets a thumbnail again; one that can't be read still
falls back to the original when resizing fails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 13:26:28 -05:00
rickyandClaude Opus 5.5 908c943e21 Fix crashes found by fuzzing malformed input
- Components can't be made into a parent loop, and the parts tree walks
  stop safely if one exists (logbook entry and squawk resolution pages
  crashed).
- A rejected aircraft photo no longer breaks the edit page; empty photos
  are refused; images that can't be read aren't resized, and a failed
  resize sends the original instead of an error.
- Unsupported formats (/report.pdf…) answer 406; tampered upload
  references, out-of-range numbers and constraint violations get a form
  message instead of a 500; requests with null bytes are refused (400).
- Blank values in required columns with defaults take the default;
  optional links to records that don't exist are validation errors.
- Imports (oil report, logbook scans, .sam.zip) accept only uploaded files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 13:17:43 -05:00
rickyandClaude Opus 5.5 5876c07a1a Harden installs reachable from the internet without a proxy
- Refuse to start with a placeholder or short SECRET_KEY_BASE (under 32
  characters); warn and fail sam:doctor under 64. .env.example no longer
  ships a placeholder.
- First-run setup needs a one-time code printed only in the server log, so
  only whoever runs the server can create the admin account.
- AirTrail: the server resolves the address and connects to exactly that;
  never the server itself or link-local addresses (cloud metadata);
  private-network addresses only for admins or hosts in
  AIRTRAIL_ALLOWED_HOSTS.
- Host authorization when APP_HOST is set: APP_HOST, the APP_URL host,
  ALLOWED_HOSTS, localhost and IP addresses; /up exempt. A blocked name
  gets a short explanation instead of a blank 403.
- docker-compose.direct.yml: HTTPS without a proxy via Thruster's built-in
  Let's Encrypt (TLS_DOMAIN).
- Notes' Markdown no longer allows the unused class attribute.
- README, .env.example and the user guide updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 12:42:53 -05:00
rickyandClaude Opus 5.5 faae719b12 Profile: two columns on wide screens
The account and its security (sign-on, two-factor, sessions) on the left,
calendar, certificates, this device and integrations on the right; one
column on phones. The account form gets a title like the other cards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 12:10:32 -05:00
ricky e199e6feeb Add LICENSE file with public domain declaration 2026-11-14 12:07:29 -05:00
rickyandClaude Opus 5.5 d4b71d17a1 Smaller aircraft photos, one-row-per-item detail cards, push diagnostics
- Aircraft photos get 192px and 960x432 copies made on upload; the header,
  share page and Fleet cards use them (and the offline copies), instead of
  the full original.
- Flight, engine data, component and major record details show one label
  and value per row on phones (wide items no longer add grid columns).
- Profile re-records this device's push subscription on every visit, and
  says why if it can't; Send test delivers now and lists each device's
  result; Google's other push hosts are accepted; turning notifications on
  shows the browser's actual error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 11:55:11 -05:00
291 changed files with 7493 additions and 685 deletions

No files matched your search

+31 -6
View File
@@ -2,10 +2,11 @@
# block is required. Every setting is explained in the README.
# --- Required ----------------------------------------------------------
# Generate with: bin/rails secret (or: openssl rand -hex 64)
# Keep a copy somewhere safe off the server: signatures and stored secrets
# depend on it, and a restore needs the same one.
SECRET_KEY_BASE=change-me
# Generate with: bin/rails secret (or: openssl rand -hex 64). Anyone who knows
# it can sign in as anyone, so the app won't start with a placeholder or a
# short one. Keep a copy somewhere safe off the server: signatures and stored
# secrets depend on it, and a restore needs the same one.
SECRET_KEY_BASE=
# The host name people use to reach the app (used in email links).
APP_HOST=aircraft.example.com
@@ -13,9 +14,20 @@ APP_HOST=aircraft.example.com
# their own zone, from Profile or their device). Default UTC.
# TZ=America/New_York
# true: the app redirects to HTTPS and sets secure cookies (use behind a TLS
# proxy such as Traefik, Caddy or Cloudflare Tunnel). false: plain HTTP on a LAN.
# proxy such as Traefik, Caddy or Cloudflare Tunnel, or with TLS_DOMAIN).
# false: plain HTTP, only on a private network: passwords travel unencrypted.
FORCE_SSL=true
# --- HTTPS without a proxy (docker-compose.direct.yml) -------------------
# The app gets a Let's Encrypt certificate for this name itself (ports 80
# and 443 must reach it).
# TLS_DOMAIN=aircraft.example.com
# --- Allowed addresses ---------------------------------------------------
# Requests are answered only for APP_HOST (and the APP_URL host), localhost
# and IP addresses. Other names that should work, comma-separated:
# ALLOWED_HOSTS=sam.lan,aircraft.home.arpa
# --- Address -----------------------------------------------------------
# Full public URL, if it isn't https://APP_HOST (used for the single sign-on
# and Google Drive redirect URIs).
@@ -34,9 +46,14 @@ FORCE_SSL=true
# OIDC_CLIENT_ID=
# OIDC_CLIENT_SECRET=
# OIDC_PROVIDER_NAME=Authentik
# OIDC_AUTO_CREATE_USERS=false # true: create an account at first sign-in
# OIDC_AUTO_CREATE_USERS=false # true: an account at first sign-in for anyone the provider lets in, without an invitation
# OIDC_TRUST_EMAIL=false # true: link accounts by unverified email
# OIDC_ADMIN_GROUP= # members become admins (synced at sign-in)
# --- AirTrail ------------------------------------------------------------
# AirTrail servers on your private network that everyone may connect to
# (admins can always use private addresses), comma-separated host names:
# AIRTRAIL_ALLOWED_HOSTS=airtrail.lan
# PASSWORD_LOGIN=true # false: SSO only (invited mechanics then can't sign in)
# --- Sign-in security ----------------------------------------------------
@@ -47,6 +64,14 @@ FORCE_SSL=true
# LOGBOOK_AI_MODEL=claude-opus-5-5
# LOGBOOK_AI_EFFORT=high
# --- Push notifications --------------------------------------------------
# Optional: without them the app makes a pair once and keeps it in storage/vapid_keys.json.
# Changing the pair turns notifications off on every device until turned on again.
# VAPID_PUBLIC_KEY=
# VAPID_PRIVATE_KEY= # bin/rails runner 'k = WebPush.generate_key; puts k.public_key, k.private_key'
# --- Other ---------------------------------------------------------------
# APP_LOCALE=en # language, e.g. es for config/locales/es.yml
# APP_REPOSITORY_URL= # source link on Admin → About (for a fork)
# APP_IMAGE= # image for the records package's viewer, used as is (for a fork); default: the published one at this release
# RAILS_LOG_LEVEL=info
+65
View File
@@ -2,6 +2,71 @@
Each release has a **version** (year.month.release, e.g. 2026.11.0) and a **build** (the exact source commit, shown on Admin → About). The newest release is first.
## 2026.11.7
### Changes
- **Correct a flight.** Open it and choose **Edit**: the date, airports, route, notes, oil and fuel (its oil and fuel records follow) and its files can always be fixed. The meter readings only on the latest flight, while nothing else has changed the hours; the aircraft and its components then move by the difference. On earlier flights the readings are shown locked. Owners can correct any flight; pilots, the ones they logged.
- **Roles you can set up.** Each person has a role on each aircraft: **Owner**, **Mechanic** (maintenance records, signing, components, inspections, ADs, squawks, reminders), **Pilot** (as before) or **Viewer** (sees everything, changes nothing). Owners and pilots keep exactly what they could do. Buttons for what your role doesn't allow aren't shown.
- **Reminders and overdue alerts** go to the roles that get them: Owners and Mechanics, as roles come.
- **Records package viewer, with no account.** The package's `viewer/docker-compose.yml` now runs a read-only copy on the recipient's computer: `docker compose up`, open http://localhost:3000, and the records are there (imported by itself, nothing can be changed, reachable only from that computer). It runs the release that made the package.
### For administrators
- **Admin → Roles**: change what Mechanic, Pilot and Viewer can do (31 permissions, grouped), or add your own roles (a partner, an instructor). Owner always has everything. **Admin → Users → Edit** lists each person's role on every aircraft, to add, change or remove. Only an Owner (or an administrator) can give the Owner role, nobody changes their own, and every aircraft keeps an Owner.
- **Admin → Invitations**: a link that makes an account (or is accepted with one) and gives roles on aircraft; limited uses, an expiry, optionally one email address (and then emailed). With single sign-on, **Continue with** on the invitation makes the account.
- **New accounts come only from an administrator**, an administrator's invitation, or an Owner's signing invitation to an outside mechanic (for that address). Signing invitations from others need an existing account.
- **Who can add aircraft** (Admin → Settings) is **administrators only** by default: adding or importing an aircraft makes you its Owner, who can bring in mechanics. **After this update, other users can't add aircraft** until you choose *Everyone* there.
- `OIDC_AUTO_CREATE_USERS=true` still gives an account to anyone the identity provider lets in, without an invitation; leave it off to keep accounts to administrators and their invitations.
- The REST API follows the person's role; its `owners_only` error is now `not_permitted`.
- The update adds the roles and invitations tables, filled in automatically when the new version starts.
- The compose files and `.env.example` mention the first-run setup code and the push notification, language and image settings.
### Fixes
- Disabled fields look disabled (they looked like any other).
- The records package's viewer said to just create an account (it needs the setup code since 2026.11.5) and named the wrong menu.
## 2026.11.6
### Changes
- **PDFs show on phones.** Android showed nothing for a PDF document and iPhones only its first page. On phones and tablets every page is now drawn in the app, as it scrolls into view, downloading only the parts of the file those pages need (a long manual opens quickly and doesn't use up mobile data). Computers keep the browser's own PDF viewer.
- **Connection status in the top bar.** It turns red when the server can't be reached, and back on its own when it can. A ring fills while pages are saved for offline use or what was logged offline is sent; it's amber with a count while flights or squawks wait to send.
- **A weak signal counts as no signal.** Log Flight and Report Squawk say "Sending…" and, if the server doesn't answer within 10 seconds (a minute with photos), keep the entry on the phone and send it when the connection's back. If it got through after all, it isn't logged twice. Every page falls back to its offline copy or the offline page instead of loading forever.
- **The activity log loads as you scroll** (it stopped at 200 events).
- **What's new** shows the running version's notes on Admin → About; older releases fold to one line each.
- **REST API** for other programs, such as a script that pulls what's coming due or a work-order system: read aircraft, parts, due items, inspections, ADs, squawks and logbook entries; report and update squawks; send draft logbook entries to be signed in the app. Webhooks announce squawks reported, updated and resolved, entries signed, and drafts completed. Personal tokens are made in Profile. The API never signs an entry; see Help → REST API.
### For administrators
- **Admin → Integrations** makes tokens for other systems, acting for the person each request names, limited to the aircraft chosen, plus webhook endpoints.
- The update adds the API's tables; they're created automatically when the new version starts.
## 2026.11.5
### Changes
- **Faster photos.** Aircraft photos load as small copies on the Fleet page and the aircraft header (they were the full original, slow on mobile). The offline copies use the small versions too.
- **Detail cards read one item per row on a phone**: flights, engine data, components and major repairs and alterations. Wider screens show two columns.
- **Profile uses the width of a desktop screen**: your account and its security on the left; calendar, certificates, this device and integrations on the right.
- **Notifications:** opening Profile on a device records its notification subscription again, so a device whose subscription was never saved starts receiving them. **Send test** lists each device and whether its push service accepted the notification, with the reason if not. If turning notifications on fails, the browser's error is shown.
### For administrators
- **The app won't start with a placeholder or short `SECRET_KEY_BASE`** (under 32 characters), since anyone who knows it can sign in as anyone. `sam:doctor` flags one under 64 characters. Use the output of `bin/rails secret`.
- **First-run setup asks for a one-time code** printed in the server log (`docker compose logs web | grep "Setup code"`), so only whoever runs the server can create the admin account.
- **HTTPS without a proxy:** `docker-compose.direct.yml` with `TLS_DOMAIN` gets and renews a Let's Encrypt certificate by itself.
- **The app answers only for its own names** when `APP_HOST` is set: `APP_HOST`, the `APP_URL` host, `localhost`, IP addresses, and any names listed in the new `ALLOWED_HOSTS`. Other names get a short explanation. If you reach the app by another name (such as a LAN name), add it to `ALLOWED_HOSTS`.
- **AirTrail servers on a private network** can be connected only by an administrator, or by anyone when listed in `AIRTRAIL_ALLOWED_HOSTS`. The server itself and link-local addresses are always refused.
- The project is released into the public domain (LICENSE, The Unlicense).
### Fixes
- A file that isn't a photo, or an empty one, chosen as the aircraft photo now shows "must be an image" instead of an error page. An image that can't be read is shown as the original file.
- A component can't be set as a part of its own parts; that made the logbook entry and squawk resolution pages fail.
- Many malformed requests that caused error pages now get a proper answer: pages requested in another format, blank required values, links to records that don't exist, numbers too large to store, and text sent where a file belongs.
## 2026.11.4
### Changes
+24
View File
@@ -0,0 +1,24 @@
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <https://unlicense.org>
+40 -27
View File
@@ -33,7 +33,7 @@ bin/dev # http://localhost:3000
```
With demo data, sign in as `admin@example.com` / `demo-password-123` (admin, owner of N12345) or `pilot@example.com` / `demo-password-123` (pilot).
Without demo data, the first visit asks you to create the admin account.
Without demo data, the first visit asks you to create the admin account. It needs the one-time setup code printed in the server's log (the line starting `Setup code`), so only whoever runs the server can claim it.
Run the tests: `bin/rails test`
@@ -48,11 +48,14 @@ cp .env.example .env # set SECRET_KEY_BASE (bin/rails secret), APP_HOST
docker compose up -d --build # http://<host>:3000
```
Data lives in the `sam_storage` volume. Set `FORCE_SSL=false` if you serve plain HTTP on a LAN. Set it to `true` when a TLS reverse proxy such as Caddy, Traefik, or Cloudflare Tunnel sits in front.
Data lives in the `sam_storage` volume. Set `FORCE_SSL=false` only if you serve plain HTTP on a private network: passwords and sign-in cookies then travel unencrypted. Set it to `true` when a TLS reverse proxy such as Caddy, Traefik, or Cloudflare Tunnel sits in front, or use the built-in HTTPS below.
The first visit asks for the setup code from the log: `docker compose logs web | grep "Setup code"`.
Other examples in the repository:
- [`docker-compose.image.yml`](docker-compose.image.yml): runs the published image (`barrettefab/simple-aircraft-manager-rails` on Docker Hub) without cloning the source, with a health check and update steps.
- [`docker-compose.direct.yml`](docker-compose.direct.yml): directly on the internet with HTTPS and no proxy. The image's web server gets and renews a Let's Encrypt certificate for `TLS_DOMAIN` by itself (ports 80 and 443 must reach the server).
- [`docker-compose.traefik.yml`](docker-compose.traefik.yml): behind Traefik with HTTPS, with optional Authentik forward auth (see [Running behind Authentik](docs/authentik.md)).
[`.env.example`](.env.example) lists every setting, grouped and commented. After starting or updating, `docker compose exec web bin/rails sam:doctor` checks the installation.
@@ -69,9 +72,12 @@ The app is a standard Rails app. Run `bin/rails db:prepare && bin/thrust bin/rai
| Variable | Purpose |
|---|---|
| `SECRET_KEY_BASE` | Required in production (`bin/rails secret`). Alternatively provide `RAILS_MASTER_KEY`. |
| `FORCE_SSL` | `true` (default) redirects to HTTPS and sets secure cookies. Use `false` for plain HTTP. |
| `APP_HOST` | Host name the app is reached at, used in email links (password resets, sign-in links, signing invitations, reminders). |
| `SECRET_KEY_BASE` | Required in production (`bin/rails secret`). Anyone who knows it can sign in as anyone, so the app won't start with a placeholder or one under 32 characters, and `sam:doctor` flags one under 64. Alternatively provide `RAILS_MASTER_KEY`. |
| `FORCE_SSL` | `true` (default) redirects to HTTPS and sets secure cookies. Use `false` for plain HTTP, only on a private network. |
| `TLS_DOMAIN` | Optional. HTTPS without a proxy: the app gets a Let's Encrypt certificate for this name (see `docker-compose.direct.yml`). |
| `APP_HOST` | Host name the app is reached at, used in email links (password resets, sign-in links, signing invitations, reminders). When set, the app answers only for this name, the `APP_URL` host, `ALLOWED_HOSTS`, `localhost` and IP addresses. |
| `ALLOWED_HOSTS` | Optional. Other names the app may be reached by, comma-separated (e.g. a LAN name). |
| `AIRTRAIL_ALLOWED_HOSTS` | Optional. AirTrail servers on your private network that anyone may connect to, comma-separated. Admins can always connect to private addresses; nobody can use the server itself or link-local addresses. |
| `SMTP_ADDRESS`, `SMTP_PORT`, `SMTP_USERNAME`, `SMTP_PASSWORD`, `MAIL_FROM` | Optional. They enable email: password resets and **Email me a sign-in link**. Without them an admin resets passwords from **Users**. Check the setup with **Admin → About → Send test email**. |
| `SMTP_TLS` | `true` for servers that use TLS from the start. That's the default on port 465; other ports upgrade with STARTTLS. |
| `VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY` | Optional. The key pair that signs push notifications (generate with `bin/rails runner 'k = WebPush.generate_key; puts k.public_key, k.private_key'`). Without them the app generates a pair once and keeps it in `storage/vapid_keys.json`. Changing it turns notifications off on every device until they're turned on again. |
@@ -82,12 +88,14 @@ The app is a standard Rails app. Run `bin/rails db:prepare && bin/thrust bin/rai
| `APP_URL` | Optional public base URL, e.g. `https://aircraft.example.com` (default `https://APP_HOST`). Used for the SSO and Google Drive redirect URIs. |
| `OIDC_ISSUER`, `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET` | Optional. Turn on single sign-on with an OpenID Connect provider (see below). |
| `OIDC_PROVIDER_NAME` | Button label, e.g. `Authentik` (default `SSO`). |
| `OIDC_AUTO_CREATE_USERS` | `true` creates an account for anyone the provider lets in. New accounts start with no aircraft. Default off: an admin adds users first. |
| `OIDC_AUTO_CREATE_USERS` | `true` creates an account for anyone the provider lets in, without an invitation. New accounts start with no aircraft. Default off: accounts come only from an admin, an admin's invitation, or an Owner's signing invitation (signing in with SSO from the link makes the account). |
| `OIDC_TRUST_EMAIL` | `true` links existing accounts by email even if the provider doesn't mark it verified. Only use it if users can't edit their own email at the provider. |
| `OIDC_ADMIN_GROUP` | Optional. Members of this provider group become admins and others lose admin, synced at each sign-in. |
| `PWNED_PASSWORDS_CHECK` | `false` turns off the check of new passwords against Have I Been Pwned (only the first 5 characters of the password's SHA-1 are sent). Use it if the server has no outbound internet access; the check also allows the password if the service can't be reached. |
| `PASSWORD_LOGIN` | `false` hides email/password sign-in, emailed sign-in links and password resets once SSO works. It's ignored while SSO isn't configured, so you can't lock yourself out. |
| `APP_REPOSITORY_URL` | Optional. The source code link on Admin → About, for a fork. |
| `APP_IMAGE` | Optional. The image the records package's viewer runs, used as is (for a fork). Default: the published image at the release that made the package. |
| `SAM_VIEWER`, `SAM_VIEWER_ARCHIVE` | **Only for the records package's viewer** (its `viewer/docker-compose.yml` sets them). `SAM_VIEWER=true` makes the app a read-only copy with no sign-in: it imports the `.sam.zip` at `SAM_VIEWER_ARCHIVE` at start, everyone browses as a built-in account, and nothing can be changed. It refuses to start on a database with any user account, so turning it on for a real installation stops the app instead of exposing its records. |
| `APP_REVISION`, `APP_BUILT_AT` | Set as Docker build arguments (see the `Dockerfile`) so Admin → About shows the version and the records keep a software version history. |
### Single sign-on (Authentik example)
@@ -132,9 +140,9 @@ To back up or move a single aircraft with all its files, use **More → Download
| Fleet dashboard | Every aircraft you can access, with airworthiness status and its top issues. |
| Airworthiness | Grounded / limited (e.g. "VFR only" for an overdue 91.411 check) / due soon / current, from AD compliance, grounding squawks, inspections, replacement-critical and expiring parts, and expiring documents (an expired registration grounds). Warnings start 10 hours or 30 days ahead. The pilot in command still decides airworthiness (91.7). Logic: `app/services/airworthiness.rb`, `app/services/compliance.rb`. |
| Hours | Absolute tach/hobbs updates or per-flight logs. Both apply the delta to every in-service component. Downward corrections are clamped at 0. Each aircraft picks tach or Hobbs as its maintenance clock (time in service). |
| Flight import | Owners can import historical flights from `.xlsx` or `.csv` (Date, From, To, Tach, Hobbs, Oil Added, Fuel Added). Each flight's time is derived from the previous row's reading. A preview flags typos such as a tach going backwards, and rows already imported are skipped. History only: component hours aren't changed unless you choose to advance the aircraft's meters. |
| Flight import | Import historical flights from `.xlsx` or `.csv` (Date, From, To, Tach, Hobbs, Oil Added, Fuel Added). Each flight's time is derived from the previous row's reading. A preview flags typos such as a tach going backwards, and rows already imported are skipped. History only: component hours aren't changed unless you choose to advance the aircraft's meters. |
| Airworthiness enforcement | Optional per aircraft. It blocks flight logs and hours updates while the aircraft is grounded (not for limitations). |
| Components | Tree of parent and child parts, TBO and replacement limits, and service/replace reset. Owners can create new component types inline. |
| Components | Tree of parent and child parts, TBO and replacement limits, and service/replace reset. New component types can be created inline. |
| Squawks | Four priorities. "Ground Aircraft" grounds the aircraft. Inoperative items can be deferred under 91.213(d) after confirming each condition; resolving can record the fix as a logbook entry. Attachments, reopen. |
| Notes | Per-aircraft notes in Markdown, with a preview; shown on share links. |
| ADs and bulletins | Shared across aircraft and applicable to the airframe or to specific components. Hour- and month-based recurrence (due at end of month), conditional and non-mandatory types, per-aircraft "not applicable" determinations, and compliance history with method of compliance and the revision complied with. |
@@ -142,35 +150,40 @@ To back up or move a single aircraft with all its files, use **More → Download
| AD import | Import ADs from an FAA DRS export (`.xlsx` recommended: its AD numbers link to each AD's DRS page, which the import keeps; `.csv` works without links). ADs are matched by number, so nothing is duplicated. The preview suggests Track, Not applicable or Skip for each AD, and flags superseded or non-current ADs, model mismatches, appliance or STC-only ADs, and repetitive actions. |
| Inspections | Shared inspection types with hour, month, and day recurrence, plus history. Each says what overdue means (grounded, no IFR, no transponder, advisory); an annual can also count as the 100-hour, and the 100-hour's 10-hour overrun is credited (91.409(b)). One click adds the standard Part 91 set. |
| Logbook | Maintenance entries with search and a link to a scanned document page. Records the signer's certificate kind and number and an inspection's result, and flags what 43.9 / 43.11 needs that's missing. Entries transcribed by Claude stay "unverified" until someone checks them against the scan. Entry templates (built-in pilot preventive maintenance per 43.3(g) and Part 43 Appendix A(c); admins add and edit their own under Admin → Logbook templates). Engine and propeller entries link the component and record its total time and time since overhaul (SMOH/SFOH/SNEW) at the entry, worked out from the entry's airframe total time; sub-components (an oil filter on the engine…) can be included with their own times. Print entries as a PDF on Avery 5163/8163 or 5164/8164 labels or half-letter/letter pages (boxed) to sign and put in the paper logbook. |
| Documents | Collections, multi-file documents with a page viewer, per-document share visibility, bulk upload, and expiration dates (registration, insurance…). Their text is read for search: PDF text layers directly, scans by Tesseract OCR (in the image) or optionally Claude. |
| Documents | Collections, multi-file documents with a page viewer (PDFs drawn page by page with PDF.js on phones, fetching only the pages viewed), per-document share visibility, bulk upload, and expiration dates (registration, insurance…). Their text is read for search: PDF text layers directly, scans by Tesseract OCR (in the image) or optionally Claude. |
| Electronic signatures | Logbook entries can be signed electronically along the lines of AC 120-78B chapter 2: the signer reviews the entry, picks their certificate, re-enters their password (or signs in again with SSO) and confirms a "Certified by" statement. The signature records who, which certificate, the statement, the time and a SHA-256 fingerprint of the entry, sealed by the server; the signer gets an email. Signed entries are locked: a correction is a new signed entry that supersedes the original. Owners can invite an outside mechanic to sign one entry with their own account. Disabled accounts can't sign; their past signatures stay. |
| Records integrity | Every change to maintenance records is kept (who, when, field by field) in a hash chain per aircraft (Activity → Record history). Nightly: a verified SQLite backup in `storage/backups` (how many are kept: Admin → Settings), then a check of the history chains and every signature; admins are emailed on a problem (Admin → About). Software versions are recorded. A records package (Access & Sharing) bundles every entry as a PDF with signatures, a signature register, the history, the status report and the `.sam.zip` for the FAA or a buyer, with a README (and a ready-to-run `viewer/docker-compose.yml`) so the recipient can browse the data in their own local copy of the app. Scans of paper logbooks can be marked as legacy records, with an "electronic records since" date per aircraft. |
| Records integrity | Every change to maintenance records is kept (who, when, field by field) in a hash chain per aircraft (Activity → Record history). Nightly: a verified SQLite backup in `storage/backups` (how many are kept: Admin → Settings), then a check of the history chains and every signature; admins are emailed on a problem (Admin → About). Software versions are recorded. A records package (Access & Sharing) bundles every entry as a PDF with signatures, a signature register, the history, the status report and the `.sam.zip` for the FAA or a buyer, with a README and a ready-to-run `viewer/docker-compose.yml`: `docker compose up` gives the recipient a read-only copy of the app on their own computer, with the archive imported and no sign-in (`SAM_VIEWER`). Scans of paper logbooks can be marked as legacy records, with an "electronic records since" date per aircraft. |
| Off-site backup | Nightly copy of the verified database snapshot (newest 30 kept) and every new uploaded file to Google Drive, using your own Google OAuth client and the `drive.file` scope (the app sees only its own files). Restore test from the admin page; failures emailed to admins; `bin/rails offsite:restore_files` brings files back after a restore. |
| Recordkeeping procedures and audits | Admin → Recordkeeping Procedures generates the procedures document AC 120-78B asks for (who is responsible, who may sign, signing, corrections, backups, access, audits, transfer, legacy records) from the system setup plus a few details you fill in (with suggested text built from the installation's settings; a revision can't be adopted while a [bracketed] blank is left); adopt it as numbered, unchangeable revisions, included in the records package. Admin → Records Audits is a periodic QC checklist (app checks plus a restore test, a sample of entries against source documents and a user review); admins get the due date in the weekly reminder. The users' instructions are the guide's [Electronic records and signing](docs/guide/records.md) page. |
| Major repairs and alterations | Form 337, STC, and ICA tracking; an STC's ICA can become a tracked recurring inspection. |
| Weight & balance | History of empty weight and CG (linked to the alteration that changed them) and a loading calculator: takeoff and landing weight and CG against max gross and the CG envelope. The envelope can be entered as CG (inches) or as moment (lb-in/1000, as in POH moment charts and Garmin Pilot). |
| Status report | A printable maintenance status (91.417(a)(2)): total times, life-limited parts, time since overhaul, inspections, ADs with method and revision, major alterations, open discrepancies. Also on maintenance share links. |
| Calendar feed | A private iCalendar link (Profile) with everything coming due on your aircraft as all-day events; hour-based items get a date projected from the past year's flying. |
| Reminders | A Monday email to owners when something is overdue or coming due, and to anyone whose certificate (e.g. an IA) is about to expire; admins also get the records audit due date (needs SMTP; users can turn it off). |
| Reminders | A Monday email to those whose role gets reminders (Owners and Mechanics by default) when something is overdue or coming due, plus push alerts when something becomes overdue, and to anyone whose certificate (e.g. an IA) is about to expire; admins also get the records audit due date (needs SMTP; users can turn it off). |
| Oil and fuel | Records, trend charts, and averages (last 20 intervals, IQR outlier filtering, manual exclusion). |
| Activity log | Every write is recorded as an `AircraftEvent`. |
| Access | Admin, owner, and pilot roles, plus share links (Current Status or Maintenance Detail, optional expiry, at most 10 per aircraft). Admins can disable accounts; a disabled account can't sign in or sign entries, and its past signatures stay. |
| Activity log | Every write is recorded as an `AircraftEvent`; the Activity tab loads them as you scroll. |
| Access | Configurable roles per aircraft (see [Roles](#roles)), admins' invitation links (limited uses, expiry, optionally one email address) that give an account and roles, plus share links (Current Status or Maintenance Detail, optional expiry, at most 10 per aircraft). Admins can disable accounts; a disabled account can't sign in or sign entries, and its past signatures stay. |
| Sign-in security | Passwords of at least 12 characters, checked against known breaches (Have I Been Pwned, k-anonymity). 10 failed sign-ins in a row lock an account for 15 minutes from any address, and the user is emailed; admins can unlock. Optional authenticator-app (TOTP) codes with recovery codes for password and emailed-link sign-in and for signing entries; admins can reset them. Rate limits per address on every sign-in form. |
| Phones and offline | Installable (PWA). Flights and squawks logged without signal, or with one too weak to answer within 10 seconds, are kept on the device and sent later, never twice. The Fleet, Overview, W&B, Log Flight and Report Squawk pages are saved ahead of time; any other page falls back to an offline page. The top bar turns red when the server can't be reached, and a ring shows saving and sending progress. |
| REST API | Personal and integration tokens with scopes, read endpoints, squawks, draft logbook entries for signing in the app, and signed webhooks ([docs](docs/guide/api.md)). Follows the person's role. |
| Help | The [user guide](docs/guide/README.md), shown in the app under **Help**. |
### Roles
| Action | Admin | Owner | Pilot |
|---|:-:|:-:|:-:|
| View everything on the aircraft | ✓ | ✓ | ✓ |
| Update hours, log flights, add squawks/notes/oil/fuel | ✓ | ✓ | ✓ |
| Defer squawks (91.213(d)) | ✓ | ✓ | ✓ |
| Sign logbook entries with their own certificate | ✓ | ✓ | ✓ |
| Edit or delete squawks and notes, resolve squawks | ✓ | ✓ | |
| Components, logbook, ADs, inspections, documents, major records | ✓ | ✓ | |
| Edit or delete aircraft, manage people and share links | ✓ | ✓ | |
| Create aircraft (creator becomes owner) | ✓ | ✓ | ✓ |
| Users, component types, airports, templates, settings, off-site backup, procedures and audits | ✓ | | |
Each person has a role on each aircraft, and a role is a set of permissions (`app/models/permission.rb`) that administrators change under **Admin → Roles**, where they can also add their own. The built-in roles as they come:
| Action | Viewer | Pilot | Mechanic | Owner |
|---|:-:|:-:|:-:|:-:|
| View everything on the aircraft | ✓ | ✓ | ✓ | ✓ |
| Log flights, correct own flights | | ✓ | | ✓ |
| Update hours, report and defer squawks (91.213(d)), add notes/oil/fuel | | ✓ | ✓ | ✓ |
| Sign logbook entries with their own certificate | | ✓ | ✓ | ✓ |
| Logbook, components, ADs, inspections, documents, major records, W&B; edit squawks, notes, oil/fuel | | | ✓ | ✓ |
| Reminders and overdue alerts | | | ✓ | ✓ |
| Correct or delete any flight, imports, exports, restore from history | | | | ✓ |
| Edit or delete the aircraft, manage people and share links | | | | ✓ |
Owner always has every permission. Only an Owner can give the Owner role, nobody changes their own, and every aircraft keeps an Owner. Administrators can do everything on every aircraft and manage users, roles, component types, airports, templates, settings, off-site backup, procedures and audits. Whoever adds an aircraft becomes its Owner (who can add aircraft is an admin setting: administrators only by default). Controllers declare the permission each action needs (`requires_permission`); a write with none declared is refused.
Users who aren't on an aircraft get a 404 for it, identical to a missing record.
@@ -191,15 +204,15 @@ Users who aren't on an aircraft get a 404 for it, identical to a missing record.
Differences from the original:
- Integer primary keys instead of UUIDs. Share tokens are 32-character random strings.
- Logbook entries and inspection records don't keep many-to-many links to components. An inspection record or AD compliance can reference one component.
- Accounts are created by an admin, by the first-run setup, at first SSO sign-in (if `OIDC_AUTO_CREATE_USERS` is on), or by an outside mechanic accepting a signing invitation. The original's invitation codes aren't implemented yet.
- Accounts are created only by an admin, by the first-run setup, by someone opening an admin's invitation link (with a password, or SSO), by an outside mechanic from an Owner's signing invitation (for its address), or at first SSO sign-in when `OIDC_AUTO_CREATE_USERS` is on. Who can add aircraft, and so become an Owner, is an admin setting (administrators only by default).
### Not yet ported
The MCP server for AI agents, invitation codes, per-aircraft feature switches, the plugin system, and the desktop builds.
The MCP server for AI agents, Prometheus metrics, per-aircraft feature switches (only airworthiness enforcement is here, as an aircraft setting), the plugin system, and the desktop builds.
### Added in this port
AirTrail sync and export, an airport database, FAA DRS AD import, spreadsheet flight import, engine monitor data (CGR-30P/C) with interactive charts, AvLab and Blackstone oil analysis import with trends, multiple squawk attachments with a photo viewer, AI logbook transcription with Claude (images and PDFs), printable logbook entries, electronic signatures and recordkeeping along the lines of AC 120-78B (record history, nightly integrity checks, records package, procedures and audits), off-site backup to Google Drive, a user guide, and an installable app (PWA) that logs flights and squawks offline, keeps pre-flight pages for use without signal, and sends push notifications.
AirTrail sync and export, an airport database, FAA DRS AD import, spreadsheet flight import, engine monitor data (CGR-30P/C) with interactive charts, multiple squawk attachments with a photo viewer, AI logbook transcription with Claude (images and PDFs), printable logbook entries, electronic signatures and recordkeeping along the lines of AC 120-78B (record history, nightly integrity checks, records package, procedures and audits), off-site backup to Google Drive, a user guide, and an installable app (PWA) that logs flights and squawks offline, keeps pre-flight pages for use without signal, and sends push notifications.
## Translating
+1 -1
View File
@@ -1 +1 @@
2026.11.4
2026.11.7
+38 -1
View File
@@ -5,6 +5,7 @@
--color-page: oklch(96.8% 0.007 247.896); /* slate-100 */
--color-surface: oklch(100% 0 0); /* white: cards, inputs, menus */
--color-header: oklch(20.8% 0.042 265.755); /* slate-900: top bar, dark in both themes */
--color-header-offline: oklch(50.5% 0.213 27.518); /* red-700: top bar when the server can't be reached */
--color-accent: oklch(50% 0.134 242.749); /* sky-700: primary buttons */
--color-accent-hover: oklch(44.3% 0.11 240.79); /* sky-800 */
}
@@ -25,7 +26,7 @@
@utility card-body { @apply p-4; }
@utility label { @apply block text-sm font-medium text-slate-700 mb-1; }
@utility input { @apply block w-full rounded-md border-0 px-2.5 py-1.5 text-sm text-slate-900 shadow-sm ring-1 ring-slate-300 ring-inset placeholder:text-slate-400 focus:ring-2 focus:ring-sky-600 focus:outline-none bg-surface; }
@utility input { @apply block w-full rounded-md border-0 px-2.5 py-1.5 text-sm text-slate-900 shadow-sm ring-1 ring-slate-300 ring-inset placeholder:text-slate-400 focus:ring-2 focus:ring-sky-600 focus:outline-none bg-surface disabled:cursor-not-allowed disabled:bg-slate-100 disabled:text-slate-500 disabled:shadow-none disabled:ring-slate-200; }
@utility hint { @apply mt-1 text-xs text-slate-500; }
@utility field-error { @apply mt-1 text-xs text-red-600; }
@@ -62,6 +63,7 @@
--color-page: oklch(15.5% 0.035 264);
--color-surface: oklch(20.8% 0.042 265.755);
--color-header: oklch(12.9% 0.042 264.695);
--color-header-offline: oklch(44.4% 0.177 26.899); /* red-800 */
--color-accent: oklch(50% 0.134 242.749); /* same blue: white text stays ≥ 4.5:1 */
--color-accent-hover: oklch(54% 0.15 242);
@@ -184,3 +186,38 @@
.btn-sm { padding: 0.4rem 0.75rem; font-size: 0.8125rem; }
.btn-primary, .btn-secondary, .btn-danger { min-height: 2.5rem; }
}
/* A label and its value on one row (label column, then value), e.g. a flight's details. */
@utility detail-row {
@apply grid grid-cols-[6.5rem_minmax(0,1fr)] items-baseline gap-x-3;
& > dt { @apply text-slate-500; }
}
/* The top bar's connection status (connection_controller.js, after
SilverBullet): red when the server can't be reached, and a ring that fills
with the percentage in its hole while saving for offline or sending. Amber
and full while flights or squawks wait to send, with how many. */
header.is-offline { --color-header: var(--color-header-offline); }
.sync-ring {
position: relative;
display: inline-block;
flex: none;
width: 24px;
height: 24px;
border-radius: 9999px;
background: conic-gradient(var(--ring-color, white) var(--progress, 0%), rgb(255 255 255 / 0.25) 0);
}
.sync-ring[hidden] { display: none; }
.sync-ring.is-waiting { --ring-color: oklch(87.9% 0.169 91.605); } /* amber-300 */
.sync-ring > span {
position: absolute;
inset: 2.5px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 9999px;
background-color: var(--color-header);
font-size: 9px;
font-variant-numeric: tabular-nums;
line-height: 1;
}
+1 -1
View File
@@ -2,7 +2,7 @@
# search terms used.
class AdAlertsController < ApplicationController
include AircraftScoped
before_action :require_owner!
requires_permission :manage_ads
before_action :set_alert, only: %i[track dismiss]
rate_limit to: 5, within: 1.minute, only: :check, with: -> { redirect_to aircraft_airworthiness_directives_path(@aircraft), alert: t("flash.ad_alerts.try_again_in_a") }
+1 -1
View File
@@ -1,6 +1,6 @@
class AdCompliancesController < ApplicationController
include AircraftScoped
before_action :require_owner!
requires_permission :manage_ads
before_action :set_compliance, only: %i[edit update destroy]
def new
+1 -1
View File
@@ -2,7 +2,7 @@
class AdImportsController < ApplicationController
include AircraftScoped
include StoredUpload
before_action :require_owner!
requires_permission :manage_ads
def new; end
@@ -0,0 +1,93 @@
# Admin → Integrations: tokens for other systems (e.g. Redmine), limited to
# chosen aircraft and scopes, each with an optional webhook (docs/api.md).
# The token and webhook secret are shown once, right after they're made.
class Admin::IntegrationsController < ApplicationController
before_action :require_admin!
before_action :set_integration, only: %i[show edit update destroy new_secret]
def index
@integrations = ApiToken.integration.order(revoked_at: :desc, name: :asc).includes(:webhook_endpoints)
end
def new
@integration = ApiToken.new(kind: "integration", scopes: %w[read])
@endpoint = WebhookEndpoint.new(events: [])
end
def create
@integration = ApiToken.new(integration_params.merge(kind: "integration", user: current_user))
@endpoint = build_endpoint(@integration)
ApiToken.transaction do
@integration.save!
@endpoint&.save!
end
@secret = @endpoint&.secret
render :created
rescue ActiveRecord::RecordInvalid
@endpoint ||= WebhookEndpoint.new(events: [])
render :new, status: :unprocessable_entity
end
def show
@endpoint = @integration.webhook_endpoints.first
@deliveries = @endpoint ? @endpoint.deliveries.recent.limit(25) : []
end
def edit
@endpoint = @integration.webhook_endpoints.first || WebhookEndpoint.new(events: [])
end
def update
@endpoint = @integration.webhook_endpoints.first
ApiToken.transaction do
@integration.update!(integration_params)
if webhook_params[:url].present?
@endpoint ||= @integration.webhook_endpoints.new(secret: WebhookEndpoint.new_secret)
@endpoint.update!(webhook_params)
else
@endpoint&.destroy!
end
end
redirect_to admin_integration_path(@integration), notice: t("flash.admin_integrations.saved")
rescue ActiveRecord::RecordInvalid
@endpoint ||= WebhookEndpoint.new(events: [])
render :edit, status: :unprocessable_entity
end
# A new webhook secret, shown once.
def new_secret
@endpoint = @integration.webhook_endpoints.first or return redirect_to(admin_integration_path(@integration))
@endpoint.update!(secret: WebhookEndpoint.new_secret)
@secret = @endpoint.secret
render :created
end
def destroy
@integration.revoke!
@integration.webhook_endpoints.update_all(enabled: false)
redirect_to admin_integrations_path, notice: t("flash.admin_integrations.revoked", name: @integration.name)
end
private
def set_integration = @integration = ApiToken.integration.find(params[:id])
def integration_params
p = params.require(:api_token).permit(:name, scopes: [], aircraft_ids: [])
p[:scopes] = Array(p[:scopes]) & ApiToken::SCOPES.keys
p[:aircraft_ids] = Aircraft.where(id: Array(p[:aircraft_ids])).ids
p
end
def webhook_params
p = params.fetch(:webhook, {}).permit(:url, :enabled, events: [])
p[:events] = Array(p[:events]) & WebhookEndpoint::EVENTS.keys
p[:enabled] = p[:enabled] != "0"
p
end
def build_endpoint(integration)
return if webhook_params[:url].blank?
integration.webhook_endpoints.new(webhook_params.merge(secret: WebhookEndpoint.new_secret))
end
end
@@ -0,0 +1,32 @@
# Invitation codes for any aircraft, or none (an account only), by
# administrators (AccessInvitation).
class Admin::InvitationsController < ApplicationController
before_action :require_admin!
def index
@invitations = AccessInvitation.recent_first.includes(:created_by, grants: %i[aircraft role]).limit(200)
end
def new
@invitation = AccessInvitation.new(max_uses: 1, expires_at: AccessInvitation::VALID_FOR.from_now.change(sec: 0))
end
def create
roles = Role.all.index_by(&:id)
grants = Aircraft.where(id: params.fetch(:roles, {}).keys).filter_map do |aircraft|
role = roles[params[:roles][aircraft.id.to_s].to_i]
[ aircraft, role ] if role
end
@invitation = AccessInvitation.create_for(current_user, params.require(:access_invitation).permit(:label, :email, :name, :max_uses, :expires_at), grants)
if @invitation.persisted?
render :created
else
render :new, status: :unprocessable_entity
end
end
def destroy
AccessInvitation.find(params[:id]).update!(revoked_at: Time.current)
redirect_to admin_invitations_path, notice: t("flash.admin_invitations.revoked")
end
end
+57
View File
@@ -0,0 +1,57 @@
# The roles people can have on an aircraft and what each allows (Role,
# Permission). Owner always has every permission; the other built-in roles
# can be changed but not deleted; administrators can add their own.
class Admin::RolesController < ApplicationController
before_action :require_admin!
before_action :set_role, only: %i[edit update destroy]
def index
Role.ensure_built_in!
@roles = Role.ordered
@counts = AircraftRole.group(:role_id).count
end
def new
@role = Role.new(permissions: Permission::DEFAULTS["viewer"])
end
def create
@role = Role.new(role_params)
if @role.save
redirect_to admin_roles_path, notice: t("flash.admin_roles.created", name: @role.name)
else
render :new, status: :unprocessable_entity
end
end
def edit; end
def update
attributes = @role.owner? ? role_params.except(:permissions) : role_params
if @role.update(attributes)
redirect_to admin_roles_path, notice: t("flash.admin_roles.updated", name: @role.name)
else
render :edit, status: :unprocessable_entity
end
end
def destroy
if @role.built_in?
redirect_to admin_roles_path, alert: t("flash.admin_roles.built_in")
elsif @role.aircraft_roles.exists?
redirect_to admin_roles_path, alert: t("flash.admin_roles.in_use", name: @role.name, count: @role.aircraft_roles.count)
else
@role.destroy!
redirect_to admin_roles_path, notice: t("flash.admin_roles.deleted", name: @role.name)
end
end
private
def set_role = @role = Role.find(params[:id])
# Unticking every box sends none, so an empty list is always sent too.
def role_params
params.require(:role).permit(:name, :description, permissions: []).tap { _1[:permissions] = Array(_1[:permissions]).compact_blank }
end
end
+3 -3
View File
@@ -2,18 +2,18 @@ class Admin::SettingsController < ApplicationController
before_action :require_admin!
def edit
@values = %w[max_upload_mb backups_kept offsite_backups_kept documents_claude_text].index_with { Setting.integer(_1) }
@values = %w[max_upload_mb backups_kept offsite_backups_kept documents_claude_text anyone_adds_aircraft].index_with { Setting.integer(_1) }
end
def update
submitted = params.fetch(:settings, {}).permit(:max_upload_mb, :backups_kept, :offsite_backups_kept, :documents_claude_text).to_h
submitted = params.fetch(:settings, {}).permit(:max_upload_mb, :backups_kept, :offsite_backups_kept, :documents_claude_text, :anyone_adds_aircraft).to_h
records = Setting.update_integers(submitted)
@errors = records.flat_map { _1.errors.full_messages }
if @errors.empty?
Rails.logger.info("[settings] #{current_user.email_address} changed #{submitted.inspect}")
redirect_to edit_admin_settings_path, notice: t("flash.admin_settings.settings_saved")
else
@values = %w[max_upload_mb backups_kept offsite_backups_kept documents_claude_text].index_with { Setting.integer(_1) }.merge(submitted)
@values = %w[max_upload_mb backups_kept offsite_backups_kept documents_claude_text anyone_adds_aircraft].index_with { Setting.integer(_1) }.merge(submitted)
render :edit, status: :unprocessable_entity
end
end
@@ -0,0 +1,31 @@
# Administrators give people roles on any aircraft (from Admin → Users),
# under the same rules as the aircraft's Access page (AircraftAccess).
class Admin::UserAircraftRolesController < ApplicationController
before_action :require_admin!
before_action :set_user
def create
aircraft = Aircraft.find_by(id: params[:aircraft_id])
return back(alert: t("services.aircraft_access.not_found")) unless aircraft
back_with AircraftAccess.new(aircraft, actor: current_user).add(@user, Role.find_by(id: params[:role_id])),
t("flash.admin_users.access_added", tail_number: aircraft.tail_number)
end
def update
membership = @user.aircraft_roles.find(params[:id])
back_with AircraftAccess.new(membership.aircraft, actor: current_user).change(membership, Role.find_by(id: params[:role_id])),
t("flash.admin_users.access_changed", tail_number: membership.aircraft.tail_number)
end
def destroy
membership = @user.aircraft_roles.find(params[:id])
back_with AircraftAccess.new(membership.aircraft, actor: current_user).remove(membership),
t("flash.admin_users.access_removed", tail_number: membership.aircraft.tail_number)
end
private
def set_user = @user = User.find(params[:user_id])
def back(flash) = redirect_to(edit_admin_user_path(@user, anchor: "access"), flash)
def back_with(error, notice) = back(error ? { alert: error } : { notice: notice })
end
+1 -1
View File
@@ -3,7 +3,7 @@ class Admin::UsersController < ApplicationController
before_action :set_user, only: %i[edit update destroy disable enable unlock reset_two_factor]
def index
@users = User.order(:email_address).includes(:certificates, aircraft_roles: :aircraft)
@users = User.order(:email_address).includes(:certificates, aircraft_roles: %i[aircraft role])
end
def new
@@ -1,6 +1,7 @@
# Download the aircraft's flights as an AirTrail import file.
class AirTrailExportsController < ApplicationController
include AircraftScoped
requires_permission :log_flights
def new
@export = build_export
+5 -2
View File
@@ -1,7 +1,10 @@
class AircraftController < ApplicationController
include AircraftScoped
skip_before_action :set_aircraft, only: %i[index new create]
before_action :require_owner!, only: %i[edit update destroy]
skip_before_action :set_aircraft, :authorize_permission!, only: %i[index new create]
before_action :require_aircraft_adder!, only: %i[new create]
requires_permission :edit_aircraft, only: %i[edit update]
requires_permission :delete_aircraft, only: :destroy
requires_permission :update_hours, only: :update_hours
def index
@aircraft_list = current_user.accessible_aircraft.ordered.with_attached_picture
@@ -1,7 +1,7 @@
# Download an aircraft as a .sam.zip archive (owners and admins).
class AircraftExportsController < ApplicationController
include AircraftScoped
before_action :require_owner!
requires_permission :export_data
EXPORT_DIR = Rails.root.join("tmp/exports")
@@ -2,13 +2,14 @@
# create an aircraft with all its records. The archive is checked right away;
# the import itself runs in the background (AircraftImportJob).
class AircraftImportsController < ApplicationController
before_action :require_aircraft_adder!, only: %i[new create]
before_action :set_import, only: :show
def new; end
def create
file = params[:archive]
return redirect_to(new_aircraft_import_path, alert: t("flash.aircraft_imports.choose_a_sam_zip")) if file.blank?
return redirect_to(new_aircraft_import_path, alert: t("flash.aircraft_imports.choose_a_sam_zip")) unless file.respond_to?(:tempfile)
preview = AircraftArchive::Importer.check(file.tempfile.path)
tail = params[:tail_number].to_s.strip.upcase.presence || preview.tail_number.to_s.upcase
+17 -34
View File
@@ -1,54 +1,37 @@
# Owner-only: manage who can access the aircraft, and its public share links.
# Who can access the aircraft, with which role ("manage people"), and its
# public share links ("manage sharing", see ShareTokensController). The rules
# for changing roles are in AircraftAccess.
class AircraftRolesController < ApplicationController
include AircraftScoped
before_action :require_owner!
checks_permission_itself only: :index
requires_permission :manage_people, only: %i[create update destroy]
def index
@roles = @aircraft.roles.includes(:user).order(:role, :created_at)
return permission_denied unless can?(:manage_people) || can?(:manage_sharing) || can?(:export_data)
@access = AircraftAccess.new(@aircraft, actor: current_user)
@roles = @aircraft.roles.includes(:user, :role).joins(:role).order("roles.position", :created_at)
@share_tokens = @aircraft.share_tokens.order(created_at: :desc).includes(:created_by)
end
def create
user = User.find_by(email_address: params[:email_address].to_s.strip.downcase)
unless user
return redirect_to aircraft_aircraft_roles_path(@aircraft),
alert: t("flash.aircraft_roles.no_user_with_that")
end
role = @aircraft.roles.new(user: user, role: params[:role])
if role.save
log_event("role", t("flash.aircraft_roles.added_as", display_name: user.display_name, role: role.role))
redirect_to aircraft_aircraft_roles_path(@aircraft), notice: t("flash.aircraft_roles.added", display_name: user.display_name)
else
redirect_to aircraft_aircraft_roles_path(@aircraft), alert: role.errors.full_messages.to_sentence
end
return back(alert: t("flash.aircraft_roles.no_user_with_that")) unless user
error = access.add(user, Role.find_by(id: params[:role_id]))
back(error ? { alert: error } : { notice: t("flash.aircraft_roles.added", display_name: user.display_name) })
end
def update
role = @aircraft.roles.find(params[:id])
if demoting_last_owner?(role, params[:role])
return redirect_to aircraft_aircraft_roles_path(@aircraft), alert: t("flash.aircraft_roles.an_aircraft_must_keep")
end
role.update!(role: params[:role])
log_event("role", t("flash.aircraft_roles.changed_to", display_name: role.user.display_name, role: role.role))
redirect_to aircraft_aircraft_roles_path(@aircraft), notice: t("flash.aircraft_roles.role_updated")
error = access.change(@aircraft.roles.find(params[:id]), Role.find_by(id: params[:role_id]))
back(error ? { alert: error } : { notice: t("flash.aircraft_roles.role_updated") })
end
def destroy
role = @aircraft.roles.find(params[:id])
if role.user == current_user
return redirect_to aircraft_aircraft_roles_path(@aircraft), alert: t("flash.aircraft_roles.you_can_t_remove")
end
if demoting_last_owner?(role, nil)
return redirect_to aircraft_aircraft_roles_path(@aircraft), alert: t("flash.aircraft_roles.an_aircraft_must_keep_2")
end
role.destroy!
log_event("role", t("flash.aircraft_roles.removed", display_name: role.user.display_name))
redirect_to aircraft_aircraft_roles_path(@aircraft), notice: t("flash.aircraft_roles.access_removed")
error = access.remove(@aircraft.roles.find(params[:id]))
back(error ? { alert: error } : { notice: t("flash.aircraft_roles.access_removed") })
end
private
def demoting_last_owner?(role, new_role)
role.role == "owner" && new_role != "owner" && @aircraft.roles.owners.count <= 1
end
def access = AircraftAccess.new(@aircraft, actor: current_user)
def back(flash) = redirect_to(aircraft_aircraft_roles_path(@aircraft), flash)
end
+1 -1
View File
@@ -1,7 +1,7 @@
# Flights → Standardize airport codes (owners).
class AirportCodesController < ApplicationController
include AircraftScoped
before_action :require_owner!
requires_permission :edit_any_flight
def show
@standardizer = AirportCodeStandardizer.new(@aircraft)
@@ -1,14 +1,14 @@
class AirworthinessDirectivesController < ApplicationController
include AircraftScoped
include Applicability
before_action :require_owner!, except: :index
requires_permission :manage_ads, except: :index
before_action :set_ad, only: %i[edit update destroy]
def index
@rows = Compliance.ad_rows(@aircraft)
@history = AdCompliance.for_aircraft(@aircraft).recent_first
.includes(:component, :logbook_entry, airworthiness_directive: :document, inspection_record: :inspection_type)
@attachable = AirworthinessDirective.where.not(id: @aircraft.applicable_ads.select(:id)).ordered if owner?
@attachable = AirworthinessDirective.where.not(id: @aircraft.applicable_ads.select(:id)).ordered if can?(:manage_ads)
@alerts = @aircraft.ad_alerts.pending
end
@@ -0,0 +1,49 @@
module Api
module V1
# The fleet this token reaches, and each aircraft's own lists.
class AircraftController < BaseController
before_action -> { require_scope!(:read) }
def index
render_page(aircraft_scope) { ApiPresenter.aircraft(_1) }
end
def show
render json: { data: ApiPresenter.aircraft(find_aircraft(params[:id])) }
end
# The parts tree (?all=1 includes disposed parts).
def components
aircraft = find_aircraft(params[:id])
scope = aircraft.components.includes(:component_type)
scope = scope.where.not(status: "DISPOSED") unless params[:all].present?
render_page(scope) { ApiPresenter.component(_1) }
end
# Everything coming due, soonest first (hours projected to dates).
def due
aircraft = find_aircraft(params[:id])
render json: { data: DueList.new(aircraft).items.map { ApiPresenter.due_item(_1) } }
end
def inspections
aircraft = find_aircraft(params[:id])
render json: { data: Compliance.inspection_rows(aircraft).map { ApiPresenter.inspection(_1) } }
end
def ads
aircraft = find_aircraft(params[:id])
render json: { data: Compliance.ad_rows(aircraft).map { ApiPresenter.ad(_1) } }
end
# Logbook entries, oldest first (paged); ?log=AC|ENG|PROP|OTHER, ?signed=true|false.
def logbook_entries
aircraft = find_aircraft(params[:id])
scope = aircraft.logbook_entries.includes(:signature)
scope = scope.where(log_type: params[:log]) if params[:log].present?
scope = params[:signed] == "true" ? scope.where.associated(:signature) : scope.where.missing(:signature) if params[:signed].present?
render_page(scope) { ApiPresenter.logbook_entry(_1) }
end
end
end
end
+127
View File
@@ -0,0 +1,127 @@
# The REST API, version 1 (docs/api.md). JSON in and out; a token in
# "Authorization: Bearer sam_…" instead of a browser session, so no cookies
# and no CSRF tokens.
#
# A personal token acts as its owner. An integration token acts for the
# person named in "SAM-On-Behalf-Of: <email>" (required for writes), and
# reaches only its aircraft that person can also see.
module Api
module V1
class BaseController < ActionController::API
include RejectsNullBytes
MAX_PAGE = 200
before_action :authenticate
rate_limit to: 600, within: 1.minute, by: -> { @api_token&.id || request.remote_ip },
with: -> { render_error(:too_many_requests, "rate_limited", "Too many requests; slow down.") }
around_action :idempotent, if: -> { request.post? || request.patch? || request.delete? }
rescue_from ActiveRecord::RecordNotFound do
render_error(:not_found, "not_found", "Not found, or not available to this token.")
end
rescue_from ActionController::ParameterMissing, ActionDispatch::Http::Parameters::ParseError do |e|
render_error(:bad_request, "bad_request", e.message.truncate(200))
end
rescue_from ActiveRecord::RecordInvalid do |e|
render_invalid(e.record)
end
rescue_from ActiveSupport::MessageVerifier::InvalidSignature, ActiveModel::RangeError,
ActiveRecord::NotNullViolation, ActiveRecord::InvalidForeignKey do
render_error(:unprocessable_entity, "invalid", "Some values couldn't be saved.")
end
private
attr_reader :api_token
def acting_user = Current.api_user
def authenticate
token = request.authorization.to_s[/\ABearer\s+(\S+)\z/i, 1]
@api_token = ApiToken.authenticate(token)
return render_error(:unauthorized, "unauthorized", "A valid API token is required.") unless @api_token
Current.api_token = @api_token
Current.ip_address = request.remote_ip
Current.api_user = @api_token.personal? ? @api_token.user : on_behalf_of
@api_token.used!(request.remote_ip)
end
# The person an integration is acting for, if it named one.
def on_behalf_of
email = request.headers["SAM-On-Behalf-Of"].to_s.strip.downcase.presence or return
User.active.find_by(email_address: email) ||
render_error(:unprocessable_entity, "unknown_user", "SAM-On-Behalf-Of doesn't match an active user.")
end
def require_scope!(scope)
return if api_token.allows?(scope)
render_error(:forbidden, "missing_scope", "This token doesn't have the #{scope} scope.")
end
# Writes always name a person, so the record history shows who.
def require_person!
return if acting_user
render_error(:unprocessable_entity, "on_behalf_of_required", "Writes with an integration token need SAM-On-Behalf-Of.")
end
def aircraft_scope = api_token.aircraft_scope(acting_user)
def find_aircraft(id = params[:aircraft_id]) = aircraft_scope.find(id)
# What the person it's acting for can do on the aircraft, as in the app (Role).
def can?(permission, aircraft) = acting_user&.can?(permission, aircraft) || false
def not_permitted(permission)
render_error(:forbidden, "not_permitted", "This needs the \"#{Permission.label(permission)}\" permission on the aircraft.")
end
# ?limit= (1–200, default 50), ?after=<id> to continue, ?updated_since=<ISO time>.
def paginate(scope)
limit = params.fetch(:limit, 50).to_i.clamp(1, MAX_PAGE)
scope = scope.where(scope.arel_table[:id].gt(params[:after].to_i)) if params[:after].present?
if params[:updated_since].present?
since = Time.iso8601(params[:updated_since].to_s) rescue (raise ActionController::BadRequest, "updated_since must be an ISO 8601 time")
scope = scope.where(scope.arel_table[:updated_at].gteq(since))
end
records = scope.reorder(:id).limit(limit + 1).to_a
more = records.size > limit
records = records.first(limit)
[ records, (records.last.id if more) ]
end
def render_page(scope, &present)
records, next_after = paginate(scope)
render json: { data: records.map(&present), next_after: next_after }
end
def render_error(status, code, message, fields: nil)
render json: { error: { code: code, message: message, fields: fields }.compact }, status: status
end
def render_invalid(record)
render_error(:unprocessable_entity, "invalid", record.errors.full_messages.to_sentence, fields: record.errors.to_hash)
end
# The same Idempotency-Key again (a retry) gets the first answer; the
# same key with a different request is a conflict.
def idempotent
key = request.headers["Idempotency-Key"].to_s.strip
return yield if key.empty? || api_token.nil?
return render_error(:bad_request, "bad_request", "Idempotency-Key is too long.") if key.length > 100
digest = OpenSSL::Digest::SHA256.hexdigest([ request.method, request.path, request.raw_post ].join("\n"))
if (seen = api_token.idempotency_keys.find_by(key: key))
return render_error(:conflict, "idempotency_conflict", "This Idempotency-Key was used for a different request.") if seen.request_digest != digest
response.headers["Idempotent-Replay"] = "true"
return render(json: seen.response_body, status: seen.response_status)
end
yield
return if response.status >= 500
api_token.idempotency_keys.create(key: key, request_digest: digest, response_status: response.status,
response_body: response.body, created_at: Time.current)
end
end
end
end
@@ -0,0 +1,129 @@
module Api
module V1
# Draft logbook entries for one visit (docs/api.md, "Draft entries"). The
# work items become one unsigned entry per logbook, signed in the app; the
# squawks they resolve and inspections they complete are held until every
# entry is signed. Like writing entries in the app, it's for the
# aircraft's owners.
class DraftBatchesController < BaseController
before_action -> { require_scope!(:read) }, only: %i[index show lookup]
before_action -> { require_scope!("drafts:write") }, :require_person!, only: %i[create destroy]
def index
scope = find_aircraft.draft_batches.includes(entries: :signature)
scope = scope.where(status: params[:status]) if params[:status].present?
render_page(scope) { ApiPresenter.draft_batch(_1) }
end
def lookup
scope = DraftBatch.where(aircraft: aircraft_scope, external_ref: params.require(:external_ref)).includes(entries: :signature)
render json: { data: scope.map { ApiPresenter.draft_batch(_1) } }
end
def show
render json: { data: ApiPresenter.draft_batch(find_batch) }
end
# POST /aircraft/:aircraft_id/draft_batches
def create
@aircraft = find_aircraft
return not_permitted(:write_logbook) unless can?(:write_logbook, @aircraft)
input = params.require(:draft_batch)
items = Array(input[:items]).map { _1.permit(:log, :text, :external_ref, resolves_squawks: []) }
errors = check(input, items)
return render_error(:unprocessable_entity, "invalid", errors.values.flatten.to_sentence, fields: errors) if errors.any?
invitations = {}
batch = DraftBatch.transaction do
b = @aircraft.draft_batches.create!(api_token: api_token, created_by: acting_user, external_ref: input[:external_ref],
signer_email: signer_email(input), held: held(input, items))
items.group_by { _1[:log] }.each do |log, group|
entry = b.entries.create!(aircraft: @aircraft, log_type: log, date: input[:date], text: group.map { _1[:text].to_s.strip }.join("\n\n"),
entry_type: inspection_logs(input, items).include?(log) ? "INSPECTION" : "MAINTENANCE",
inspection_result: inspection_result_for(input, items, log),
aircraft_hours_at_entry: input[:aircraft_hours].presence, external_ref: group.filter_map { _1[:external_ref] }.join(",").presence)
invitations[entry.id] = invite(entry, b.signer_email, send: input.dig(:signer, :send_email).to_s == "true") if b.signer_email
end
b
end
@aircraft.log_event!("logbook", I18n.t("api.draft_batches.sent", count: batch.entries.size, name: api_token.name), notes: batch.external_ref)
render json: { data: ApiPresenter.draft_batch(batch.reload, invitations: invitations) }, status: :created
end
# DELETE /draft_batches/:id: withdraw it while nothing in it is signed.
def destroy
batch = find_batch
return not_permitted(:write_logbook) unless can?(:write_logbook, batch.aircraft)
unless batch.awaiting? && batch.entries.none?(&:signed?)
return render_error(:conflict, "signed", "Part of this draft is signed (or it's no longer awaiting signature); correct it in the app instead.")
end
batch.withdraw!
render json: { data: ApiPresenter.draft_batch(batch.reload) }
end
private
def find_batch = DraftBatch.where(aircraft: aircraft_scope).includes(entries: :signature).find(params[:id])
def check(input, items)
errors = Hash.new { |h, k| h[k] = [] }
errors[:items] << "at least one item is needed" if items.empty?
items.each_with_index do |item, i|
errors[:"items.#{i}.log"] << "must be one of #{LogbookEntry::LOG_TYPES.keys.join(', ')}" unless LogbookEntry::LOG_TYPES.key?(item[:log])
errors[:"items.#{i}.text"] << "can't be blank" if item[:text].blank?
end
errors[:date] << "must be a date (YYYY-MM-DD)" unless (Date.iso8601(input[:date].to_s) rescue nil)
errors[:aircraft_hours] << "must be a number" if input[:aircraft_hours].present? && !input[:aircraft_hours].to_s.match?(/\A\d+(\.\d+)?\z/)
squawk_ids = items.flat_map { Array(_1[:resolves_squawks]) }.map(&:to_i)
missing = squawk_ids - @aircraft.squawks.active.where(id: squawk_ids).ids
errors[:resolves_squawks] << "no open squawk #{missing.join(', ')} on this aircraft" if missing.any?
Array(input[:completes_inspections]).each_with_index do |c, i|
id = c.respond_to?(:[]) ? c[:inspection_type_id].to_i : 0
errors[:"completes_inspections.#{i}"] << "no inspection #{id} applies to this aircraft" unless @aircraft.applicable_inspection_types.exists?(id: id)
log = inspection_log(c, items)
errors[:"completes_inspections.#{i}.log"] << "must be the log of one of the items" unless items.any? { _1[:log] == log }
unless LogbookEntry::INSPECTION_RESULTS.key?(c.respond_to?(:[]) ? c[:result].to_s : "")
errors[:"completes_inspections.#{i}.result"] << "must be #{LogbookEntry::INSPECTION_RESULTS.keys.join(' or ')}"
end
end
Array(input[:completes_inspections]).group_by { inspection_log(_1, items) }.each do |log, group|
errors[:completes_inspections] << "inspections in the #{log} log need the same result (one entry)" if group.map { _1[:result].to_s }.uniq.size > 1
end
errors[:aircraft_hours] << "is needed to record an inspection" if Array(input[:completes_inspections]).any? && input[:aircraft_hours].blank?
email = input.dig(:signer, :email).to_s.strip
errors[:"signer.email"] << "isn't an email address" if email.present? && !email.match?(URI::MailTo::EMAIL_REGEXP)
errors[:"signer.send_email"] << "needs email set up on the server" if input.dig(:signer, :send_email).to_s == "true" && !MailSettings.configured?
errors
end
# The inspection goes in the logbook named for it, else the airframe
# log if there's an item for it, else the first item's.
def inspection_log(c, items)
c[:log].presence || (items.any? { _1[:log] == "AC" } ? "AC" : items.first&.dig(:log))
end
def inspection_logs(input, items) = Array(input[:completes_inspections]).map { inspection_log(_1, items) }
# approved | discrepancies, for the entry in that log that records inspections.
def inspection_result_for(input, items, log)
Array(input[:completes_inspections]).find { inspection_log(_1, items) == log }&.dig(:result)
end
def held(input, items)
{ "squawks" => items.flat_map { |it| Array(it[:resolves_squawks]).map { |id| { "id" => id.to_i, "log" => it[:log] } } }.uniq { _1["id"] },
"inspections" => Array(input[:completes_inspections]).map { { "id" => _1[:inspection_type_id].to_i, "log" => inspection_log(_1, items) } } }
end
def signer_email(input) = input.dig(:signer, :email).to_s.strip.downcase.presence
# A link for the signer to sign this entry with their own account,
# returned to the caller to pass on; emailed too when asked.
def invite(entry, email, send: false)
invitation = entry.signing_invitations.create!(email: email, invited_by: acting_user)
SigningInvitationMailer.invite(invitation, invitation.token).deliver_later if send
invitation.token
end
end
end
end
+16
View File
@@ -0,0 +1,16 @@
module Api
module V1
# What this token is and who it's acting as: a quick check for a new integration.
class MeController < BaseController
def show
render json: { data: {
token: { name: api_token.name, kind: api_token.kind, hint: api_token.token_hint, scopes: api_token.scopes,
aircraft_ids: (api_token.aircraft_ids if api_token.integration?) }.compact,
acting_as: acting_user && { id: acting_user.id, name: acting_user.display_name, email: acting_user.email_address },
aircraft_ids: aircraft_scope.ids,
api_version: "v1", app_version: Rails.root.join("VERSION").read.strip
} }
end
end
end
end
@@ -0,0 +1,67 @@
module Api
module V1
# Squawks: list and report on an aircraft; find by external_ref; update.
# Resolving happens through a signed logbook entry, not here.
class SquawksController < BaseController
before_action -> { require_scope!(:read) }, only: %i[index show lookup]
before_action -> { require_scope!("squawks:write") }, :require_person!, only: %i[create update]
# GET /aircraft/:aircraft_id/squawks?status=open|resolved|all (default open)
def index
scope = find_aircraft.squawks.includes(:reported_by).with_attached_attachments
scope = case params.fetch(:status, "open")
when "open" then scope.active
when "resolved" then scope.resolved
else scope
end
render_page(scope) { ApiPresenter.squawk(_1) }
end
# GET /squawks?external_ref=redmine:issue:4512
def lookup
ref = params.require(:external_ref)
scope = Squawk.where(aircraft: aircraft_scope, external_ref: ref).includes(:reported_by).with_attached_attachments
render json: { data: scope.map { ApiPresenter.squawk(_1) } }
end
def show
render json: { data: ApiPresenter.squawk(find_squawk) }
end
# POST /aircraft/:aircraft_id/squawks
def create
aircraft = find_aircraft
return not_permitted(:report_squawks) unless can?(:report_squawks, aircraft)
squawk = aircraft.squawks.new(create_params.merge(reported_by: acting_user, resolved: false))
squawk.component_id = nil unless aircraft.components.exists?(id: squawk.component_id)
squawk.save!
SquawkReported.call(squawk, by: acting_user)
render json: { data: ApiPresenter.squawk(squawk) }, status: :created
end
# PATCH /squawks/:id: external_ref by anyone who may write; the rest
# (issue, priority, component, notes) with "manage squawks", as in the app.
def update
squawk = find_squawk
return render_error(:unprocessable_entity, "resolved", "A resolved squawk can't be changed.") if squawk.resolved?
attrs = params.require(:squawk).permit(:external_ref, :issue_reported, :priority, :component_id, :notes)
if (attrs.keys - %w[external_ref]).any? && !can?(:manage_squawks, squawk.aircraft)
return not_permitted(:manage_squawks)
end
attrs[:component_id] = nil if attrs.key?(:component_id) && !squawk.aircraft.components.exists?(id: attrs[:component_id])
squawk.update!(attrs)
render json: { data: ApiPresenter.squawk(squawk) }
end
private
def find_squawk = Squawk.where(aircraft: aircraft_scope).find(params[:id])
def create_params
params.require(:squawk).permit(:issue_reported, :priority, :component_id, :external_ref).tap do |p|
p[:priority] = p.fetch(:priority, 2).to_i
end
end
end
end
end
+19
View File
@@ -0,0 +1,19 @@
# Profile → API tokens: personal tokens for the REST API (docs/api.md). The
# token is shown once, on the page right after it's made (not kept in the
# flash or anywhere else).
class ApiTokensController < ApplicationController
def create
@token = current_user.api_tokens.new(name: params.dig(:api_token, :name), kind: "personal",
scopes: Array(params.dig(:api_token, :scopes)) & ApiToken::SCOPES.keys)
if @token.save
render :created
else
redirect_to edit_profile_path(anchor: "api"), alert: @token.errors.full_messages.to_sentence
end
end
def destroy
current_user.api_tokens.personal.active.find(params[:id]).revoke!
redirect_to edit_profile_path(anchor: "api"), notice: t("flash.api_tokens.revoked")
end
end
+38
View File
@@ -4,7 +4,9 @@ class ApplicationController < ActionController::Base
include TimeZones
allow_browser versions: :modern
include RejectsNullBytes
prepend_before_action :redirect_to_setup
prepend_before_action :viewer_guard # first (see Viewer)
before_action { Current.ip_address = request.remote_ip } # for record history
helper_method :current_user
@@ -15,15 +17,51 @@ class ApplicationController < ActionController::Base
end
end
# Asked for a format a page doesn't have (/aircraft/1/report.pdf): not a crash.
rescue_from ActionView::MissingTemplate do |error|
raise error if request.format.html?
head :not_acceptable
end
# Input no form produces: a tampered upload reference, a number too big to
# store, a missing required value or a link to a record that isn't there.
# The forms validate what people can enter; this is the safety net.
rescue_from ActiveSupport::MessageVerifier::InvalidSignature, ActiveModel::RangeError,
ActiveRecord::NotNullViolation, ActiveRecord::InvalidForeignKey do |error|
Rails.logger.warn("[input] #{error.class}: #{error.message.truncate(200)}")
respond_to do |format|
format.html { redirect_back_or_to root_path, alert: t("flash.application.invalid_input") }
format.any { head :unprocessable_entity }
end
end
private
def current_user = Current.user
# First run: no users yet → create the initial admin.
# Viewer mode: never with real accounts, and nothing can be changed.
def viewer_guard
return unless Viewer.enabled?
return render(plain: Viewer::RealAccounts.new.message, status: :service_unavailable) if Viewer.real_accounts?
Viewer.user
return if request.get? || request.head?
respond_to do |format|
format.html { redirect_back fallback_location: root_path, alert: t("viewer.read_only") }
format.any { head :forbidden }
end
end
def redirect_to_setup
redirect_to new_setup_path if !User.exists? && !is_a?(SetupController)
end
# Adding or importing an aircraft (User#can_add_aircraft?).
def require_aircraft_adder!
redirect_to root_path, alert: t("flash.aircraft.ask_an_administrator") unless current_user.can_add_aircraft?
end
def require_admin!
redirect_to root_path, alert: t("flash.application.admins_only") unless current_user&.admin?
end
+1 -1
View File
@@ -1,6 +1,6 @@
class ComponentsController < ApplicationController
include AircraftScoped
before_action :require_owner!, except: %i[index show]
requires_permission :manage_components, except: %i[index show]
before_action :set_component, only: %i[show edit update destroy reset_service]
def index
+54 -15
View File
@@ -1,16 +1,38 @@
# Scopes a controller to one aircraft the current user can access and exposes
# role helpers. Unknown and inaccessible aircraft both 404 (enumeration-safe).
# Scopes a controller to one aircraft the current user can access, and checks
# what their role there allows (Role, Permission). Unknown and inaccessible
# aircraft both 404 (enumeration-safe). Administrators can do everything.
#
# Access matrix (mirrors the original):
# admin – everything
# owner – everything on their aircraft
# pilot – view all; update hours; create squawks, notes, oil/fuel, flight logs
# Each controller says which permission its actions need:
#
# requires_permission :manage_components, except: %i[index show]
# requires_permission :report_squawks, only: %i[new create]
# checks_permission_itself only: %i[edit update] # decided in the controller
#
# Looking needs no permission. A request that changes something (anything but
# GET/HEAD) with no permission declared for its action is refused, so nothing
# is left open by mistake; in development and tests it raises instead.
module AircraftScoped
extend ActiveSupport::Concern
SELF_CHECKED = "(checked by the controller)".freeze
class MissingPermission < StandardError; end
included do
class_attribute :permission_rules, instance_accessor: false, default: []
before_action :set_aircraft
helper_method :current_role, :owner?, :can_write?
before_action :authorize_permission!
helper_method :current_role, :can?, :owner?
end
class_methods do
def requires_permission(permission, only: nil, except: nil)
self.permission_rules += [ [ permission.to_s, only && Array(only).map(&:to_s), except && Array(except).map(&:to_s) ] ]
end
def checks_permission_itself(only:)
requires_permission(SELF_CHECKED, only: only)
end
end
private
@@ -21,18 +43,35 @@ module AircraftScoped
@aircraft = current_user.accessible_aircraft.find(aircraft_param)
end
# Their Role here (nil for an administrator without one).
def current_role
@current_role ||= current_user.role_for(@aircraft)
return @current_role if defined?(@current_role)
@current_role = current_user.role_for(@aircraft)
end
# Owner-level write access (admins included).
def owner? = current_role.in?(%w[admin owner])
alias_method :can_write?, :owner?
# Nothing in viewer mode (a read-only copy, see Viewer).
def can?(permission) = !Viewer.enabled? && (current_user.admin? || current_role&.can?(permission) || false)
def require_owner!
return if owner?
redirect_back fallback_location: aircraft_path(@aircraft),
alert: t("flash.common.only_owners_can_do")
# The Owner role (or an administrator): everything.
def owner? = !Viewer.enabled? && (current_user.admin? || current_role&.owner? || false)
def authorize_permission!
rules = self.class.permission_rules.select do |_, only, except|
(only.nil? || only.include?(action_name)) && (except.nil? || except.exclude?(action_name))
end
if rules.empty?
return if request.get? || request.head?
raise MissingPermission, "#{self.class.name}##{action_name} changes data without declaring a permission" if Rails.env.local?
return permission_denied
end
permission_denied unless rules.all? { |permission, *| permission == SELF_CHECKED || can?(permission) }
end
def permission_denied
respond_to do |format|
format.html { redirect_back fallback_location: aircraft_path(@aircraft), alert: t("flash.common.not_allowed") }
format.any { head :forbidden }
end
end
# Returns id only if it belongs to the given (aircraft-scoped) relation; else nil.
+6 -1
View File
@@ -21,7 +21,12 @@ module Authentication
end
def require_authentication
resume_session || request_authentication
resume_session || start_viewer_session || request_authentication
end
# Viewer mode: everyone is its built-in account, without signing in.
def start_viewer_session
start_new_session_for(Viewer.user) if Viewer.enabled? && !Viewer.real_accounts?
end
def resume_session
@@ -0,0 +1,22 @@
# No form or API client sends a null byte; some libraries (password hashing,
# file paths) raise on one, so such requests are refused up front.
module RejectsNullBytes
extend ActiveSupport::Concern
included { prepend_before_action :reject_null_bytes }
private
def reject_null_bytes
head :bad_request if contains_null_byte?(request.params)
end
def contains_null_byte?(value)
case value
when String then value.include?("\0")
when Hash then value.any? { |k, v| contains_null_byte?(k) || contains_null_byte?(v) }
when Array then value.any? { contains_null_byte?(_1) }
else false
end
end
end
@@ -1,6 +1,7 @@
class ConsumableRecordsController < ApplicationController
include AircraftScoped
before_action :require_owner!, only: %i[edit update destroy]
requires_permission :record_consumables, only: %i[new create]
requires_permission :manage_consumables, only: %i[edit update destroy]
before_action :set_record, only: %i[edit update destroy]
RECORDS_PER_PAGE = 50
@@ -1,6 +1,6 @@
class DocumentCollectionsController < ApplicationController
include AircraftScoped
before_action :require_owner!
requires_permission :manage_documents
before_action :set_collection, only: %i[edit update destroy]
def new
+1 -1
View File
@@ -1,6 +1,6 @@
class DocumentsController < ApplicationController
include AircraftScoped
before_action :require_owner!, except: %i[index show]
requires_permission :manage_documents, except: %i[index show]
before_action :set_document, only: %i[show edit update destroy]
def index
@@ -3,6 +3,7 @@
# who they are again (password, or single sign-on just now), and confirms.
class EntrySignaturesController < ApplicationController
include AircraftScoped
requires_permission :sign_logbook
include EntrySigning
before_action :set_entry
+10 -2
View File
@@ -1,10 +1,18 @@
class EventsController < ApplicationController
include AircraftScoped
EVENTS_PER_PAGE = 50
# A page at a time; the rest load as you scroll (each page ends in a lazy
# frame that fetches the next).
def index
@category = params[:category].presence_in(AircraftEvent::CATEGORIES.keys)
scope = @aircraft.events.includes(:user)
@page = [ params[:page].to_i, 1 ].max
scope = @aircraft.events.includes(:user).reorder(created_at: :desc, id: :desc)
scope = scope.where(category: @category) if @category
@events = scope.limit(200)
rows = scope.offset((@page - 1) * EVENTS_PER_PAGE).limit(EVENTS_PER_PAGE + 1).to_a
@more = rows.size > EVENTS_PER_PAGE
@events = rows.first(EVENTS_PER_PAGE)
render(partial: "events/page", locals: { events: @events, page: @page, more: @more, category: @category }) if turbo_frame_request?
end
end
+1 -1
View File
@@ -2,7 +2,7 @@
class FlightImportsController < ApplicationController
include AircraftScoped
include StoredUpload
before_action :require_owner!
requires_permission :import_flights
def new; end
+33 -5
View File
@@ -1,7 +1,11 @@
class FlightLogsController < ApplicationController
include AircraftScoped
before_action :require_owner!, only: :destroy
before_action :set_flight_log, only: %i[show engine_data_series attach_engine_data remove_engine_data]
requires_permission :log_flights, only: %i[new create]
requires_permission :delete_flights, only: :destroy
checks_permission_itself only: %i[edit update attach_engine_data remove_engine_data]
before_action :set_flight_log, only: %i[show edit update engine_data_series attach_engine_data remove_engine_data]
before_action :require_flight_editor!, only: %i[edit update]
helper_method :can_edit_flight?
before_action :require_engine_data_access!, only: %i[attach_engine_data remove_engine_data]
helper_method :manage_engine_data?
@@ -99,6 +103,22 @@ class FlightLogsController < ApplicationController
redirect_to aircraft_flight_log_path(@aircraft, @flight_log), notice: t("flash.flight_logs.engine_data_removed")
end
def edit
@meters_editable = @flight_log.meters_editable?
end
# A correction. The readings only change on the latest flight (see
# FlightLog#meters_editable?); on earlier ones they're left as they are.
def update
@meters_editable = @flight_log.meters_editable?
attributes = flight_log_params.except(:client_key)
attributes = attributes.except(*FlightLog::METERS) unless @meters_editable
HoursService.new(@aircraft).update_flight!(@flight_log, attributes)
redirect_to aircraft_flight_log_path(@aircraft, @flight_log), notice: t("flash.flight_logs.flight_corrected")
rescue ActiveRecord::RecordInvalid
render :edit, status: :unprocessable_entity
end
# Deleting a flight does not roll back hours; correct those with an hours update.
def destroy
@aircraft.flight_logs.find(params[:id]).destroy!
@@ -108,14 +128,22 @@ class FlightLogsController < ApplicationController
private
# Any flight with "correct any flight"; the ones they logged with "correct own flights".
def can_edit_flight?(flight)
can?(:edit_any_flight) || (can?(:edit_own_flights) && flight.user_id.present? && flight.user_id == current_user.id)
end
def require_flight_editor!
return if can_edit_flight?(@flight_log)
redirect_to aircraft_flight_log_path(@aircraft, @flight_log), alert: t("flash.flight_logs.only_owners_or_the")
end
def set_flight_log
@flight_log = @aircraft.flight_logs.find(params[:id])
end
# Owners, or the pilot who logged the flight.
def manage_engine_data?
owner? || (@flight_log.user_id.present? && @flight_log.user_id == current_user.id)
end
def manage_engine_data? = can_edit_flight?(@flight_log)
def require_engine_data_access!
return if manage_engine_data?
@@ -1,6 +1,6 @@
class InspectionRecordsController < ApplicationController
include AircraftScoped
before_action :require_owner!
requires_permission :manage_inspections
before_action :set_record, only: %i[edit update destroy]
def new
@@ -1,7 +1,7 @@
class InspectionTypesController < ApplicationController
include AircraftScoped
include Applicability
before_action :require_owner!
requires_permission :manage_inspections
before_action :set_type, only: %i[edit update destroy]
def new
@@ -1,6 +1,7 @@
# The invited signer's side: sign in (or create an account for the invited
# address), add a certificate if needed, review the entry and sign it. The
# invitation gives access to that one entry only.
# The invited signer's side: sign in (or, from an Owner's invitation, create an
# account for the invited address: SigningInvitation#creates_account?), add a
# certificate if needed, review the entry and sign it. The invitation gives
# access to that one entry only.
class InvitedSigningsController < ApplicationController
include EntrySigning
allow_unauthenticated_access only: %i[show account]
@@ -12,6 +13,7 @@ class InvitedSigningsController < ApplicationController
@aircraft = @entry.aircraft
unless authenticated?
session[:return_to_after_authenticating] = request.url
session[:signing_token] = params[:token] # for an account made by signing in with SSO
return render(:welcome)
end
return render(:wrong_account) unless current_user.email_address == @invitation.email
@@ -20,10 +22,10 @@ class InvitedSigningsController < ApplicationController
render :new
end
# Creating an account for the invited email address.
# Creating an account for the invited email address (an Owner's invitation).
def account
return redirect_to(invited_signing_path(params[:token])) if authenticated?
if User.exists?(email_address: @invitation.email) || !Sso.password_login?
if User.exists?(email_address: @invitation.email) || !Sso.password_login? || !@invitation.creates_account?
return redirect_to invited_signing_path(params[:token]), alert: t("flash.invited_signings.sign_in_to_continue")
end
user = User.new(params.permit(:name, :password, :password_confirmation).merge(email_address: @invitation.email))
+68
View File
@@ -0,0 +1,68 @@
# Opening an invitation link (AccessInvitation): see what it gives, then sign
# in and accept. Only an administrator's invitation can make a new account
# (with a password here, or by signing in with SSO: SsoController); others
# need an existing one. An invitation for one email address only works for
# that address. Any invalid link (unknown, expired, used up, revoked) gets
# one answer.
class JoinsController < ApplicationController
allow_unauthenticated_access only: %i[show account]
before_action :set_invitation
rate_limit to: 10, within: 15.minutes, only: %i[account accept],
with: -> { redirect_to join_path(params[:token]), alert: t("flash.joins.try_again_later") }
def show
unless current_user
session[:return_to_after_authenticating] = request.url
session[:join_token] = params[:token] # for an account made by signing in with SSO
return render(:welcome)
end
return redirect_to(root_path, notice: t("flash.joins.already_accepted")) if @invitation.redeemed_by?(current_user)
return render(:wrong_account) unless @invitation.for?(current_user)
render :accept
end
# A new account, then the invitation accepted with it.
def account
return redirect_to(join_path(params[:token])) if current_user
unless Sso.password_login? && @invitation.creates_accounts?
return redirect_to(join_path(params[:token]), alert: t("flash.joins.sign_in_to_continue"))
end
email = @invitation.email || params[:email_address].to_s.strip.downcase
if User.exists?(email_address: email)
return redirect_to join_path(params[:token]), alert: t("flash.joins.account_exists")
end
user = User.new(params.permit(:name, :password, :password_confirmation).merge(email_address: email))
results = nil
User.transaction do
raise ActiveRecord::Rollback unless user.save
results = @invitation.redeem!(user)
end
if results
reset_session
start_new_session_for user
redirect_to root_path, notice: [ t("flash.joins.welcome"), AccessInvitation.describe(results) ].join(" ").strip
else
@account_errors = user.errors.full_messages
render :welcome, status: :unprocessable_entity
end
rescue ActiveRecord::RecordInvalid
render :invalid, layout: "public", status: :not_found
end
def accept
return redirect_to(root_path, notice: t("flash.joins.already_accepted")) if @invitation.redeemed_by?(current_user)
return render(:wrong_account) unless @invitation.for?(current_user)
redirect_to root_path, notice: [ t("flash.joins.accepted"), AccessInvitation.describe(@invitation.redeem!(current_user)) ].join(" ").strip
rescue ActiveRecord::RecordInvalid
render :invalid, layout: "public", status: :not_found
end
private
def set_invitation
@invitation = AccessInvitation.find_by_token(params[:token])
render :invalid, layout: "public", status: :not_found unless @invitation&.usable?
end
def current_user = Current.user || (resume_session && Current.user)
end
+1 -1
View File
@@ -2,7 +2,7 @@
# the loading calculator.
class LoadingSetupsController < ApplicationController
include AircraftScoped
before_action :require_owner!
requires_permission :manage_weight_balance
def edit
@setup = @aircraft.loading_setup
@@ -1,6 +1,6 @@
class LogbookEntriesController < ApplicationController
include AircraftScoped
before_action :require_owner!, except: %i[index show]
requires_permission :write_logbook, except: %i[index show]
before_action :set_entry, only: %i[show edit update destroy verify]
before_action :require_unsigned, only: %i[edit update destroy]
@@ -3,14 +3,14 @@
# entries in the background (LogbookTranscriptionJob).
class LogbookImportsController < ApplicationController
include AircraftScoped
before_action :require_owner!
requires_permission :import_records
def new
@collections = @aircraft.document_collections.ordered
end
def create
files = Array(params[:pages]).compact_blank
files = Array(params[:pages]).select { _1.respond_to?(:original_filename) } # uploaded files only
return redirect_to(new_aircraft_logbook_import_path(@aircraft), alert: t("flash.logbook_imports.choose_the_scanned_pages")) if files.empty?
# Page order follows the file names ("page-002" before "page-010").
+1 -1
View File
@@ -1,6 +1,6 @@
class MajorRecordsController < ApplicationController
include AircraftScoped
before_action :require_owner!, except: %i[index show]
requires_permission :manage_major_records, except: %i[index show]
before_action :set_record, only: %i[show edit update destroy]
def index
+2 -1
View File
@@ -1,6 +1,7 @@
class NotesController < ApplicationController
include AircraftScoped
before_action :require_owner!, only: %i[edit update destroy]
requires_permission :write_notes, only: %i[new create preview]
requires_permission :manage_notes, only: %i[edit update destroy]
before_action :set_note, only: %i[edit update destroy]
def index
+3 -2
View File
@@ -1,6 +1,7 @@
class OilAnalysesController < ApplicationController
include AircraftScoped
before_action :require_owner!, only: %i[edit update destroy]
requires_permission :record_oil_analyses, only: %i[new create import]
requires_permission :manage_oil_analyses, only: %i[edit update destroy]
before_action :set_analysis, only: %i[show edit update destroy]
COMPARE_SAMPLES = 6 # columns in the trend table, like the lab report's history
@@ -35,7 +36,7 @@ class OilAnalysesController < ApplicationController
# earlier samples, so samples already on file are skipped rather than duplicated.
def import
file = params[:report]
return redirect_to(new_aircraft_oil_analysis_path(@aircraft), alert: t("flash.oil_analyses.choose_a_lab_report")) if file.blank?
return redirect_to(new_aircraft_oil_analysis_path(@aircraft), alert: t("flash.oil_analyses.choose_a_lab_report")) unless file.respond_to?(:tempfile)
report = OilReportParser.from_pdf(file.tempfile)
file.rewind
@@ -6,7 +6,13 @@ class PushSubscriptionsController < ApplicationController
record = PushSubscription.find_or_initialize_by(endpoint: sub[:endpoint].to_s)
record.assign_attributes(user: current_user, p256dh: sub.dig(:keys, :p256dh), auth: sub.dig(:keys, :auth),
user_agent: request.user_agent.to_s.first(250))
record.save ? head(:created) : head(:unprocessable_entity)
if record.save
head :created
else
render json: { error: t("flash.push_subscriptions.not_saved", host: URI.parse(record.endpoint).host.to_s) }, status: :unprocessable_entity
end
rescue URI::InvalidURIError
render json: { error: t("flash.push_subscriptions.not_saved", host: "?") }, status: :unprocessable_entity
end
def destroy
@@ -14,9 +20,35 @@ class PushSubscriptionsController < ApplicationController
head :no_content
end
# A notification to this user's devices, to check they arrive.
# A notification to each of this user's devices, sent now so the page can
# say which push services took it (and why one didn't).
def test
PushNotifier.notify(current_user, :test, path: edit_profile_path, tag: "test")
head :accepted
message = PushNotificationJob.message("test", edit_profile_path, "test")
devices = current_user.push_subscriptions.order(:created_at).map do |sub|
{ device: device_name(sub.user_agent), error: PushNotificationJob.deliver(sub, message) }
end
render json: { devices: devices }
end
private
# "Chrome on Android" from the browser's description of itself.
def device_name(agent)
browser = case agent
when /Edg\//, /EdgA\// then "Edge"
when /SamsungBrowser/ then "Samsung Internet"
when /Firefox|FxiOS/ then "Firefox"
when /Chrome|CriOS/ then "Chrome"
when /Safari/ then "Safari"
end
system = case agent
when /Android/ then "Android"
when /iPhone/ then "iPhone"
when /iPad/ then "iPad"
when /Macintosh/ then "Mac"
when /Windows/ then "Windows"
when /Linux/ then "Linux"
end
[ browser, system ].compact.join(" · ").presence || t("flash.push_subscriptions.unknown_device")
end
end
@@ -1,7 +1,7 @@
# Every change to the aircraft's maintenance records (AC 120-78B 3.2.2).
class RecordVersionsController < ApplicationController
include AircraftScoped
before_action :require_owner!, only: :restore
requires_permission :restore_history, only: :restore
SHARED = { "AirworthinessDirective" => AirworthinessDirective, "InspectionType" => InspectionType }.freeze
@@ -1,7 +1,7 @@
# Download every record of an aircraft in one ZIP (owners).
class RecordsPackagesController < ApplicationController
include AircraftScoped
before_action :require_owner!
requires_permission :export_data
def show
package = RecordsPackage.new(@aircraft, source: request.host)
+8
View File
@@ -1,16 +1,24 @@
class SetupController < ApplicationController
allow_unauthenticated_access
before_action { redirect_to root_path if User.exists? }
rate_limit to: 10, within: 15.minutes, only: :create, with: -> { redirect_to new_setup_path, alert: t("flash.setup.try_again_later") }
layout "public"
def new
@user = User.new
SetupCode.announce
end
def create
@user = User.new(params.require(:user).permit(:name, :email_address, :password, :password_confirmation))
@user.admin = true
unless SetupCode.matches?(params[:setup_code])
@user.errors.add(:base, t("flash.setup.wrong_code"))
SetupCode.announce
return render(:new, status: :unprocessable_entity)
end
if @user.save
SetupCode.clear
start_new_session_for @user
redirect_to root_path, notice: t("flash.setup.welcome_you_re_the")
else
+1 -1
View File
@@ -1,6 +1,6 @@
class ShareTokensController < ApplicationController
include AircraftScoped
before_action :require_owner!
requires_permission :manage_sharing
def create
token = @aircraft.share_tokens.new(params.require(:share_token).permit(:label, :privilege, :expires_at))
@@ -1,7 +1,7 @@
# An owner asks someone outside the aircraft (a mechanic) to sign an entry.
class SigningInvitationsController < ApplicationController
include AircraftScoped
before_action :require_owner!
requires_permission :write_logbook
before_action :set_entry
rate_limit to: 10, within: 1.hour, only: :create, with: -> { redirect_back fallback_location: root_path, alert: t("flash.signing_invitations.too_many_invitations_try") }
@@ -22,7 +22,9 @@ class SigningInvitationsController < ApplicationController
tail: @aircraft.tail_number, name: current_user.display_name)
end
log_event("logbook", t("flash.signing_invitations.signature_requested_from_entry", email: @invitation.email, date: l(@entry.date, format: :app)))
redirect_to aircraft_logbook_entry_path(@aircraft, @entry), notice: t("flash.signing_invitations.invitation_sent_to_the", email: @invitation.email, days: SigningInvitation::VALID_FOR.in_days.to_i)
notice = t("flash.signing_invitations.invitation_sent_to_the", email: @invitation.email, days: SigningInvitation::VALID_FOR.in_days.to_i)
notice = "#{notice} #{t('flash.signing_invitations.no_account_yet')}" unless invitee || @invitation.creates_account?
redirect_to aircraft_logbook_entry_path(@aircraft, @entry), notice: notice
else
render :new, status: :unprocessable_entity
end
+4 -6
View File
@@ -2,7 +2,9 @@ class SquawksController < ApplicationController
include AircraftScoped
# Pilots may create squawks and defer inoperative items (91.213(d) lets the
# pilot decide); editing and resolving need an owner.
before_action :require_owner!, except: %i[index new create deferral defer]
requires_permission :report_squawks, only: %i[new create]
requires_permission :defer_squawks, only: %i[deferral defer]
requires_permission :manage_squawks, except: %i[index new create deferral defer]
before_action :set_squawk, only: %i[edit update destroy resolution resolve reopen deferral defer undefer]
def index
@@ -21,11 +23,7 @@ class SquawksController < ApplicationController
end
@squawk = @aircraft.squawks.new(squawk_params.merge(reported_by: current_user))
if @squawk.save
log_event("squawk", t("flash.squawks.squawk_reported_2", priority_label: @squawk.priority_label), notes: @squawk.issue_reported.truncate(200))
if @squawk.grounding?
PushNotifier.notify(@aircraft.users.merge(User.active).where.not(id: current_user.id), :grounding_squawk, path: aircraft_squawks_path(@aircraft),
tag: "squawk-#{@squawk.id}", tail: @aircraft.tail_number, issue: @squawk.issue_reported.truncate(120))
end
SquawkReported.call(@squawk, by: current_user)
redirect_to aircraft_squawks_path(@aircraft), notice: t("flash.squawks.squawk_reported")
else
render :new, status: :unprocessable_entity
+28 -3
View File
@@ -6,6 +6,11 @@
# email is verified (or OIDC_TRUST_EMAIL is on), since some providers let
# users edit their email. Otherwise, sign in with a password once and link
# from the profile page.
#
# Someone without an account gets one only from an invitation they opened
# first that can make one (an administrator's AccessInvitation, accepted at
# once; an Owner's SigningInvitation, for its address), or for anyone the
# provider lets in when OIDC_AUTO_CREATE_USERS is on.
class SsoController < ApplicationController
allow_unauthenticated_access only: %i[callback failure]
before_action :require_sso
@@ -29,6 +34,7 @@ class SsoController < ApplicationController
return_to = session[:return_to_after_authenticating]
reset_session # fresh session id after signing in
start_new_session_for user
return redirect_to(root_url, notice: [ t("flash.joins.welcome"), AccessInvitation.describe(@joined) ].join(" ").strip) if @joined
redirect_to return_to || root_url
end
@@ -81,15 +87,34 @@ class SsoController < ApplicationController
end
def create_user(auth)
return unless Sso.auto_create_users?
email = auth.info&.email.to_s.strip.downcase
return if email.blank? || User.exists?(email_address: email)
# The random password is never shown; a password reset can set a real one.
User.create!(email_address: email, name: auth.info&.name.presence, sso_uid: auth.uid, password: SecureRandom.base58(40))
invitation = invitation_making_account(email)
return unless invitation || signing_invitation_making_account?(email) || Sso.auto_create_users?
User.transaction do
# The random password is never shown; a password reset can set a real one.
user = User.create!(email_address: email, name: auth.info&.name.presence, sso_uid: auth.uid, password: SecureRandom.base58(40))
@joined = invitation&.redeem!(user)
user
end
rescue ActiveRecord::RecordInvalid
nil
end
# A signing invitation opened in this browser before signing in, from an
# Owner, for this email address.
def signing_invitation_making_account?(email)
invitation = SigningInvitation.find_usable(session[:signing_token])
invitation.present? && invitation.creates_account? && invitation.email == email
end
# The invitation opened in this browser before signing in, when it can
# make an account (an administrator's) for this email address.
def invitation_making_account(email)
invitation = AccessInvitation.find_by_token(session[:join_token])
invitation if invitation&.usable? && invitation.creates_accounts? && invitation.for_email?(email)
end
def email_verified?(auth)
[ true, "true" ].include?(raw_info(auth)["email_verified"])
end
@@ -1,6 +1,6 @@
class StandardInspectionsController < ApplicationController
include AircraftScoped
before_action :require_owner!
requires_permission :manage_inspections
def new; end
@@ -2,7 +2,7 @@
# keep the records and the loading setup).
class WeightBalanceRecordsController < ApplicationController
include AircraftScoped
before_action :require_owner!, except: :index
requires_permission :manage_weight_balance, except: :index
before_action :set_record, only: %i[edit update destroy]
def index
+6 -3
View File
@@ -3,12 +3,15 @@ module AircraftHelper
# What the app saves ahead of time for use without signal (see
# offline_prep_controller.js): for each of your aircraft, the Overview, W&B,
# Log Flight and Report Squawk pages, and its photo.
# Log Flight and Report Squawk pages (when their role allows them), and its
# photo (at both page sizes).
def offline_pages
current_user.accessible_aircraft.ordered.limit(OFFLINE_AIRCRAFT).map do |a|
role = current_user.role_for(a)
can = ->(permission) { current_user.admin? || role&.can?(permission) }
{ tail: a.tail_number, pages: [ aircraft_path(a), aircraft_weight_balance_records_path(a) ],
flight: new_aircraft_flight_log_path(a), squawk: new_aircraft_squawk_path(a),
picture: (url_for(a.picture) if a.picture.attached?) }.compact
flight: (new_aircraft_flight_log_path(a) if can.(:log_flights)), squawk: (new_aircraft_squawk_path(a) if can.(:report_squawks)),
pictures: (%i[thumb card].map { url_for(a.picture_for(_1)) }.uniq if a.picture_shown?) }.compact
end
end
# Tabs on the aircraft pages: [label, path, controller names that highlight it, owner_only]
+11
View File
@@ -7,4 +7,15 @@ module HelpHelper
html = HelpGuide.html(page, title: title, link: (links ? method(:help_page_url_for) : nil))
tag.div(html.html_safe, class: "markdown guide") # rubocop:disable Rails/OutputSafety -- sanitized in HelpGuide
end
# A piece of the guide's Markdown (an intro, one release's notes).
def guide_markdown(markdown, class: nil)
html = HelpGuide.render(markdown, link: method(:help_page_url_for))
tag.div(html.html_safe, class: [ "markdown guide", binding.local_variable_get(:class) ]) # rubocop:disable Rails/OutputSafety -- sanitized in HelpGuide
end
# "4 changes · 3 fixes · 2 for administrators"
def release_summary(release)
release.counts.map { |key, count| t("help.changelog.counts.#{key}", count: count) }.join(" · ")
end
end
+1 -1
View File
@@ -9,7 +9,7 @@ module MarkdownHelper
extension: { strikethrough: true, tagfilter: true, table: true, autolink: true, tasklist: true, header_ids: nil, footnotes: false }
}.freeze
TAGS = %w[p br strong em del a ul ol li blockquote code pre h1 h2 h3 h4 h5 h6 hr table thead tbody tr th td input span].freeze
ATTRIBUTES = %w[href title type checked disabled align class].freeze
ATTRIBUTES = %w[href title type checked disabled align].freeze
def markdown(text)
return "".html_safe if text.blank?
@@ -0,0 +1,118 @@
import { Controller } from "@hotwired/stimulus"
import { t } from "i18n"
// The top bar shows the connection at a glance (as SilverBullet does):
// - it turns red when the server can't be reached: the device is offline, or
// a request failed (signal but no internet, or the proxy answering for the
// app). While red it checks /up every so often and turns back on its own;
// - a ring fills while pages are being saved for offline use or flights and
// squawks logged offline are being sent, with the percentage in its middle;
// - while some are waiting to send, the ring is amber with how many.
// Others report with events on document:
// sam:progress { source, done, total } (done >= total when finished)
// sam:waiting { count }
// sam:unreachable / sam:reachable
// and it says when the server answers again with sam:back-online (what was
// logged offline is sent then).
// The header is replaced on every page, so the state and the listeners live
// in this module and the header on the page just shows them.
const RETRY_EVERY = 15 * 1000
const UNREACHABLE = [ 502, 503, 504 ]
const OFFLINE_COLOR = "#b91c1c" // red-700, for the phone's status bar
const state = { online: navigator.onLine, progress: {}, waiting: 0 }
let header = null // the controller on the page
let checking = null
let timer = null
let normalColor = null
// Any answer from the app (even a sign-in redirect) means it's reachable.
async function check() {
checking ||= fetch("/up", { cache: "no-store", redirect: "manual", credentials: "same-origin" })
.then((response) => !UNREACHABLE.includes(response.status), () => false)
.finally(() => { checking = null })
setOnline(await checking)
}
function setOnline(online) {
clearTimeout(timer)
if (!online) timer = setTimeout(check, RETRY_EVERY)
if (state.online === online) return
state.online = online
header?.announce(online ? t("connection.back_online") : t("connection.offline"))
update()
if (online) document.dispatchEvent(new CustomEvent("sam:back-online"))
}
// Several reports often arrive together (done sending, then none waiting):
// show them once, on the next frame, so the ring doesn't flicker between.
let frame = null
function update() {
frame ||= requestAnimationFrame(() => { frame = null; header?.render() })
}
window.addEventListener("online", check)
window.addEventListener("offline", () => setOnline(false))
document.addEventListener("visibilitychange", () => { if (document.visibilityState === "visible" && !state.online) check() })
document.addEventListener("sam:unreachable", () => setOnline(false))
document.addEventListener("turbo:fetch-request-error", () => setOnline(false))
document.addEventListener("sam:reachable", () => setOnline(true))
document.addEventListener("sam:progress", ({ detail }) => { state.progress[detail.source] = detail; update() })
document.addEventListener("sam:waiting", ({ detail }) => { state.waiting = detail.count; update() })
// Whether the server answered last time (false while the top bar is red).
export const serverReachable = () => state.online
export default class extends Controller {
static targets = [ "ring", "label", "announce" ]
connect() {
header = this
this.themeColor = document.querySelector("meta[name=theme-color]")
normalColor ||= this.themeColor?.content
if (!navigator.onLine) setOnline(false)
else if (!state.online || this.fromSavedCopy()) check() // a fresh page, or maybe the offline copy
this.render()
}
disconnect() {
if (header === this) header = null
}
fromSavedCopy() {
const rendered = Date.parse(document.querySelector("meta[name=rendered-at]")?.content || "")
return rendered && Date.now() - rendered > 60 * 1000
}
announce(text) {
if (this.hasAnnounceTarget) this.announceTarget.textContent = text
}
render() {
this.element.classList.toggle("is-offline", !state.online)
this.element.title = state.online ? "" : t("connection.offline")
if (this.themeColor && normalColor) this.themeColor.content = state.online ? normalColor : OFFLINE_COLOR
const busy = Object.values(state.progress).filter((p) => p.total && p.done < p.total)
if (busy.length) {
const done = busy.reduce((sum, p) => sum + p.done, 0)
const total = busy.reduce((sum, p) => sum + p.total, 0)
const percent = Math.floor((done / total) * 100)
const what = busy.some((p) => p.source === "send") ? "sending" : "saving"
this.showRing({ percent, number: percent, waiting: false, text: t(`connection.${what}`, { percent }) })
} else if (state.waiting) {
this.showRing({ percent: 100, number: state.waiting, waiting: true, text: t("connection.waiting", { count: state.waiting }) })
} else {
this.ringTarget.hidden = true
}
}
showRing({ percent, number, waiting, text }) {
const ring = this.ringTarget
ring.hidden = false
ring.classList.toggle("is-waiting", waiting)
ring.style.setProperty("--progress", `${percent}%`)
ring.title = text
ring.setAttribute("aria-label", text)
this.labelTarget.textContent = number
}
}
@@ -1,10 +1,18 @@
import { Controller } from "@hotwired/stimulus"
import { t } from "i18n"
import { queue, formFields, newKey, currentUser } from "controllers/offline_queue"
import { serverReachable } from "controllers/connection_controller"
// How long to wait for the server before keeping it here instead. Photos
// on a squawk take longer to send.
const WAIT = 10 * 1000
const WAIT_WITH_FILES = 60 * 1000
// Log Flight and Report Squawk: with no connection, the form is kept on this
// device and sent later (see offline_sync_controller). For flights, the next
// leg starts where the last saved one ended.
// leg starts where the last saved one ended. A signal so weak the server
// doesn't answer counts as none: it's kept here too, and if it got through
// after all, the server drops the copy sent later (same client_key).
export default class extends Controller {
static targets = [ "key", "notice" ]
static values = { kind: { type: String, default: "flight" }, tail: String }
@@ -23,14 +31,21 @@ export default class extends Controller {
get flight() { return this.kindValue === "flight" }
// No connection: keep it here instead of submitting.
// No connection (or the top bar is red): keep it here instead of submitting.
async submit(event) {
if (navigator.onLine) return
if (navigator.onLine && serverReachable()) return
event.preventDefault()
event.stopImmediatePropagation()
await this.save(formFields(this.element))
}
// Give up waiting after a while; the request then fails (networkFailed).
limit(event) {
const options = event.detail.fetchOptions
const files = [ ...this.element.querySelectorAll("input[type=file]") ].some((input) => input.files?.length)
options.signal = AbortSignal.any([ options.signal, AbortSignal.timeout(files ? WAIT_WITH_FILES : WAIT) ].filter(Boolean))
}
// Kept in case the request fails on the way (no signal but the browser thinks it's online).
remember() { this.pending = formFields(this.element) }
@@ -8,6 +8,9 @@ import { currentUser } from "controllers/offline_queue"
// your aircraft change. Signing out clears it.
const EVERY = 60 * 60 * 1000
// How far along it is, for the ring in the top bar (connection_controller.js).
const progress = (done, total) => document.dispatchEvent(new CustomEvent("sam:progress", { detail: { source: "prep", done, total } }))
export default class extends Controller {
static values = { aircraft: Array }
@@ -26,17 +29,26 @@ export default class extends Controller {
const forms = {}
const paths = [ "/" ]
for (const a of this.aircraftValue) {
paths.push(...a.pages, a.flight, a.squawk)
forms[a.flight] = { tail: a.tail, kind: "flight" }
forms[a.squawk] = { tail: a.tail, kind: "squawk" }
paths.push(...a.pages)
if (a.flight) { paths.push(a.flight); forms[a.flight] = { tail: a.tail, kind: "flight" } }
if (a.squawk) { paths.push(a.squawk); forms[a.squawk] = { tail: a.tail, kind: "squawk" } }
}
for (const path of paths) {
if (!navigator.onLine) return
// One at a time, after the page has settled, so it never competes with what you're doing.
await new Promise((resolve) => (window.requestIdleCallback || setTimeout)(resolve, { timeout: 2000 }))
try { await fetch(path, { credentials: "same-origin", headers: { Accept: "text/html" } }) } catch (_) { return }
}
await this.savePictures(this.aircraftValue.map((a) => a.picture).filter(Boolean))
const pictures = this.aircraftValue.flatMap((a) => a.pictures || [])
const total = paths.length + 1
try {
for (const [ index, path ] of paths.entries()) {
progress(index, total)
if (!navigator.onLine) return
// One at a time, after the page has settled, so it never competes with what you're doing.
await new Promise((resolve) => (window.requestIdleCallback || setTimeout)(resolve, { timeout: 2000 }))
try { await fetch(path, { credentials: "same-origin", headers: { Accept: "text/html" } }) } catch (_) {
document.dispatchEvent(new CustomEvent("sam:unreachable"))
return
}
}
progress(paths.length, total)
await this.savePictures(pictures)
} finally { progress(total, total) }
try {
localStorage.setItem("sam-offline-forms", JSON.stringify({ ...JSON.parse(localStorage.getItem("sam-offline-forms") || "{}"), ...forms }))
localStorage.setItem("sam-offline-prep", JSON.stringify({ signature, at: Date.now() }))
@@ -58,10 +70,11 @@ export default class extends Controller {
}
// Photo links carry an expiry, so they change with every page; the saved copy
// is filed under the upload's id instead (same rule in service-worker.js).
// is filed under the upload's id (and size) instead (same rule in service-worker.js).
function imageKey(url) {
try {
const signed = new URL(url, location.origin).pathname.match(/\/blobs\/redirect\/([^/]+?)--/)[1]
return `${location.origin}/offline-image/${JSON.parse(atob(decodeURIComponent(signed)))._rails.data}`
const [ , signed, size ] = new URL(url, location.origin).pathname.match(/\/(?:blobs|representations)\/redirect\/([^/]+?)--[^/]+\/(?:([^/]+)\/)?/)
const id = JSON.parse(atob(decodeURIComponent(signed)))._rails.data
return `${location.origin}/offline-image/${id}${size ? `/${size}` : ""}`
} catch (_) { return null }
}
@@ -1,10 +1,20 @@
import { Controller } from "@hotwired/stimulus"
import { t } from "i18n"
import { queue } from "controllers/offline_queue"
import { serverReachable } from "controllers/connection_controller"
// How long to wait for the server to take one before trying again later
// (a weak signal can leave a request hanging for minutes). Photos take longer.
const WAIT = 15 * 1000
const WAIT_WITH_FILES = 60 * 1000
const report = (name, detail) => document.dispatchEvent(new CustomEvent(name, { detail }))
// On every page: sends the flights and squawks this user saved offline once
// there's a connection, says what happened, and shows the count on the app
// icon. A rejected item stays until it's discarded.
// icon. A rejected item stays until it's discarded. Nothing is tried while
// the top bar is red; it goes again as soon as it turns back
// (connection_controller.js), signal or not.
export default class extends Controller {
static targets = [ "banner" ]
@@ -12,30 +22,37 @@ export default class extends Controller {
this.sync = this.sync.bind(this)
window.addEventListener("online", this.sync)
document.addEventListener("offline-queue:changed", this.sync)
document.addEventListener("sam:back-online", this.sync)
this.sync()
}
disconnect() {
window.removeEventListener("online", this.sync)
document.removeEventListener("offline-queue:changed", this.sync)
document.removeEventListener("sam:back-online", this.sync)
}
async sync() {
let items
try { items = await queue.mine() } catch (_) { return }
if (!items.length) { this.badge(0); return this.show("") }
if (!navigator.onLine || this.running) return this.status(items)
if (!items.length) { this.badge(0); report("sam:waiting", { count: 0 }); return this.show("") }
if (!navigator.onLine || !serverReachable() || this.running) return this.status(items)
this.running = true
const sent = []
const sending = items.filter((i) => !i.error)
try {
for (const item of items.filter((i) => !i.error)) {
for (const [ index, item ] of sending.entries()) {
report("sam:progress", { source: "send", done: index, total: sending.length })
const result = await this.send(item)
if (result === "sent") { await queue.remove(item.id); sent.push(item) }
if (result === "sent") { await queue.remove(item.id); sent.push(item); report("sam:reachable") }
else if (result === "signin") { this.show(t("offline.sign_in")); return }
else if (result === "offline") break
else if (result === "offline") { report("sam:unreachable"); break }
else { item.error = result; await queue.put(item) }
}
} finally { this.running = false }
} finally {
this.running = false
report("sam:progress", { source: "send", done: 0, total: 0 })
}
this.status(await queue.mine(), sent)
}
@@ -46,7 +63,9 @@ export default class extends Controller {
if (token) body.append("authenticity_token", token)
let response
try {
response = await fetch(item.url, { method: "POST", body, credentials: "same-origin", headers: { Accept: "text/html" } })
const files = item.fields.some(([ , value ]) => value instanceof Blob)
response = await fetch(item.url, { method: "POST", body, credentials: "same-origin", headers: { Accept: "text/html" },
signal: AbortSignal.timeout(files ? WAIT_WITH_FILES : WAIT) })
} catch (_) { return "offline" }
if ([ 502, 503, 504 ].includes(response.status)) return "offline"
if (response.url.includes("/session/new")) return "signin"
@@ -68,6 +87,7 @@ export default class extends Controller {
}
this.show(parts.join(" "), failed)
this.badge(items.length)
report("sam:waiting", { count: waiting.length })
}
// The number of unsent items on the installed app's icon.
@@ -0,0 +1,109 @@
import { Controller } from "@hotwired/stimulus"
import { t } from "i18n"
// A PDF in the document viewer. Desktop browsers show it in their own viewer,
// in a frame. Phones don't: Android shows nothing in a frame and iPhones only
// the first page, so there every page is drawn with PDF.js (public/pdfjs,
// loaded only here), each one as it scrolls into view, fetching only the
// parts of the file those pages need.
export default class extends Controller {
static targets = [ "frame", "status", "pages" ]
static values = { url: String, pdfjs: String }
// Starts over each time, as a page restored from Turbo's cache comes back
// with blank pages.
connect() {
this.pagesTarget.replaceChildren()
this.statusTarget.replaceChildren(t("pdf.loading"))
this.statusTarget.hidden = false
if (navigator.pdfViewerEnabled && !matchMedia("(pointer: coarse)").matches) return this.showFrame()
this.draw().catch((error) => this.failed(error))
}
disconnect() {
this.observer?.disconnect()
this.loading?.destroy()
}
showFrame() {
this.statusTarget.hidden = true
this.pagesTarget.append(this.frameTarget.content.cloneNode(true))
}
async draw() {
const base = this.pdfjsValue
const pdfjs = await import(`${base}pdf.min.mjs`)
pdfjs.GlobalWorkerOptions.workerSrc = `${base}pdf.worker.min.mjs`
this.loading = pdfjs.getDocument({
url: this.urlValue,
withCredentials: true,
// Only the parts needed for the pages being drawn, not the whole file
// in the background (a long manual on a phone's data plan).
disableAutoFetch: true,
disableStream: true,
wasmUrl: `${base}wasm/`,
standardFontDataUrl: `${base}standard_fonts/`,
iccUrl: `${base}iccs/`
})
const pdf = await this.loading.promise
if (!this.element.isConnected) return
// Placeholders the size of the first page keep the scroll position steady
// while pages are drawn; each takes its own shape once it's drawn.
const first = (await pdf.getPage(1)).getViewport({ scale: 1 })
// Pages are drawn as they come near the screen and let go once they're
// far from it, so a long manual doesn't use up a phone's memory.
this.observer = new IntersectionObserver((entries) => {
for (const { target, isIntersecting } of entries) {
target.dataset.near = isIntersecting
if (isIntersecting && !target.dataset.drawn) this.drawPage(pdf, target)
else if (!isIntersecting && target.dataset.drawn) { delete target.dataset.drawn; target.replaceChildren() }
}
}, { rootMargin: "200% 0px" })
for (let number = 1; number <= pdf.numPages; number++) {
const page = document.createElement("div")
page.className = "relative w-full bg-white shadow-sm ring-1 ring-slate-200"
page.style.aspectRatio = `${first.width} / ${first.height}`
page.dataset.page = number
page.setAttribute("role", "img")
page.setAttribute("aria-label", t("pdf.page", { page: number, pages: pdf.numPages }))
this.pagesTarget.append(page)
this.observer.observe(page)
}
this.statusTarget.hidden = true
}
async drawPage(pdf, holder) {
holder.dataset.drawn = "drawing"
try {
const page = await pdf.getPage(Number(holder.dataset.page))
const natural = page.getViewport({ scale: 1 })
holder.style.aspectRatio = `${natural.width} / ${natural.height}`
// Sharp on the screen and when pinched in a little.
const density = Math.min((window.devicePixelRatio || 1) * 1.25, 2.5)
const viewport = page.getViewport({ scale: (holder.clientWidth * density) / natural.width })
const canvas = document.createElement("canvas")
canvas.width = Math.floor(viewport.width)
canvas.height = Math.floor(viewport.height)
canvas.className = "block h-auto w-full"
await page.render({ canvas, canvasContext: canvas.getContext("2d"), viewport }).promise
page.cleanup()
if (holder.dataset.near !== "true") { canvas.width = canvas.height = 0; delete holder.dataset.drawn; return } // scrolled away meanwhile
holder.dataset.drawn = "drawn"
holder.replaceChildren(canvas)
} catch (_) {
holder.dataset.drawn = "failed"
holder.replaceChildren(Object.assign(document.createElement("p"), { className: "p-6 text-center text-sm text-slate-500", textContent: t("pdf.page_failed") }))
}
}
// Can't draw it here (an old browser, or not a readable PDF): the browser's own viewer is one tap away.
failed(error) {
if (!this.element.isConnected) return
console.warn("PDF viewer:", error)
this.statusTarget.hidden = false
this.statusTarget.replaceChildren(t("pdf.failed"), " ")
this.statusTarget.append(Object.assign(document.createElement("a"), { href: this.urlValue, target: "_blank", rel: "noopener", className: "link", textContent: t("pdf.open") }))
}
}
+33 -8
View File
@@ -14,18 +14,34 @@ export default class extends Controller {
this.registration = await navigator.serviceWorker.ready
const subscription = await this.registration.pushManager.getSubscription()
if (Notification.permission === "denied") return this.show(t("push.blocked"), null)
this.show(t(subscription ? "push.on" : "push.off"), !!subscription)
if (!subscription) return this.show(t("push.off"), false)
// The browser keeps its subscription even if the app never recorded it
// (or forgot it), so record it again on every visit.
const error = await this.save(subscription)
this.show(error ? t("push.not_saved", { reason: error }) : t("push.on"), true)
}
async turnOn() {
if (await Notification.requestPermission() !== "granted") return this.show(t("push.blocked"), null)
let subscription
try {
subscription = await this.registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: this.keyBytes() })
} catch (e) {
return this.show(t("push.failed", { reason: e.message || e.name }), false)
}
const error = await this.save(subscription)
this.show(error ? t("push.failed", { reason: error }) : t("push.on"), !error)
if (error) await subscription.unsubscribe()
}
// Records the subscription with the app: null, or why it couldn't.
async save(subscription) {
try {
const subscription = await this.registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: this.keyBytes() })
const response = await this.request("POST", this.urlValue, { subscription: subscription.toJSON() })
if (!response.ok) throw new Error(response.status)
this.show(t("push.on"), true)
} catch (_) {
this.show(t("push.failed"), false)
if (response.ok) return null
return (await response.json().catch(() => ({}))).error || `HTTP ${response.status}`
} catch (e) {
return e.message
}
}
@@ -38,9 +54,18 @@ export default class extends Controller {
this.show(t("push.off"), false)
}
// Sends one to each of your devices and lists which push services took it.
async sendTest() {
await this.request("POST", this.testUrlValue, {})
this.statusTarget.textContent = t("push.test_sent")
this.statusTarget.textContent = t("push.test_sending")
try {
const { devices } = await (await this.request("POST", this.testUrlValue, {})).json()
const lines = devices.length
? [ ...devices.map((d) => d.error ? t("push.test_failed", { device: d.device, reason: d.error }) : t("push.test_ok", { device: d.device })), t("push.test_hint") ]
: [ t("push.test_none") ]
this.statusTarget.textContent = lines.join("\n")
} catch (e) {
this.statusTarget.textContent = t("push.failed", { reason: e.message })
}
}
// on: true / false, or null when it can't be changed here.
+4 -4
View File
@@ -1,17 +1,17 @@
# Daily: tells owners about items that have newly become overdue or limit
# Daily: tells those who get its reminders (Role "gets reminders") about items that have newly become overdue or limit
# the aircraft (grounded, VFR only…). Each is sent once; one that's fixed and
# becomes overdue again is sent again.
class OverdueNotificationJob < ApplicationJob
queue_as :default
def perform
Aircraft.includes(roles: :user).find_each do |aircraft|
Aircraft.includes(roles: %i[user role]).find_each do |aircraft|
issues = aircraft.airworthiness.issues.select { _1.severity.in?([ Airworthiness::RED, Airworthiness::LIMITED ]) }
keys = issues.map { |i| "#{i.category}:#{i.item.class.name}:#{i.item.id}" }
fresh = issues.reject.with_index { |_, n| aircraft.notified_issue_keys.include?(keys[n]) }
owners = aircraft.roles.select { _1.role == "owner" }.map(&:user).reject(&:disabled?)
recipients = aircraft.roles.select { _1.role.can?(:receive_reminders) }.map(&:user).reject(&:disabled?)
if fresh.any?
PushNotifier.notify(owners, :overdue, path: Rails.application.routes.url_helpers.aircraft_path(aircraft), tag: "overdue-#{aircraft.id}",
PushNotifier.notify(recipients, :overdue, path: Rails.application.routes.url_helpers.aircraft_path(aircraft), tag: "overdue-#{aircraft.id}",
tail: aircraft.tail_number, items: fresh.map(&:title).to_sentence, count: fresh.size)
end
aircraft.update_column(:notified_issue_keys, keys) if keys.sort != aircraft.notified_issue_keys.sort
+19 -7
View File
@@ -4,20 +4,32 @@ class PushNotificationJob < ApplicationJob
queue_as :default
def perform(user_ids, key, path, tag, vars)
vars = vars.symbolize_keys
message = JSON.generate(title: I18n.t("push.#{key}.title", **vars), body: I18n.t("push.#{key}.body", **vars), path: path, tag: tag)
PushSubscription.where(user_id: user_ids).find_each { deliver(_1, message) }
message = self.class.message(key, path, tag, vars)
PushSubscription.where(user_id: user_ids).find_each { self.class.deliver(_1, message) }
end
private
def self.message(key, path, tag, vars = {})
vars = vars.symbolize_keys
JSON.generate(title: I18n.t("push.#{key}.title", **vars), body: I18n.t("push.#{key}.body", **vars), path: path, tag: tag)
end
def deliver(subscription, message)
# Sends to one device: nil when the push service took it, else why not.
def self.deliver(subscription, message)
WebPush.payload_send(message: message, endpoint: subscription.endpoint, p256dh: subscription.p256dh, auth: subscription.auth,
ttl: 1.day.to_i, urgency: "high",
vapid: { subject: PushKeys.subject, public_key: PushKeys.public_key, private_key: PushKeys.private_key })
rescue WebPush::ExpiredSubscription, WebPush::InvalidSubscription, WebPush::Unauthorized
nil
rescue WebPush::ExpiredSubscription, WebPush::InvalidSubscription, WebPush::Unauthorized => e
subscription.destroy
failure(subscription, e)
rescue WebPush::Error, SocketError, SystemCallError, Net::OpenTimeout, Net::ReadTimeout, OpenSSL::SSL::SSLError => e
Rails.logger.warn("[push] #{subscription.endpoint.truncate(60)}: #{e.class}: #{e.message.truncate(200)}")
failure(subscription, e)
end
def self.failure(subscription, error)
reason = "#{error.class.name.demodulize}: #{error.message.truncate(200)}"
Rails.logger.warn("[push] #{subscription.endpoint.truncate(60)}: #{reason}")
reason
end
private_class_method :failure
end
+57
View File
@@ -0,0 +1,57 @@
require "net/http"
# Posts one webhook delivery. The body is signed so the receiver can check
# it came from here and wasn't replayed:
# SAM-Signature: t=<unix time>,v1=<hex HMAC-SHA256 of "<t>.<body>" with the endpoint's secret>
# Anything but a 2xx answer is retried with growing waits, then marked failed.
class WebhookDeliveryJob < ApplicationJob
queue_as :default
ATTEMPTS = 8
class Failed < StandardError; end
retry_on Failed, wait: :polynomially_longer, attempts: ATTEMPTS do |job, error|
WebhookDelivery.find_by(id: job.arguments.first)&.update!(status: "failed", last_error: error.message.truncate(250))
end
def perform(delivery_id)
delivery = WebhookDelivery.includes(:webhook_endpoint).find_by(id: delivery_id) or return
return if delivery.status == "delivered"
endpoint = delivery.webhook_endpoint
delivery.increment!(:attempts)
response = post(endpoint, delivery)
if response.code.to_i.between?(200, 299)
delivery.update!(status: "delivered", response_status: response.code.to_i, delivered_at: Time.current, last_error: nil)
else
delivery.update!(response_status: response.code.to_i, last_error: "HTTP #{response.code}")
raise Failed, "HTTP #{response.code}"
end
rescue OutboundAddress::Blocked => e
# Pointed at an address the server won't send to: retrying won't help.
delivery.update!(status: "failed", last_error: "blocked address (#{e.reason})")
rescue Timeout::Error, SocketError, SystemCallError, OpenSSL::SSL::SSLError, EOFError, IOError => e
delivery.update!(last_error: "#{e.class.name.demodulize}: #{e.message}".truncate(250))
raise Failed, e.message
end
private
def post(endpoint, delivery)
uri = URI.parse(endpoint.url)
timestamp = Time.current.to_i
signature = OpenSSL::HMAC.hexdigest("SHA256", endpoint.secret, "#{timestamp}.#{delivery.payload}")
req = Net::HTTP::Post.new(uri)
req["Content-Type"] = "application/json"
req["User-Agent"] = "SimpleAircraftManager-Webhooks"
req["SAM-Event"] = delivery.event
req["SAM-Delivery"] = delivery.id.to_s
req["SAM-Signature"] = "t=#{timestamp},v1=#{signature}"
req.body = delivery.payload
http = Net::HTTP.new(uri.host, uri.port)
http.ipaddr = OutboundAddress.resolve!(uri.host, allow_private: true) # set up by an admin: the private network is fine
http.use_ssl = uri.scheme == "https"
http.open_timeout = 5
http.read_timeout = 10
http.start { _1.request(req) }
end
end
+1 -1
View File
@@ -1,4 +1,4 @@
# Weekly email to aircraft owners listing what's overdue or coming due
# Weekly email to those who get an aircraft's reminders (Role "gets reminders") listing what's overdue or coming due
# (inspections, ADs, components, expiring documents), deferred items, new
# ADs, and the user's own certificates that are about to expire.
# Nothing is sent when nothing needs attention, or when email isn't set up.
+9
View File
@@ -0,0 +1,9 @@
# The link of an invitation made for one email address (AccessInvitation).
class AccessInvitationMailer < ApplicationMailer
def invite(invitation, token)
@invitation = invitation
@grants = invitation.grants.includes(:aircraft, :role).sort_by { _1.aircraft.tail_number }
@url = join_url(token)
mail subject: t(".subject", who: invitation.created_by&.display_name || t(".an_administrator")), to: invitation.email
end
end
+12 -6
View File
@@ -1,8 +1,13 @@
class ReminderMailer < ApplicationMailer
# [[aircraft, issues, new AD alerts], …] for the aircraft the user owns
# that need attention.
# Aircraft where the user's role includes the permission.
def self.aircraft_where(user, permission)
Aircraft.where(id: AircraftRole.with_permission(permission).where(user_id: user.id).select(:aircraft_id)).ordered
end
# [[aircraft, issues, new AD alerts], …] for the aircraft the user gets
# reminders for (their role's "gets reminders") that need attention.
def self.items_for(user)
Aircraft.joins(:roles).where(aircraft_roles: { user_id: user.id, role: "owner" }).ordered
aircraft_where(user, :receive_reminders)
.map { [ _1, _1.airworthiness.issues, _1.ad_alerts.pending.to_a ] }.reject { _2.empty? && _3.empty? }
end
@@ -10,10 +15,11 @@ class ReminderMailer < ApplicationMailer
def self.audit_due_for?(user) = user.admin? && AuditRun.due_soon?
# Owned aircraft whose AD baseline needs a (new) DRS import: none yet, a
# year old, or a model never covered.
# Aircraft they get reminders for and manage the ADs of, whose AD baseline
# needs a (new) DRS import: none yet, a year old, or a model never covered.
def self.drs_due_for(user)
Aircraft.joins(:roles).where(aircraft_roles: { user_id: user.id, role: "owner" }).ordered
aircraft_where(user, :receive_reminders)
.where(id: AircraftRole.with_permission(:manage_ads).where(user_id: user.id).select(:aircraft_id))
.select { DrsImport.renewal_due?(_1) || DrsImport.missing_models(_1).any? }
end
+87
View File
@@ -0,0 +1,87 @@
# An invitation code: a link someone opens to create an account (or accept
# with the one they have) and get roles on aircraft. Made by administrators
# (Admin → Invitations, any aircraft) or by whoever manages an aircraft's
# people (its Access page, that aircraft). Limited by number of uses, an
# expiry, and optionally to one email address; it can be revoked. Only a
# digest of the code is kept, so the link is shown once, when it's made.
#
# New accounts are only ever made by an administrator or from an
# administrator's invitation: anyone can add an aircraft and so manage its
# people, so other invitations are for people who already have an account.
class AccessInvitation < ApplicationRecord
VALID_FOR = 14.days
belongs_to :created_by, class_name: "User", optional: true
has_many :grants, class_name: "AccessInvitationRole", dependent: :delete_all
has_many :redemptions, class_name: "AccessInvitationRedemption", dependent: :delete_all
has_many :aircraft, through: :grants
attr_reader :token
normalizes :email, with: ->(email) { email.strip.downcase.presence }
normalizes :label, :name, with: ->(text) { text.squish.presence }
validates :label, presence: true, length: { maximum: 100 }
validates :email, format: { with: URI::MailTo::EMAIL_REGEXP }, allow_nil: true
validates :max_uses, numericality: { only_integer: true, greater_than: 0, less_than_or_equal_to: 1000 }, allow_nil: true
before_validation(on: :create) do
@token = SecureRandom.urlsafe_base64(24)
self.token_digest = self.class.digest(@token)
end
scope :recent_first, -> { order(created_at: :desc) }
scope :usable, -> {
where(revoked_at: nil).where("expires_at IS NULL OR expires_at > ?", Time.current).where("max_uses IS NULL OR uses_count < max_uses")
}
# A new invitation by creator giving roles ([[aircraft, role], …]); its
# link is emailed when it's for one address and email is set up.
def self.create_for(creator, attributes, grants)
invitation = new(attributes.merge(created_by: creator))
grants.each { |aircraft, role| invitation.grants.build(aircraft: aircraft, role: role) }
if invitation.save && invitation.email && MailSettings.configured?
AccessInvitationMailer.invite(invitation, invitation.token).deliver_later
end
invitation
end
# "N12345: Mechanic. N54321: already Owner, unchanged" (from #redeem!).
def self.describe(results)
results.map { |aircraft, role, message| "#{aircraft.tail_number}: #{[ role&.name, message ].compact.join(', ')}" }.join(" ")
end
def self.digest(token) = OpenSSL::Digest::SHA256.hexdigest(token.to_s)
def self.find_by_token(token) = token.present? ? find_by(token_digest: digest(token)) : nil
def usable? = !revoked? && !expired? && !used_up?
# Whether someone without an account can make one with it (see above),
# decided when it's used: its creator must still be an administrator.
def creates_accounts? = created_by.present? && created_by.admin? && !created_by.disabled?
def for_email?(email) = self.email.nil? || self.email == email.to_s.strip.downcase
def revoked? = revoked_at.present?
def expired? = expires_at.present? && expires_at <= Time.current
def used_up? = max_uses.present? && uses_count >= max_uses
def for?(user) = for_email?(user.email_address)
def redeemed_by?(user) = redemptions.exists?(user: user)
# Gives the person the invitation's roles, as if its creator added them
# (AircraftAccess: so it can't give more than they could, then or now).
# A role they already have on an aircraft stays as it is. Returns
# [[aircraft, role or nil, message or nil], …].
def redeem!(user)
with_lock do
raise ActiveRecord::RecordInvalid, self unless usable? && for?(user)
redemptions.create!(user: user)
increment!(:uses_count)
grants.includes(:aircraft, :role).map do |grant|
if (existing = grant.aircraft.roles.find_by(user: user))
[ grant.aircraft, nil, I18n.t("models.access_invitation.already_has", role: existing.role.name) ]
elsif created_by.nil? || created_by.disabled? || !created_by.can?(:manage_people, grant.aircraft)
[ grant.aircraft, nil, I18n.t("models.access_invitation.creator_gone") ]
else
error = AircraftAccess.new(grant.aircraft, actor: created_by).add(user, grant.role)
[ grant.aircraft, (grant.role unless error), error ]
end
end
end
end
end
@@ -0,0 +1,7 @@
# Who used an invitation, and when (once per person).
class AccessInvitationRedemption < ApplicationRecord
belongs_to :access_invitation
belongs_to :user
validates :user_id, uniqueness: { scope: :access_invitation_id }
end
+8
View File
@@ -0,0 +1,8 @@
# A role an invitation gives on one aircraft.
class AccessInvitationRole < ApplicationRecord
belongs_to :access_invitation
belongs_to :aircraft
belongs_to :role
validates :aircraft_id, uniqueness: { scope: :access_invitation_id }
end
+1 -1
View File
@@ -20,7 +20,7 @@ class AirTrailConnection < ApplicationRecord
scope :active, -> { where(enabled: true) }
def client = AirTrailClient.new(base_url: base_url, api_key: api_key)
def client = AirTrailClient.new(base_url: base_url, api_key: api_key, allow_private: user&.admin?)
def ok? = status == "ok"
+20 -2
View File
@@ -1,9 +1,15 @@
class Aircraft < ApplicationRecord
STATUSES = LabelSet.new("aircraft.statuses", %w[AVAILABLE MX GROUND UNAVAILABLE])
has_one_attached :picture
# Small copies of the photo for the pages (the original can be several MB):
# made when it's uploaded; see #picture_for.
has_one_attached :picture do |picture|
picture.variant :thumb, resize_to_fill: [ 192, 192 ], preprocessed: true
picture.variant :card, resize_to_fill: [ 960, 432 ], preprocessed: true
end
has_many :roles, class_name: "AircraftRole", dependent: :destroy
has_many :invitation_grants, class_name: "AccessInvitationRole", dependent: :delete_all
has_many :users, through: :roles
has_many :notes, class_name: "AircraftNote", dependent: :destroy
has_many :events, class_name: "AircraftEvent", dependent: :delete_all
@@ -11,6 +17,7 @@ class Aircraft < ApplicationRecord
has_many :components, dependent: :destroy
has_many :squawks, dependent: :destroy
has_many :logbook_entries, dependent: :destroy
has_many :draft_batches, dependent: :destroy
has_many :logbook_imports, dependent: :destroy
has_many :document_collections, dependent: :destroy
has_many :documents, dependent: :destroy
@@ -77,10 +84,21 @@ class Aircraft < ApplicationRecord
events.create!(category: category, event_name: event_name, user: user, notes: notes)
end
# A saved photo to show (not one just rejected by validation, which has no
# address yet).
def picture_shown? = picture.attached? && picture.attachment.persisted?
# The photo at a page's size (:thumb or :card), or the original when it
# isn't a kind that can be resized. (One that can't be read is sent as the
# original too: see config/initializers/active_storage_images.rb.)
def picture_for(size)
picture.variable? ? picture.variant(size) : picture
end
private
def picture_is_image
if picture.attached? && !picture.content_type.to_s.start_with?("image/")
if picture.attached? && (!picture.content_type.to_s.start_with?("image/") || picture.blob.byte_size.zero?)
errors.add(:picture, :not_image)
end
end
+14 -4
View File
@@ -1,11 +1,21 @@
# Someone's role on an aircraft (Role), which decides what they can do there.
class AircraftRole < ApplicationRecord
ROLES = LabelSet.new("aircraft_role.roles", %w[owner pilot])
belongs_to :aircraft
belongs_to :user
belongs_to :role
validates :role, inclusion: { in: ROLES.keys }
validates :user_id, uniqueness: { scope: :aircraft_id, message: "already has a role on this aircraft" }
scope :owners, -> { where(role: "owner") }
scope :owners, -> { joins(:role).where(roles: { key: "owner" }) }
# Whose role includes a permission (Owner always does).
scope :with_permission, ->(permission) {
joins(:role).where("roles.key = 'owner' OR EXISTS (SELECT 1 FROM json_each(roles.permissions) WHERE json_each.value = ?)", permission.to_s)
}
# A Role, or a built-in role's key ("owner", "pilot").
def role=(value)
super(value.is_a?(Role) || value.nil? ? value : Role.for_key(value))
end
def owner? = role&.owner?
end
+9
View File
@@ -0,0 +1,9 @@
# A write sent with an Idempotency-Key header, and the answer it got: the
# same key again (a retry) gets the same answer instead of a second record.
class ApiIdempotencyKey < ApplicationRecord
KEEP_FOR = 24.hours
belongs_to :api_token
def self.purge_old = where(created_at: ...KEEP_FOR.ago).delete_all
end
+80
View File
@@ -0,0 +1,80 @@
# A key for the REST API (docs/api.md). Only its SHA-256 digest is kept; the
# token itself is shown once, when it's made.
#
# personal: acts as its owner, with exactly their aircraft and role.
# integration: made by an admin for another system (e.g. Redmine), limited to
# chosen aircraft and scopes. Its writes name the person they're
# for (SAM-On-Behalf-Of), so the record history always shows who.
class ApiToken < ApplicationRecord
KINDS = %w[personal integration].freeze
SCOPES = LabelSet.new("api_token.scopes", %w[read squawks:write drafts:write])
PREFIX = "sam_"
belongs_to :user
has_many :webhook_endpoints, dependent: :destroy
has_many :idempotency_keys, class_name: "ApiIdempotencyKey", dependent: :delete_all
attr_reader :token # the plain token, only right after create
normalizes :name, with: ->(n) { n.to_s.strip }
validates :name, presence: true, length: { maximum: 80 }
validates :kind, inclusion: { in: KINDS }
validate :scopes_known
validate :integration_made_by_admin, on: :create
before_validation :generate, on: :create
scope :active, -> { where(revoked_at: nil) }
scope :personal, -> { where(kind: "personal") }
scope :integration, -> { where(kind: "integration") }
def self.digest(token) = OpenSSL::Digest::SHA256.hexdigest(token.to_s)
# The token for this string, if it's in use (and its owner is too).
def self.authenticate(token)
return unless token.to_s.start_with?(PREFIX)
found = active.includes(:user).find_by(token_digest: digest(token))
found if found && (found.integration? || !found.user.disabled?)
end
def personal? = kind == "personal"
def integration? = kind == "integration"
def revoked? = revoked_at.present?
def revoke! = update!(revoked_at: Time.current)
def allows?(scope) = scopes.include?(scope.to_s)
# The aircraft this token reaches, acting for `user` (who must also have
# access, for an integration acting on someone's behalf).
def aircraft_scope(acting_user)
if personal?
user.accessible_aircraft
else
reachable = Aircraft.where(id: Array(aircraft_ids))
acting_user ? reachable.where(id: acting_user.accessible_aircraft.select(:id)) : reachable
end
end
# Last use, at most once a minute (no write per request).
def used!(ip)
return if last_used_at && last_used_at > 1.minute.ago && last_used_ip == ip
update_columns(last_used_at: Time.current, last_used_ip: ip)
end
private
def generate
@token = "#{PREFIX}#{SecureRandom.base58(40)}"
self.token_digest = self.class.digest(@token)
self.token_hint = @token.first(PREFIX.length + 6)
self.scopes = Array(scopes).map(&:to_s).compact_blank.uniq
end
def scopes_known
errors.add(:scopes, :blank) if scopes.blank?
errors.add(:scopes, :inclusion) if (Array(scopes) - SCOPES.keys).any?
end
def integration_made_by_admin
errors.add(:kind, :admins_only) if integration? && !user&.admin?
end
end
+25
View File
@@ -1,3 +1,28 @@
class ApplicationRecord < ActiveRecord::Base
primary_abstract_class
before_validation :default_blank_required_columns
validate :optional_references_exist
private
# A blank form field arrives as nil; for a column that can't be empty and has
# a default (a checkbox, a count, a position), use the default rather than
# failing in the database.
def default_blank_required_columns
self.class.columns.each do |column|
next if column.null || column.default.nil? || !self[column.name].nil?
self[column.name] = self.class.type_for_attribute(column.name).cast(column.default)
end
end
# An optional link (a parent part, a collection…) given an id that doesn't
# exist is a mistake in the form, not something to store.
def optional_references_exist
self.class.reflect_on_all_associations(:belongs_to).each do |assoc|
next if assoc.polymorphic? || !assoc.options[:optional]
next if self[assoc.foreign_key].blank? || !attribute_changed?(assoc.foreign_key)
errors.add(assoc.name, :invalid) unless public_send(assoc.name)
end
end
end
+57
View File
@@ -0,0 +1,57 @@
# The release notes (CHANGELOG.md) split into releases, so the app can show
# the running version's notes on their own and fold away older ones. The
# file stays one plain Markdown document (it reads the same on GitHub):
#
# # What's new
# intro...
# ## 2026.11.5
# ### Changes
# - ...
# ### Fixes
# - ...
class Changelog
PATH = Rails.root.join("CHANGELOG.md")
# The section headings counted in a release's one-line summary; items
# under any other heading (the first release's highlights) count as notes.
SECTIONS = { "Changes" => :changes, "Fixes" => :fixes, "For administrators" => :administrators }.freeze
Release = Data.define(:version, :markdown) do
def year = version.split(".")[0].to_i
def month = version.split(".")[1].to_i
def month_start = Date.new(year, month, 1)
def anchor = "v#{version.tr('.', '-')}"
# { changes: 4, fixes: 3 }: the top-level items under each heading.
def counts
counts = markdown.split(/^### /).drop(1).each_with_object(Hash.new(0)) do |section, tally|
heading, body = section.split("\n", 2)
tally[SECTIONS.fetch(heading.strip, :notes)] += body.to_s.scan(/^- /).size
end
(SECTIONS.values + [ :notes ]).filter_map { |key| [ key, counts[key] ] if counts[key].positive? }.to_h
end
end
def self.load = new(PATH.file? ? PATH.read : "")
attr_reader :title, :intro, :releases
def initialize(markdown)
head, *parts = markdown.split(/^## /)
@title = head[/\A# (.+)$/, 1] || "What's new"
@intro = head.sub(/\A# .+\n+/, "").strip
@releases = parts.filter_map do |part|
version, body = part.split("\n", 2)
version = version.strip
Release.new(version: version, markdown: body.to_s.strip) if version.match?(/\A\d{4}\.\d{1,2}\.\d+\z/)
end
end
def release(version) = releases.find { _1.version == version }
# Shown open: the running version and any newer (or the newest, when the
# running version has no notes, such as in development).
def open?(release, running:)
index = releases.index { _1.version == running } || 0
releases.index(release) <= index
end
end
+15 -4
View File
@@ -44,13 +44,23 @@ class Component < ApplicationRecord
OVERHAUL_ABBREVIATIONS.fetch(overhaul_kind) { engine? || propeller? ? "TSO" : I18n.t("models.component.since_service") }
end
# Its sub-components, and theirs.
def descendant_ids
child_components.flat_map { [ _1.id, *_1.descendant_ids ] }
# Its sub-components, and theirs. (Stops at a loop, should one exist.)
def descendant_ids(seen = Set[id])
child_components.flat_map do |child|
next [] unless seen.add?(child.id)
[ child.id, *child.descendant_ids(seen) ]
end
end
# Its parent, the parent's parent, and so on up.
def ancestor_ids
parent_component ? [ parent_component_id, *parent_component.ancestor_ids ] : []
ids = []
node = self
while (parent_id = node.parent_component_id) && parent_id != id && !ids.include?(parent_id)
ids << parent_id
node = Component.find_by(id: parent_id) or break
end
ids
end
def engine? = component_type&.name.to_s.match?(/engine/i)
def propeller? = component_type&.name.to_s.match?(/propell?er|\bprop\b/i)
@@ -133,6 +143,7 @@ class Component < ApplicationRecord
def parent_on_same_aircraft
return unless parent_component
errors.add(:parent_component, :itself) if parent_component_id == id && id
errors.add(:parent_component, :own_part) if id && parent_component.ancestor_ids.include?(id) # would make a loop
errors.add(:parent_component, :other_aircraft) if parent_component.aircraft_id != aircraft_id
end
end
+5 -2
View File
@@ -1,4 +1,7 @@
class Current < ActiveSupport::CurrentAttributes
attribute :session, :ip_address
delegate :user, to: :session, allow_nil: true
# api_token / api_user: an API request (see Api::V1::BaseController), which
# acts as a person without a browser session.
attribute :session, :ip_address, :api_token, :api_user
def user = api_user || session&.user
end
+63
View File
@@ -0,0 +1,63 @@
# One visit's work sent through the API as draft logbook entries: an
# unsigned entry for each logbook it touches, signed in the app like any
# other entry (by an aircraft user, or a mechanic invited to sign).
#
# What the work resolves (squawks, inspections) is held until every entry in
# the batch is signed: a draft never clears a squawk or completes an
# inspection on its own.
class DraftBatch < ApplicationRecord
include Versioned
STATUSES = %w[awaiting_signature completed withdrawn].freeze
belongs_to :aircraft
belongs_to :api_token, optional: true
belongs_to :created_by, class_name: "User", optional: true
has_many :entries, class_name: "LogbookEntry", dependent: :nullify
validates :status, inclusion: { in: STATUSES }
def awaiting? = status == "awaiting_signature"
def held_squawks = Array(held["squawks"])
def held_inspections = Array(held["inspections"])
# What signing will do, for the signer to see before they sign.
def held_effects_for(entry)
squawks = aircraft.squawks.where(id: held_squawks.select { _1["log"] == entry.log_type }.map { _1["id"] })
types = aircraft.applicable_inspection_types.where(id: held_inspections.select { _1["log"] == entry.log_type }.map { _1["id"] })
{ squawks: squawks.to_a, inspections: types.to_a }
end
# Called when one of its entries is signed: once they all are, the held
# changes are made, attributed to the person who signed last.
def entry_signed!
return unless awaiting?
with_lock do
return unless awaiting? && entries.reload.all?(&:signed?)
by_log = entries.index_by(&:log_type)
aircraft.squawks.active.where(id: held_squawks.map { _1["id"] }).find_each do |squawk|
entry = by_log[held_squawks.find { _1["id"] == squawk.id }["log"]]
squawk.resolve!(logbook_entry: entry)
aircraft.log_event!("squawk", I18n.t("flash.squawks.squawk_resolved_2"), notes: squawk.issue_reported.truncate(200))
end
aircraft.applicable_inspection_types.where(id: held_inspections.map { _1["id"] }).find_each do |type|
entry = by_log[held_inspections.find { _1["id"] == type.id }["log"]]
aircraft.inspection_records.create!(inspection_type: type, logbook_entry: entry, date: entry.date, aircraft_hours: entry.aircraft_hours_at_entry)
aircraft.log_event!("inspection", I18n.t("flash.logbook_entries.inspection_completed_logbook_entry",
name: type.name, date: I18n.l(entry.date, format: :app)))
end
update!(status: "completed", completed_at: Time.current)
end
Webhooks.publish("draft_batch.completed", aircraft: aircraft, data: ApiPresenter.draft_batch(self))
end
# Withdraws an unsigned batch: its entries are removed (kept in the record history).
def withdraw!
transaction do
raise ActiveRecord::RecordInvalid, self if entries.any?(&:signed?)
entries.each(&:destroy!)
update!(status: "withdrawn")
end
end
end
+7
View File
@@ -18,6 +18,13 @@ class EntrySignature < ApplicationRecord
validates :auth_method, inclusion: { in: AUTH_METHODS.keys + [ "imported" ] }
validates :logbook_entry_id, uniqueness: true
before_create { self.seal ||= compute_seal unless imported? }
# Integrations hear about it (webhooks); not for signatures carried over by an import.
after_create_commit do
next if imported?
entry = logbook_entry
Webhooks.publish("entry.signed", aircraft: entry.aircraft, data: ApiPresenter.logbook_entry(entry))
entry.draft_batch&.entry_signed! # a draft from the API: its held changes once all its entries are signed
end
before_update { throw :abort } # signatures are permanent (2.1.2.7)
before_destroy { throw :abort unless destroyed_by_association }
+10
View File
@@ -26,6 +26,16 @@ class FlightLog < ApplicationRecord
[ departure_location, destination_location ].compact_blank.join(" → ")
end
# The meter readings that move the aircraft's and components' hours.
METERS = %w[tach_out tach_in tach_time hobbs_out hobbs_in hobbs_time].freeze
# Its readings can be corrected only while it's the last flight logged and
# nothing has changed the hours since (an hours update, an import): only
# then is the aircraft's time just this flight's on top of the one before.
def meters_editable?
aircraft.flight_logs.maximum(:id) == id && (tach_in.nil? || tach_in == aircraft.tach_time)
end
private
# Reject files the engine data parser can't read, before they're stored.
+6 -2
View File
@@ -3,7 +3,7 @@
class HelpGuide
DIR = Rails.root.join("docs/guide")
ORDER = %w[README getting-started profile aircraft flights squawks oil-and-fuel components logbook records
inspections ads documents major-records sharing administration disclaimer changelog].freeze
inspections ads documents major-records sharing administration api disclaimer changelog].freeze
OPTIONS = {
parse: { smart: true },
render: { hardbreaks: false, unsafe: false },
@@ -27,7 +27,11 @@ class HelpGuide
# Sanitized HTML. Links to other guide pages ("records.md#mistakes") go
# through `link` (slug, anchor) -> URL, or become plain text when nil.
def self.html(page, link:, title: true)
source = title ? page.markdown : page.markdown.sub(/\A# .+\n+/, "")
render(title ? page.markdown : page.markdown.sub(/\A# .+\n+/, ""), link: link)
end
# Any Markdown from the guide (or a part of it, such as one release of the changelog).
def self.render(source, link:)
html = Commonmarker.to_html(source, options: OPTIONS, plugins: { syntax_highlighter: nil })
html = Rails::HTML5::SafeListSanitizer.new.sanitize(html, tags: TAGS, attributes: ATTRIBUTES)
html.gsub(%r{<a href="([a-z-]+|README)\.md(?:#([a-z0-9-]+))?">(.*?)</a>}m) do
+2
View File
@@ -14,6 +14,7 @@ class LogbookEntry < ApplicationRecord
belongs_to :document, optional: true
# For engine / propeller logs: which one, and its times at this entry.
belongs_to :component, optional: true
belongs_to :draft_batch, optional: true # made through the API, see DraftBatch
# Sub-components it also covers (the oil filter on the engine…).
has_many :parts, -> { includes(component: :component_type).order(:id) }, class_name: "LogbookEntryPart",
dependent: :destroy, autosave: true
@@ -33,6 +34,7 @@ class LogbookEntry < ApplicationRecord
validates :signoff_certificate_type, inclusion: { in: CERTIFICATE_TYPES.keys }, allow_blank: true
validates :inspection_result, inclusion: { in: INSPECTION_RESULTS.keys }, allow_blank: true
validates :component_hours_at_entry, :component_since_overhaul_at_entry, numericality: { greater_than_or_equal_to: 0 }, allow_nil: true
normalizes :external_ref, with: ->(r) { r.to_s.strip.first(200).presence }
normalizes :signoff_certificate_type, :inspection_result, :signoff_certificate_number, with: ->(v) { v.strip.presence }
# Fields that may still change on a signed entry: its link to a scanned
+34
View File
@@ -0,0 +1,34 @@
# What a role on an aircraft can do (Role#permissions). Grouped the way the
# app is laid out; labels and descriptions are in config/locales
# (permissions.<key>.label / .description). Seeing an aircraft's records
# needs no permission: every role can view everything on its aircraft.
module Permission
GROUPS = {
flying: %w[log_flights update_hours import_flights edit_own_flights edit_any_flight delete_flights],
squawks_and_notes: %w[report_squawks defer_squawks manage_squawks write_notes manage_notes record_consumables manage_consumables],
maintenance: %w[write_logbook sign_logbook manage_components manage_inspections manage_ads manage_major_records
manage_weight_balance manage_documents record_oil_analyses manage_oil_analyses],
data: %w[import_records export_data restore_history],
aircraft: %w[edit_aircraft delete_aircraft manage_people manage_sharing],
notifications: %w[receive_reminders]
}.freeze
ALL = GROUPS.values.flatten.freeze
# The built-in roles' permissions when first created (admins can change all
# but Owner's, which always has every permission). Pilot is what pilots
# could do before roles were configurable.
DEFAULTS = {
"pilot" => %w[log_flights update_hours edit_own_flights report_squawks defer_squawks write_notes record_consumables
record_oil_analyses sign_logbook],
"mechanic" => %w[update_hours report_squawks defer_squawks manage_squawks write_notes manage_notes record_consumables
manage_consumables write_logbook sign_logbook manage_components manage_inspections manage_ads
manage_major_records manage_weight_balance manage_documents record_oil_analyses manage_oil_analyses
receive_reminders],
"viewer" => []
}.freeze
def self.label(key) = I18n.t("permissions.#{key}.label")
def self.description(key) = I18n.t("permissions.#{key}.description")
def self.group_label(group) = I18n.t("permissions.groups.#{group}")
end
+1 -1
View File
@@ -2,7 +2,7 @@
class PushSubscription < ApplicationRecord
# The browsers' push services. The server posts to the endpoint, so only
# these hosts are accepted (not, say, an address inside the network).
PUSH_SERVICES = /\A(fcm\.googleapis\.com|updates\.push\.services\.mozilla\.com|([\w-]+\.)*push\.apple\.com|([\w-]+\.)*notify\.windows\.com)\z/
PUSH_SERVICES = /\A(([\w-]+\.)*googleapis\.com|([\w-]+\.)*google\.com|updates\.push\.services\.mozilla\.com|([\w-]+\.)*push\.apple\.com|([\w-]+\.)*notify\.windows\.com)\z/
belongs_to :user
+5 -2
View File
@@ -4,6 +4,7 @@
# editing a version breaks the chain and the nightly check reports it.
class RecordVersion < ApplicationRecord
belongs_to :user, optional: true
belongs_to :api_token, optional: true
scope :chronological, -> { order(:id) }
@@ -15,10 +16,12 @@ class RecordVersion < ApplicationRecord
def self.append!(item:, aircraft_id:, event:, changes:)
now = Time.current
payload = { "item_type" => item.class.name, "item_id" => item.id, "event" => event, "changes" => changes,
"user_id" => Current.user&.id, "at" => now.utc.iso8601(6) }.to_json
"user_id" => Current.user&.id, "at" => now.utc.iso8601(6) }
payload["api_token_id"] = Current.api_token.id if Current.api_token # made through the API (part of the hashed payload)
payload = payload.to_json
prev = where(aircraft_id: aircraft_id).order(:id).last&.chain_hash
create!(aircraft_id: aircraft_id, item_type: item.class.name, item_id: item.id, event: event, user_id: Current.user&.id,
ip_address: Current.ip_address, payload: payload, prev_hash: prev, chain_hash: digest(prev, payload), created_at: now)
ip_address: Current.ip_address, api_token_id: Current.api_token&.id, payload: payload, prev_hash: prev, chain_hash: digest(prev, payload), created_at: now)
end
def changes_hash = JSON.parse(payload)["changes"]
+41
View File
@@ -0,0 +1,41 @@
# A role someone can have on an aircraft: a name and a set of permissions
# (Permission). Installation-wide; administrators manage them (Admin → Roles).
# Four are built in (key set): Owner, which always has every permission so an
# aircraft can always be managed, and Mechanic, Pilot and Viewer, whose
# permissions can be changed. Administrators can add their own.
class Role < ApplicationRecord
BUILT_IN = %w[owner mechanic pilot viewer].freeze
has_many :aircraft_roles, dependent: :restrict_with_error
has_many :invitation_grants, class_name: "AccessInvitationRole", dependent: :delete_all
normalizes :name, with: ->(name) { name.squish }
validates :name, presence: true, uniqueness: { case_sensitive: false }, length: { maximum: 40 }
validates :description, length: { maximum: 200 }
validates :key, inclusion: { in: BUILT_IN }, uniqueness: true, allow_nil: true
before_validation { self.permissions = Array(permissions).map(&:to_s) & Permission::ALL }
before_destroy { throw :abort if built_in? }
scope :ordered, -> { order(Arel.sql("CASE WHEN key IS NULL THEN 1 ELSE 0 END"), :position, :name) }
# The built-in roles, created when first needed (a new installation, tests).
def self.ensure_built_in!
BUILT_IN.each_with_index do |key, i|
find_or_create_by!(key: key) do |role|
role.name = I18n.t("roles.#{key}.name")
role.description = I18n.t("roles.#{key}.description")
role.permissions = Permission::DEFAULTS.fetch(key, [])
role.position = i
end
end
end
def self.for_key(key) = find_by(key: key.to_s) || (ensure_built_in! && find_by!(key: key.to_s))
def self.owner = for_key("owner")
def built_in? = key.present?
def owner? = key == "owner"
def permissions = owner? ? Permission::ALL : super
def can?(permission) = permissions.include?(permission.to_s)
end
+27
View File
@@ -0,0 +1,27 @@
# The application secret key signs the sign-in cookie and protects stored
# secrets (two-factor keys, API keys), so anyone who can guess it can sign in
# as anyone. A placeholder or short key stops the app from starting; one
# shorter than what `bin/rails secret` makes is reported by sam:doctor.
module SecretKeyCheck
MIN = 32 # below this, refuse to start
RECOMMENDED = 64 # below this, warn
PLACEHOLDERS = %w[change-me changeme change_me secret password your-secret-key replace-me example].freeze
module_function
# :ok, :weak or :unsafe
def strength(key = ENV["SECRET_KEY_BASE"].to_s)
return :unsafe if PLACEHOLDERS.include?(key.strip.downcase) || key.length < MIN || key.chars.uniq.size < 10
key.length < RECOMMENDED ? :weak : :ok
end
def verify!(key = ENV["SECRET_KEY_BASE"].to_s)
case strength(key)
when :unsafe
abort "SECRET_KEY_BASE is a placeholder or too short (#{key.length} characters). " \
"Set it to the output of `bin/rails secret` (128 random characters) and start again."
when :weak
Rails.logger.warn("[security] SECRET_KEY_BASE is only #{key.length} characters; `bin/rails secret` makes 128.")
end
end
end
+4
View File
@@ -10,6 +10,9 @@ class Setting < ApplicationRecord
"backups_kept" => { default: 14, in: 1..365 },
"offsite_backups_kept" => { default: 30, in: 1..365 },
"documents_claude_text" => { default: 0, in: 0..1 },
# Who can add aircraft (and so become an Owner, who invites people): 0
# administrators only, 1 everyone.
"anyone_adds_aircraft" => { default: 0, in: 0..1 },
"logbook_templates_seeded" => { default: 0, in: 0..1 } # internal flag
}.freeze
LABELS = LabelSet.new("setting.keys", INTEGERS.keys)
@@ -20,6 +23,7 @@ class Setting < ApplicationRecord
class << self
def max_upload_mb = integer("max_upload_mb")
def max_upload_bytes = max_upload_mb.megabytes
def anyone_adds_aircraft? = integer("anyone_adds_aircraft") == 1
def integer(key)
definition = INTEGERS.fetch(key)
+33
View File
@@ -0,0 +1,33 @@
# Until the first account exists, whoever reaches the server could create the
# admin account. The setup page asks for this one-time code, which is only in
# the server's log, so only whoever runs the server can finish setup.
module SetupCode
ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789".chars.freeze # no look-alikes (0/O, 1/I/L)
module_function
# (Each parallel test process has its own.)
def file = Rails.env.test? ? Rails.root.join("tmp", "setup_code-#{Process.pid}") : Rails.root.join("storage", "setup_code")
# The code, made the first time it's needed and kept until setup is done.
def current
return file.read.strip if file.exist?
code = Array.new(8) { ALPHABET[SecureRandom.random_number(ALPHABET.size)] }.join.insert(4, "-")
file.dirname.mkpath
File.write(file, code, perm: 0o600)
code
end
def announce
Rails.logger.warn("Setup code: #{current} (enter it on the setup page to create the admin account)")
end
def matches?(given)
normalize = ->(s) { s.to_s.upcase.gsub(/[^A-Z0-9]/, "") }
ActiveSupport::SecurityUtils.secure_compare(normalize.(given), normalize.(current))
end
def clear
file.delete if file.exist?
end
end
+8
View File
@@ -22,4 +22,12 @@ class SigningInvitation < ApplicationRecord
def self.find_usable(token) = where(token_digest: digest(token), used_at: nil).where("expires_at > ?", Time.current).first
def aircraft = logbook_entry.aircraft
# Whether the mechanic can make an account for the invited address with it:
# when it's from an Owner of the aircraft or an administrator (still, when
# it's used). Who can become an Owner is up to the administrator (Admin →
# Settings, who can add aircraft); others' invitations need an account.
def creates_account?
invited_by.present? && !invited_by.disabled? && (invited_by.admin? || invited_by.role_for(aircraft)&.owner?) || false
end
end
Loaded 100 of 291 files, more files were not shown because too many files have changed in this diff. Show more