Skip to content

Data model

This page describes everything Aperture stores: the directories on disk, the SQLite database with its migrations and tables, and what the built-in configuration backup does and does not include. Use it to find a file, read the database safely, plan a full backup, or write a migration.

Aperture keeps its state in two directories, set in /etc/aperture/aperture.env and read by config.Load in internal/config/config.go.

Variable Installed value Default when unset (development) Holds
APERTURE_DATA_DIR /var/lib/aperture/data ./data Database, secrets, caches, exports, extensions
APERTURE_RECORDINGS_DIR /var/lib/aperture/recordings ./recordings Recorded segments and event thumbnails

config.Load creates both directories, plus frame-cache, spool, rcache and ext under the data directory, if they are missing. On an installed system systemd-tmpfiles creates them first, from deploy/tmpfiles/aperture.conf.

An installed system looks like this:

/var/lib/aperture/ 0755 root
├── go2rtc.yaml 0600 aperture-go2rtc go2rtc's own config, rewritten by go2rtc
├── ai/ object-recognition runtimes and models
│ ├── packs/<pack>/<artifact>/ unpacked ONNX Runtime libraries + .sha256 marker
│ ├── models/<model>.onnx catalogue models + <model>.onnx.sha256 marker
│ ├── custom/<id>.onnx models you uploaded, with <id>.json and optional <id>.classes.txt
│ └── tmp/ partial downloads
├── data/ 0711 root APERTURE_DATA_DIR
│ ├── aperture.db 0600 SQLite database
│ ├── aperture.db-wal 0600 write-ahead log
│ ├── aperture.db-shm 0600 WAL shared-memory index
│ ├── secrets.json 0600 signing keys and the at-rest encryption key
│ ├── cli.token 0600 local admin token for nvrctl
│ ├── exports/ 0700 finished exports: <job>.mp4 or <job>.zip
│ ├── frame-cache/<camera_id>/ 0700 hover-scrub preview frames: <unix-ms>.jpg
│ ├── spool/<camera_id>/ 0700 segments waiting to upload to SMB/SFTP
│ ├── rcache/ 0700 temporary local copies of network segments
│ ├── homekit/ 0700 HomeKit pairing state
│ └── ext/ 0711 installed extensions
│ ├── <ext-id>/ one extension's files, .import-map.json, .deno/ cache
│ ├── <ext-id>.prev/ the previous version, kept for rollback
│ └── .staging/<ext-id>/ an install or update being prepared
└── recordings/ 0755 root APERTURE_RECORDINGS_DIR
├── .aperture-reservation hard-reservation balloon file (only when an allocation is set)
└── <camera_id>/
├── <unix-seconds>.ts one 10-second MPEG-TS segment
└── events/<event_id>.jpg event thumbnails
Path Written by Contents and cleanup
aperture.db, -wal, -shm store.Open The database (see below). store.Open sets all three to 0600 after migrating.
secrets.json config.loadSecrets Generated on first start (see Secrets).
cli.token config.loadSecrets A plain copy of cli_token, so nvrctl can read it locally.
exports/ internal/export Export outputs, and the concat lists ffmpeg reads while rendering. Manager.cleanupAt runs hourly and deletes finished jobs older than export.TTL (24 hours), row and files together, except a clip that a live share link still points at (Store.ShareHolds); it stays until its last link expires, runs out of views or is revoked. The delete is conditional (DeleteExportUnlessShared), so a link created meanwhile still keeps its clip, and links to clips that are gone are removed (DeleteDanglingShares).
frame-cache/<camera_id>/ GET /api/v1/cameras/{id}/frame handler in internal/api/recordings_handlers.go JPEG frames for hover scrubbing, named by the requested time rounded to the second. A loop in cmd/nvrd/main.go deletes files older than 2 hours every 30 minutes.
spool/<camera_id>/ the recorder’s ffmpeg Segments for cameras that record to an SMB or SFTP destination. The uploader in internal/record/recorder.go moves each finished file to the share and indexes it. If a share stays down, enforceSpoolCap drops the oldest files once a camera’s spool passes 4 GiB.
rcache/ localizeSegment A network segment downloaded for a tool that needs a local file (scrub frames, exports). Removed when the caller is done.
homekit/ internal/homekit The HomeKit accessory store (hap.NewFsStore).
ext/ extension install and manager handlers in internal/api Extension files. They are never stored in the database; the extensions table holds the metadata.

Data root and ext/ are 0711: traversable but not listable, so an extension process (running as its own uid, allocated from 65600 upwards) can reach its own ext/<ext-id>/ without listing its neighbours. aperture-harden re-applies these modes and the 0600 file modes on every start.

Everything under the data directory counts toward the default location’s storage allocation, because the janitor (Janitor.apertureAppBytes in internal/retention/janitor.go) adds dirBytes(DataDir) and the per-camera events/ folders to the footage total. That is why the object-recognition files live in ai/ beside the data directory and not inside it: cmd/nvrd/main.go passes filepath.Join(filepath.Dir(cfg.DataDir), "ai") to ai.NewManager.

secrets.json is a small JSON object. config.loadSecrets reads it, fills in anything missing with fresh random values and writes it back with mode 0600.

Field Used for Override
jwt_secret Signs short-lived JWTs, such as the pending second-factor step at sign-in APERTURE_JWT_SECRET
stream_secret Signs stream tokens for live video and the signed thumbnail links in notifications APERTURE_STREAM_SECRET
cli_token The local admin bearer token nvrctl uses; also written to cli.token none
enc_key 32-byte AES-256-GCM key (hex) for values encrypted at rest none

enc_key is used by secret.Cipher in internal/secret/cipher.go. The stored form is base64(nonce || ciphertext || tag). It encrypts storage-destination credentials (storage_locations.secret_enc), per-camera ONVIF passwords (cameras.onvif_pass_enc) and the Eufy account password (the eufy_pass_enc setting).

The recorder writes each camera’s footage to <root>/<camera_id>/<unix-seconds>.ts, where the name is the segment’s start time (ffmpeg’s -strftime 1 with %s.ts). <root> is:

  • the recordings directory, or the path in the recordings_path setting if you changed it in the app (Store.RecordingsPathOverride), for cameras on the default destination;
  • the destination’s own path for a local destination: <path>/<camera_id>/<unix-seconds>.ts;
  • the spool for SMB and SFTP destinations; on the share the file ends up at <camera_id>/<unix-seconds>.ts relative to the share’s root.

Mirror copies use the same names. A local mirror copy is written as <name>.ts.part and renamed when complete, so a half-written file is never indexed (internal/record/mirror.go).

Motion, audio and package events save their thumbnail to APERTURE_RECORDINGS_DIR/<camera_id>/events/<event_id>.jpg. The .aperture-reservation file is the balloon that holds a hard reservation (internal/reserve/reserve.go); the janitor resizes it on every pass so footage plus app data plus balloon equals the allocation, and removes it when no allocation is set. See Storage for the reservation wizard and Recording pipeline for how segments are written and pruned.

Deleting a camera removes its rows through foreign-key cascades and its files through purgeCameraFiles: every segment (local or remote) and every mirror copy of it (best effort), every event thumbnail, and the camera’s folders in the recordings directory, the spool and the frame cache. Delete footage and Playback’s Remove footage go through the same per-copy delete (internal/api/footage_delete.go): mirror copies first (file, then its segment_copies row), then the canonical file, and the segments row only once every file is gone.

go2rtc reads /var/lib/aperture/go2rtc.yaml and writes it back when nvrd adds or removes streams through its API, so the file ends up holding camera RTSP URLs with their passwords in clear text. It is owned by aperture-go2rtc, mode 0600, and sits outside the data directory. The file is derived state: nvrd calls stream.Manager.Sync at start and every 60 seconds, which registers a cam_<id> stream for every camera in the database and deletes cam_* streams that no longer have one. See Live streaming.

Property Value Where
File <data>/aperture.db Config.DBPath
Driver modernc.org/sqlite, a pure-Go SQLite (no cgo) internal/store/store.go
Opened by nvrd only cmd/nvrd/main.go calls store.Open
Connection pool one connection (db.SetMaxOpenConns(1)) store.Open
Schema embedded migrations/*.sql, applied at start internal/store/migrate.go

store.Open runs these pragmas before migrating:

Pragma Effect
journal_mode=WAL Write-ahead logging. Commits go to aperture.db-wal first and are checkpointed into aperture.db later.
busy_timeout=10000 A statement waits up to 10 seconds for a lock instead of failing with SQLITE_BUSY.
foreign_keys=ON REFERENCES … ON DELETE CASCADE clauses are enforced.
synchronous=NORMAL The usual setting with WAL: fewer fsyncs; a power cut can lose the last commits but does not corrupt the file.

Because the pool holds a single connection, every query nvrd makes runs on it in turn. There is one writer by construction, and a long transaction delays everything else, reads included. This is why migrations and backfills must be fast (see Writing a migration). Nothing in the code runs VACUUM or a manual WAL checkpoint.

nvrctl never opens the database. It talks to the API with the bearer token from cli.token (see nvrctl).

  • Most primary keys are store.NewID(): 16 random bytes as 32 hex characters. Camera ids are of this form; the cam_<id> stream names and the per-camera folders use them. There is no stored slug; the live WebSocket route derives one from the camera name at request time.
  • events.seq is strictly increasing (not gapless). It is the stable cursor for /api/v1/events and the Last-Event-ID of the change feed. New values come from an in-process counter that store.Open seeds from MAX(seq).
  • event_objects.id works the same way, seeded from MAX(id), so every detection keeps a stable id.
  • audit_log.id and notify_log.id are SQLite AUTOINCREMENT integers.

Footage and detection times (segments.start_ts/end_ts, events.*_ts, event_objects.ts, object_tracks.ts, segment_leases.*) are Unix milliseconds. created_at and updated_at are Unix seconds in the original tables (users, cameras, sessions, storage_locations, camera_groups, export_jobs), but several newer tables store milliseconds (api_tokens, automations, webhooks, extensions, segment_copies). audit_log.ts and weather_samples.ts are seconds. Check the column comment in the migration or the insert in internal/store before comparing times across tables.

With foreign_keys=ON, deleting a row removes its children:

Parent Children deleted with it
cameras segments, events, schedules, user_camera_acl, camera_destinations
segments segment_copies
events event_objects, object_tracks
users user_camera_acl, user_preferences, api_tokens, sessions, trusted_devices
webhooks webhook_deliveries

The cascades remove rows, not files. Code that deletes footage removes the file first and deletes the row only when that worked, so a failed delete is retried on the next pass instead of leaving an untracked file behind; see Recording pipeline for the janitor’s rules.

The installer does not install the sqlite3 shell. If you install it to look around, open the file read-only so you cannot take the write lock from nvrd:

Terminal window
sudo sqlite3 -readonly /var/lib/aperture/data/aperture.db '.tables'
sudo sqlite3 -readonly /var/lib/aperture/data/aperture.db 'SELECT MAX(version) FROM schema_migrations'

Migrations live in internal/store/migrations as NNNN_name.sql and are embedded into the binary with //go:embed migrations/*.sql. At every start, Store.migrate:

  1. creates schema_migrations (version, applied_at) if needed;
  2. reads MAX(version);
  3. sorts the embedded files by their numeric prefix and, for each one with a higher number, runs the whole file and inserts its version row in one transaction.

A failed migration rolls back its transaction; store.Open returns the error and nvrd exits. There are no down migrations. An older binary started on a newer database applies nothing and runs against the extra tables and columns. That works because migrations add tables, columns and indexes (and fill new columns) but do not drop or rename anything; the one exception, 0002, dropped a placeholder table nothing had written to. ImportConfig refuses a backup made on a newer schema than the running server.

The rules from internal/store/migrations/README.md:

  • One migration per change. Take the next free number; never edit or renumber a migration that has shipped.
  • Stay additive. ALTER TABLE … ADD COLUMN … NOT NULL DEFAULT <constant> is a metadata-only change in SQLite and does not rewrite the table. New tables and indexes on small tables are cheap.
  • Backfills run at start while holding the only connection, so they block the recorder’s writes. Write them as a single pass (a window function, or UPDATE … FROM over an ordered set), never a correlated subquery per row: the 0022 backfill uses one and is quadratic in the number of events.
  • Time any backfill that touches segments, the largest table, on a copy of a real database before you ship it.
# File What it does
0001 init users, cameras, user_camera_acl, segments, events, schedules, settings and a placeholder audit_log
0002 wave1_rails Replaces the unused placeholder with the hash-chained audit_log; adds user_preferences
0003 exports_shares export_jobs and shares (share links)
0004 notifications notify_channels, notify_rules, push_subscriptions, notify_log
0005 motion_tuning Per-camera preroll_ms, postroll_ms, cooldown_ms (5000 each) and min_duration_ms
0006 user_security must_change_password and TOTP columns on users
0007 webauthn webauthn_credentials (passkeys)
0008 context weather_samples time series; the site profile and weather config live in settings
0009 rule_conditions notify_rules.conditions (time of day, precipitation)
0010 detection events.top_label, events.object_summary and the event_objects table
0011 integrations api_tokens, webhooks, webhook_deliveries
0012 automations automations
0013 export_multicam export_jobs.cameras and export_jobs.mode (single, zip, composite)
0014 camera_detection cameras.motion_detection and the per-camera detect_method override
0015 camera_temp_sensor cameras.temp_sensor, a Home Assistant entity for the overlay
0016 export_timelapse export_jobs.speed
0017 event_motion_cells events.motion_cells, the active cells of a 32 by 18 grid, for grid search
0018 camera_audio cameras.audio_detection and cameras.audio_threshold
0019 camera_groups camera_groups
0020 storage_locations storage_locations; location_id on cameras and segments
0021 api_token_scopes api_tokens.scopes and api_tokens.camera_grants
0022 event_seq events.seq with a backfill and a unique index
0023 event_object_id event_objects.id, backfilled from rowid
0024 idempotency_keys idempotency_keys
0025 segment_leases segment_leases, replacing the unused segments.locked flag
0026 extensions extensions
0027 api_token_ext api_tokens.ext_id, so an extension’s tokens can be revoked together
0028 ext_manager extensions.pinned and extensions.modified
0029 ext_kv ext_kv, per-extension key/value storage
0030 mirrors camera_destinations (seeded from cameras.location_id) and segment_copies
0031 camera_onvif onvif_enabled, onvif_port, onvif_user, onvif_pass_enc on cameras
0032 camera_vendor cameras.vendor, an explicit vendor marking for vendor-specific controls
0033 sessions Server-side sessions and trusted_devices
0034 record_quality record_height, record_fps, record_kbps on cameras
0035 ha_hidden cameras.ha_hidden, to keep a camera out of Home Assistant and HomeKit
0036 object_tracks object_tracks, per-object boxes over an event’s lifetime

Column lists below show the columns that matter; the migrations hold the full definitions.

Table Key columns Notes
cameras id, name, rtsp_main_url, rtsp_sub_url, enabled, record_mode, retention_days, location_id, record_height, record_fps, record_kbps, sort_order record_mode is never, motion, continuous or scheduled. retention_days defaults to 7. location_id is the primary destination ("" = default). The three record_* columns are 0 for “as the camera sends it”, which keeps stream copy.
motion_detection, motion_threshold, motion_zones_json, preroll_ms, postroll_ms, cooldown_ms, min_duration_ms, audio_detection, audio_threshold, detect_method Detection settings. motion_threshold defaults to 0.02. detect_method is "" (use the global setting), off, bridge (external server) or local; the older value onnx is accepted as local.
onvif_enabled, onvif_port, onvif_user, onvif_pass_enc, vendor, temp_sensor, ha_hidden Integrations. onvif_pass_enc is encrypted with enc_key.
schedules camera_id, weekday (0 = Sunday), start_min, end_min, mode Time windows for scheduled cameras, in minutes from midnight.
camera_groups name, cameras_json, sort_order Named camera sets. The built-in all-cameras group is virtual and not stored.
storage_locations id, name, type, config_json, secret_enc, allocation_bytes, enabled type is local, smb or sftp. config_json holds only non-secret fields; the password or key is in secret_enc. allocation_bytes is a hard reservation for local destinations and a soft cap for network ones. The default destination (id "") is not stored: it is the recordings directory with the storage_cap_bytes setting.
camera_destinations camera_id, location_id, retention_days Every destination a camera writes to, the primary included. Every row other than the primary is a mirror. retention_days 0 inherits the camera’s value.
segments id, camera_id, location_id, path, start_ts, end_ts, duration_ms, size_bytes One row per recorded file, indexed on (camera_id, start_ts). path is absolute for the default and local destinations, and <camera_id>/<unix-seconds>.ts relative to the share for SMB and SFTP.
segment_copies segment_id, location_id, path, size_bytes, created_at Extra physical copies made by mirroring. When retention removes the canonical file while a mirror must keep it, Store.PromoteCopy moves the copy into the segments row.
segment_leases camera_id, from_ts, to_ts, holder, expires_at A time range retention must not delete, for example export:<job id> while an export renders. Expired leases are ignored and swept.
export_jobs camera_id, cameras, mode, from_ts, to_ts, speed, status, progress, output_path Export queue and results. Removed with their files after 24 hours.

Two segments columns from 0001 are inert: has_motion and locked are never set by current code. Footage protection uses segment_leases, and motion-mode pruning compares segments with events (Store.NonEventSegments).

scanSegment in internal/store/segments.go applies clampSegmentDuration to every row it reads: a duration above 60 seconds (an MPEG-TS timestamp wrap can make ffprobe report hours) is replaced by the wall-clock span from the file names, or the nominal 10 seconds. The stored row is not changed.

Table Key columns Notes
events id, camera_id, type, start_ts, end_ts, seq, score, thumb_path, snapshot_path, top_label, object_summary, motion_cells, reviewed, saved type is motion, audio or package. end_ts is NULL while the event runs; FinalizeOrphanedEvents closes events a previous run left open, at start_ts + 10000. top_label and object_summary (for example person, car) are filled by object recognition.
event_objects id, event_id, label, confidence, bbox_x, bbox_y, bbox_w, bbox_h, ts Detections attached to an event; boxes are normalized 0 to 1. SaveEventDetections replaces an event’s whole set and its summary columns in one transaction.
object_tracks event_id, camera_id, obj, label, confidence, x, y, w, h, ts Where each recognized object was, a few times a second, while its event ran. obj is the live tracker’s object id. Playback uses it to draw boxes that follow the object.
weather_samples ts, temp_c, humidity_pct, wind_speed_ms, precip_mm, condition_code, source, … One row per weather poll; looked up as the nearest sample at or before a time.

Retention removes segments, not events: event rows and thumbnails stay until footage is removed with POST /api/v1/system/purge or DELETE /api/v1/cameras/{id}/recordings (the remove action in Playback), or until the camera is deleted. See Detection pipeline for how rows get here.

Table Key columns Notes
users id, email (unique), name, password_hash, role, oidc_sub, disabled, must_change_password, totp_secret, totp_enabled, totp_recovery role is admin or viewer. password_hash is bcrypt, and NULL for accounts that only sign in through OIDC.
user_camera_acl user_id, camera_id The cameras a viewer may see. Admins ignore it; a viewer with no rows sees no cameras.
user_preferences user_id, prefs Per-user UI preferences as JSON.
sessions id, user_id, token_hash, device_id, expires_at, max_expires_at, ip, ua Browser sessions. The cookie carries a random token; only its SHA-256 is stored, so a copy of the database cannot be replayed as a login. expires_at slides forward with use; max_expires_at is the absolute cap.
trusted_devices id, user_id, token_hash, expires_at Browsers that completed a second factor and may skip it next time. They survive sign-out.
webauthn_credentials user_id, name, cred_id, cred_json, last_used Passkeys.
api_tokens id, user_id, name, token_hash, prefix, scopes, camera_grants, ext_id, expires_at, last_used A token is apt_ plus 48 hex characters; only its SHA-256 is stored, with the first 12 characters as prefix for display. scopes and camera_grants are comma-separated. A non-empty ext_id marks a token minted for an extension backend. expires_at 0 means never. See Scopes.
shares token_hash, kind, target, expires_at, password_hash, max_views, views, revoked Share links. kind is clip.
audit_log id, ts, actor_id, actor_email, action, target, detail, ip, ua, prev_hash, hash The activity log, hash-chained (below).

Store.AppendAudit in internal/store/audit.go computes each row’s hash as the hex SHA-256 of prev_hash|ts|actor_id|action|target|detail, with prev_hash taken from the previous row. Store.VerifyAuditChain walks the table in id order and returns the first row whose hash does not match; the API exposes it as GET /api/v1/system/audit/verify. actor_email, ip and ua are stored but are not part of the hash.

Table Key columns Notes
notify_channels user_id, type, name, config, enabled type is webpush, ntfy, telegram, discord, webhook or email; config is JSON.
notify_rules user_id, cameras, event_types, channels, quiet_start, quiet_end, cooldown_sec, conditions JSON arrays; an empty camera or type list means all. cooldown_sec defaults to 120; quiet hours are minutes from midnight, -1 when off.
push_subscriptions user_id, endpoint, p256dh, auth Web-push endpoints of each browser.
notify_log rule_id, event_key, ts Delivery log used for cooldowns.
webhooks name, url, events, secret, enabled Outbound event webhooks; secret is the HMAC-SHA256 signing key.
webhook_deliveries webhook_id, event, status, code, detail, ts The 50 most recent deliveries per webhook.
automations name, enabled, trigger, conditions, actions, cooldown_ms, last_fired Rules; trigger, conditions and actions are JSON. See Automations.
Table Key columns Notes
extensions id, name, version, source, update_url, manifest_json, scopes, camera_grants, enabled, ext_uid, pinned, modified, installed_by One row per installed extension. id is the manifest’s reverse-DNS id; source is store or sideload; ext_uid is the non-root uid its backend runs as. modified is set when you edit its files in the app.
ext_kv ext_id, key, value, updated_at Private storage for extensions with the storage permission. Limits in internal/store/ext_kv.go: 1000 rows, 1 MiB of values and 64 KiB per value per extension. Rows are deleted on uninstall.

See Extensions and Extension security.

Table Key columns Notes
settings key, value A flat key/value store for everything configured in the app. Larger settings are JSON values.
idempotency_keys key, method, path_hash, status_code, response, expires_at Stored responses for requests sent with an Idempotency-Key header, kept 24 hours (idempotencyTTL in internal/api/idempotency.go).
schema_migrations version, applied_at One row per applied migration.

A few settings keys, to help you find your way:

Key Holds
site_name The site name shown in the app; Home NVR when unset
recordings_path Override of the default recordings directory for new footage
storage_cap_bytes Allocation of the default destination
record_quality The global recording-quality preference; low records each camera’s sub stream when it has one
detection Object-recognition configuration (JSON, internal/detect)
site_profile, weather_config Location and weather source (JSON)
hardware_profile The hardware profile used for capacity estimates
ha_broker, ha_user, ha_pass, ha_prefix, ha_enabled Home Assistant MQTT connection
oidc_issuer, oidc_client_id, oidc_client_secret, oidc_enabled Single sign-on
vapid_public, vapid_private Web-push key pair, generated by notify.New when missing
onvif.enabled, homekit.enabled Interop toggles, seeded once from the environment
ext.enabled, api.v1.frozen_at The extension gate and when /api/v1 was frozen
eufy_pass_enc The Eufy account password, encrypted with enc_key

Settings › System, under Maintenance, has Download backup and Restore…. Both call internal/store/backup.go:

Route Access
Download GET /api/v1/system/backup Admin, session or CLI token only; API tokens are refused
Restore POST /api/v1/system/restore, multipart field backup, up to 256 MiB Same

Store.ExportConfig writes a JSON file named aperture-backup-<UTC time>.json:

{
"version": "<app version>",
"schemaVersion": 36,
"timestamp": 1767225600,
"tables": {
"users": [ { "id": "…", "email": "…", "password_hash": "…" } ],
"cameras": [ { "id": "…", "rtsp_main_url": "…" } ]
}
}

Each table is dumped as SELECT *, one JSON object per row. The tables are exactly the configTables list:

Included Not included
users, storage_locations, cameras, camera_destinations, settings, schedules, notify_channels, notify_rules, user_preferences, user_camera_acl, webauthn_credentials, camera_groups, automations, webhooks Everything else, among them api_tokens, sessions, trusted_devices, extensions, ext_kv, webhook_deliveries, and all footage and event tables (segments, segment_copies, segment_leases, events, event_objects, object_tracks, weather_samples, audit_log, notify_log, export_jobs, shares, push_subscriptions, idempotency_keys)

No files are included: not secrets.json, not the recordings, not extension files, not the ai/ folder.

extensions and ext_kv are left out on purpose. An extension is its files under data/ext/<id>/ plus its row, and the files are owned by the extension’s own uid (ext_uid). A row restored without its files is a broken install, and a row restored onto files owned by another uid could leave two extensions sharing one uid, which undoes the first layer of the sandbox. A restore therefore leaves the installed extensions as they are. At boot, StartEnabledExtensions still refuses to start an enabled extension whose files are missing, which covers a state backup of aperture.db put back without data/ext/.

Store.ImportConfig(backup, RestoreOptions) checks schemaVersion first and refuses a backup from a newer schema. It parses every table before it touches the database, then takes a dedicated connection and turns foreign_keys off on it (otherwise deleting cameras would cascade into every segment and event row). In one transaction it:

  1. deletes, children-first, only the included tables the file contains. A table the file lacks, such as storage_locations in a backup from before it was included, is left as it is rather than emptied;
  2. inserts the backup’s rows parents-first. Column names come from the uploaded file and are spliced into the INSERT, so each one is checked against pragma_table_info first, and an unknown column fails the whole restore;
  3. for storage_locations, gives each restored local location this server’s allocation_bytes for that id, or 0 if it is new here (a local allocation sizes the .aperture-reservation file on a real disk), and puts back any of this server’s locations the backup dropped that still have segments or segment_copies rows, or a local allocation;
  4. clears every restored ciphertext that RestoreOptions.CanDecrypt cannot open: storage_locations.secret_enc, cameras.onvif_pass_enc and the eufy_pass_enc setting. The API passes the server’s enc_key cipher; without one, nothing is cleared;
  5. deletes camera_destinations rows whose camera is not in the restored cameras;
  6. commits once.

Rows of tables that are not in the list are left as they are. handleRestore then drops the cached storage backends of every location before and after the restore, and replies with what needs attention:

{
"ok": true,
"tables": 14,
"clearedCredentials": [ { "kind": "storage", "id": "…", "name": "NAS" } ],
"keptLocations": [],
"reservationsNotRestored": [ { "kind": "storage", "id": "…", "name": "Disk 2" } ]
}

kind is storage, onvif or setting. Every download and restore is written to the audit log (system.backup, system.restore).

To fetch a backup from a script on the server itself, use the CLI token (8971 is the installed default port; use the one in APERTURE_HTTP_ADDR):

Terminal window
sudo sh -c 'curl -fsS -H "Authorization: Bearer $(cat /var/lib/aperture/data/cli.token)" http://127.0.0.1:8971/api/v1/system/backup' > aperture-backup.json
chmod 600 aperture-backup.json

The configuration backup is not a full backup. To keep everything, copy the state directories with the service stopped, because recent commits may still be in aperture.db-wal:

  1. sudo systemctl stop aperture
  2. Copy /var/lib/aperture/data (the database with its -wal and -shm files, secrets.json, cli.token, homekit/, ext/).
  3. Copy /var/lib/aperture/recordings and any local destination folders if you want the footage.
  4. Optionally copy /var/lib/aperture/ai; models and runtimes can be downloaded again from the app.
  5. sudo systemctl start aperture

go2rtc.yaml does not need to be kept: nvrd registers every camera’s stream again within a minute of starting. The caches (frame-cache/, rcache/) and finished exports can be left out. Local footage rows hold absolute paths, so restore the recordings to the same location, or the rows point at files that do not exist. The Backup page covers the procedure step by step.

Related: How it works, Recording pipeline, Storage, Backup.