chore: de-slop prose, correct the Nox API docs, standardize route headers
Two passes over the repo, one editorial and one for accuracy. Prose (the avoid-ai-writing pass) - Replace ~250 em-dash-shaped " - " splices in comments, docs and UI copy with real punctuation. Paired dashes reading as parentheticals become parentheses. - Remove the remaining em dashes from code comments, CI and compose files, CLAUDE.md, and the legal pages. Bolded-lead-term list items keep theirs: there the dash is typography, not a splice. - Drop the Tier-1 filler: "actionable", "genuinely", "genuine", "deep dive", "showcase". Each one is now the specific thing it was standing in for. - Remove the coffee emoji from the README, the support modal and the landing page nav. - Relabel the "Deep dive" buttons in Archive and Research as "Object dossier", which is what the destination is called everywhere else. API docs, checked against the code rather than from memory - nox/docs/reference/http-api.md said the Nox routes need no auth. They do: real mode requires a bearer token AND confirmed: true. Documented both gates, the 401/403/404/503 responses, the /run summary field, the 200 parse-error diagnostic, and the two endpoints missing entirely (docs-search, docs/<path>). - cli.md conflated exit 1 and exit 3, and never documented --help/-h. - runtime-api.md implied every run() option was required and showed a diagnostic without suggest/seeAlso. - routes/nox.js listed 3 of its 6 endpoints, and its run-stream comment described a GET with the source in a query string. It is a POST. Standardization - Module header with a purpose line and an endpoint map on the 17 route files that had none. The 10 that already had one set the format. - engines: node >=22 on server and client, matching root, parser, runtime. - CLAUDE.md pointed at server/src/db/ and server/src/drivers/, neither of which exists, and claimed no linter is wired. Fixed all three, plus the stale 42-test count. - README's Node 20+ table row contradicted every engines field and its own quick start. Its Testing section omitted the server and client suites. - The client suite ran nowhere in CI. It now rides along in client-build. - The sqlite server-test leg is waived for a failure that no longer reproduces; noted in the job, left advisory pending runner confirmation. Verified: lint clean, SPA builds, 127 server + 10 client + parser + runtime suites pass, and both compose files plus .gitlab-ci.yml still parse as YAML. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
30232082f7
commit
ba9e7c63de
+18
-12
@@ -1,25 +1,25 @@
|
||||
# GitLab CI for Caelum — full pipeline on the self-hosted VPS runner (tag `vps`).
|
||||
# GitLab CI for Caelum: full pipeline on the self-hosted VPS runner (tag `vps`).
|
||||
#
|
||||
# Runs entirely on our own runner installed on the OVH VPS → zero GitLab
|
||||
# SaaS CI minutes. The runner mounts the host Docker socket (image builds use the
|
||||
# host daemon — no DinD/privileged) and the caelum stack dir at $DEPLOY_DIR, so
|
||||
# host daemon, no DinD/privileged) and the caelum stack dir at $DEPLOY_DIR, so
|
||||
# deploy is a *local* `docker compose` call (no SSH).
|
||||
#
|
||||
# Flow (everything blocks the next step):
|
||||
# verify — build the client, lint the code, test it (nox + server matrix).
|
||||
# image — build the Docker image, push :<sha> + :latest (host daemon).
|
||||
# image_check — lint the image (hadolint) + smoke-test it (boots in sqlite mode).
|
||||
# deploy — docker compose pull/up the caelum service against the live stack.
|
||||
# verify - build and test the client, lint, test (nox + server matrix).
|
||||
# image - build the Docker image, push :<sha> + :latest (host daemon).
|
||||
# image_check - lint the image (hadolint) + smoke-test it (boots in sqlite mode).
|
||||
# deploy - docker compose pull/up the caelum service against the live stack.
|
||||
#
|
||||
# Registry auth: a project deploy token named exactly "gitlab-deploy-token"
|
||||
# (read_registry) - GitLab then injects CI_DEPLOY_USER / CI_DEPLOY_PASSWORD
|
||||
# into jobs automatically. No CI/CD variable to rotate. CI_REGISTRY* are
|
||||
# GitLab built-ins.
|
||||
# (SSH_PRIVATE_KEY / VPS_HOST are unused now.) Secrets live on the VPS in
|
||||
# $DEPLOY_DIR/caelum.env — the image bakes none.
|
||||
# $DEPLOY_DIR/caelum.env; the image bakes none.
|
||||
|
||||
default:
|
||||
# Node 22 (LTS) — chevrotain 12 uses Object.groupBy which Node 20 lacks.
|
||||
# Node 22 (LTS): chevrotain 12 uses Object.groupBy which Node 20 lacks.
|
||||
image: node:22-alpine
|
||||
tags: [vps]
|
||||
|
||||
@@ -50,6 +50,9 @@ client-build:
|
||||
script:
|
||||
- cd client
|
||||
- npm ci --no-audit --no-fund
|
||||
# The client suite has no DB or browser dependency, so it rides along here
|
||||
# rather than paying for a separate job and a second npm ci.
|
||||
- npm test
|
||||
- npx vite build
|
||||
artifacts:
|
||||
paths:
|
||||
@@ -126,15 +129,18 @@ nox-runtime:
|
||||
- DB_KIND=$DB_KIND npm test
|
||||
rules: *run_rules
|
||||
|
||||
# Production runs DB_KIND=mysql (see $DEPLOY_DIR/caelum.env) — this leg blocks.
|
||||
# Production runs DB_KIND=mysql (see $DEPLOY_DIR/caelum.env), so this leg blocks.
|
||||
server-test:mysql:
|
||||
<<: *server_test
|
||||
variables:
|
||||
DB_KIND: mysql
|
||||
|
||||
# SQLite is a dev/test-only backend. Advisory (allow_failure) due to a known
|
||||
# pre-existing failure in observatory-daemon.test.js under sqlite — tracked
|
||||
# separately. Does NOT gate deploy; the mysql (prod) leg above does.
|
||||
# SQLite is a dev/test-only backend, so this leg stays advisory
|
||||
# (allow_failure) and does NOT gate deploy; the mysql (prod) leg above does.
|
||||
# The observatory-daemon.test.js failure this was originally waived for no
|
||||
# longer reproduces: the full suite passes 127/127 under DB_KIND=sqlite as of
|
||||
# 2026-09-12. Promote to allow_failure: false once a few pipelines confirm the
|
||||
# same on the runner.
|
||||
server-test:sqlite:
|
||||
<<: *server_test
|
||||
variables:
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@ See the quick start in [README.md](README.md). Once `npm run dev` works, you hav
|
||||
```
|
||||
client/ Vue 3 SPA. Pages in src/views/, components in src/components/.
|
||||
server/ Express API. Routes in src/routes/, services in src/services/.
|
||||
nox/ The Nox DSL. Self-contained - parser, runtime, docs, examples.
|
||||
nox/ The Nox DSL. Self-contained: parser, runtime, docs, examples.
|
||||
sql/ Database dumps. Regenerate via `cd server && npm run migrate -- --dump ../sql`.
|
||||
scripts/ Tooling, including the deploy bundler.
|
||||
```
|
||||
|
||||
@@ -9,14 +9,14 @@ Caelum is a shared observatory network: publish telescope time, run live
|
||||
imaging sessions, coordinate with federated operators, and share an imaging
|
||||
archive. Ships with **Nox**, a typed DSL for telescope/dome control.
|
||||
|
||||
Users are observatory operators and astronomers. The UI is a **dark,
|
||||
data-dense control surface** - information density over whitespace. Operators
|
||||
want to see state at a glance, not scroll.
|
||||
Users are observatory operators and astronomers. The UI is a dark, data-dense
|
||||
control surface that favors information density over whitespace. Operators want
|
||||
to see state at a glance, not scroll.
|
||||
|
||||
## Information architecture
|
||||
|
||||
Navigation follows the **lifecycle of a night**, top to bottom - the same arc
|
||||
the landing page tells. Read the sidebar as a story, not a taxonomy: your
|
||||
Navigation follows the lifecycle of a night, top to bottom, the same arc the
|
||||
landing page tells. Read the sidebar as a story, not a taxonomy: your
|
||||
telescope goes on the network → people book it → it runs live → the data lands
|
||||
→ all inside a community. Sidebar order is fixed and is the narrative.
|
||||
|
||||
@@ -28,14 +28,14 @@ telescope goes on the network → people book it → it runs live → the data l
|
||||
| **Archive** | Archive, SpaceDB | The data that lands |
|
||||
| **Community** | Community, Messages, Inbox | The people around it |
|
||||
|
||||
Live sessions render as a dynamic group **above** the workspaces when active -
|
||||
the "Run" beat, given top billing while it's happening. Quick-jump (⌘K)
|
||||
Live sessions render as a dynamic group above the workspaces while active. That
|
||||
is the "Run" beat, given top billing for as long as it lasts. Quick-jump (⌘K)
|
||||
searches both destinations and remote entities.
|
||||
|
||||
Rule: a page belongs to exactly one workspace, and the workspace answers "which
|
||||
stage of the night is this?". If a concept spans two, the surfaces co-locate
|
||||
inside one page (e.g. "My Bookings" and "Schedule" are the same page, not two
|
||||
nav items) - this is what kills the "scheduled here but not there" confusion.
|
||||
nav items). That is what kills the "scheduled here but not there" confusion.
|
||||
|
||||
**One home per surface.** A given kind of thing has a single canonical page:
|
||||
the network activity firehose lives on Activity (not also as an Archive tab);
|
||||
@@ -66,8 +66,8 @@ hard-code hex in a component.
|
||||
## Lifecycle state semantics (single source of truth)
|
||||
|
||||
The API returns `session_state` (`live` | `scheduled` | `completed` | raw
|
||||
status). Bind it directly to the pill component - never re-derive state in a
|
||||
view, never invent a fourth color:
|
||||
status). Bind it directly to the pill component. Never re-derive state in a
|
||||
view, and never invent a fourth color:
|
||||
|
||||
```vue
|
||||
<span class="pill" :class="'pill-' + s.session_state">{{ s.session_state }}</span>
|
||||
@@ -117,7 +117,7 @@ All sizes in rem via tokens. Font: system stack (air-gap safe, no CDN).
|
||||
One pattern per concern. Don't hand-roll a second variant in a view.
|
||||
|
||||
- **Page shell**: `.page-header` (title block + right-aligned actions slot)
|
||||
inside `.page-container` (max 1200px, centered) - provided by `App.vue`.
|
||||
inside `.page-container` (max 1200px, centered), provided by `App.vue`.
|
||||
- **Card**: `.card`. Header row: `.card-header` + `<h3>`. Stack with
|
||||
`.card + .card`.
|
||||
- **Stat strip**: `.stat-card` with `.label` + `.value`, laid out in
|
||||
@@ -125,7 +125,7 @@ One pattern per concern. Don't hand-roll a second variant in a view.
|
||||
- **Table**: `.data-table`. Numeric columns get `.num` (right-aligned,
|
||||
tabular figures). Don't style raw `<table>`.
|
||||
- **State pill**: `.pill` + `.pill-<state>` (see lifecycle table). The only
|
||||
status component. `.badge-*` is legacy - migrate on touch, don't add new.
|
||||
status component. `.badge-*` is legacy: migrate on touch, don't add new.
|
||||
- **Buttons**: `.btn` + `.btn-primary` / `-secondary` / `-danger` / `-ghost`,
|
||||
`.btn-sm` for dense rows. Hover color is pinned (RouterLink renders `<a>`;
|
||||
global `a:hover` would otherwise eat the label).
|
||||
@@ -142,7 +142,7 @@ Never use auto-fill/auto-fit (it silently rendered 3 cramped columns in a
|
||||
|
||||
## Density rules
|
||||
|
||||
- Tables: compact rows (`--space-3` padding), no zebra - hover only.
|
||||
- Tables: compact rows (`--space-3` padding), no zebra striping, hover only.
|
||||
- Headers: roomy (`--space-6` below page header).
|
||||
- Lists of entities: prefer table over card grid past ~6 rows.
|
||||
- Calendar/sky-viewer keep their specialized treatments.
|
||||
@@ -157,7 +157,7 @@ Never use auto-fill/auto-fit (it silently rendered 3 cramped columns in a
|
||||
## Non-negotiables
|
||||
|
||||
1. Read this file before any visual change. In QA, flag deviations.
|
||||
2. No hard-coded colors, spacing, or font sizes - tokens only.
|
||||
2. No hard-coded colors, spacing, or font sizes. Tokens only.
|
||||
3. One component per concern; migrate legacy on touch, never fork.
|
||||
4. Lifecycle state = API `session_state` → `.pill`. Never re-derive.
|
||||
5. A page lives in exactly one workspace.
|
||||
|
||||
@@ -4,15 +4,15 @@ A shared observatory network. Caelum lets observatories publish telescope time,
|
||||
|
||||
- **Site:** [caelum.network](https://caelum.network)
|
||||
- **Source:** [gitlab.com/paulhitt/caelum](https://gitlab.com/paulhitt/caelum)
|
||||
- **License:** MIT - see [LICENSE](LICENSE)
|
||||
- **Support:** [☕ Buy me a coffee](https://buy.stripe.com/eVqaEX1S41hz5R42JVeQM00)
|
||||
- **License:** MIT. See [LICENSE](LICENSE).
|
||||
- **Support:** [Buy me a coffee](https://buy.stripe.com/eVqaEX1S41hz5R42JVeQM00)
|
||||
|
||||
## What's in the box
|
||||
|
||||
| Area | Tech | What it does |
|
||||
| --- | --- | --- |
|
||||
| Web client | Vue 3 + Vite | Dashboards, scheduling, archive browser, Nox console |
|
||||
| API server | Node 20+, Express, Socket.IO | REST + realtime endpoints, auth, hardware drivers |
|
||||
| API server | Node 22+, Express, Socket.IO | REST + realtime endpoints, auth, hardware drivers |
|
||||
| Telescope control | Stellarium protocol, Alpaca | Mount + dome integration |
|
||||
| App database | MySQL 8 | Users, sites, telescopes, bookings, proposals, frames |
|
||||
| Catalog database | MySQL 8 (SpaceDB) | 1.5M+ asteroids and comets from NASA/JPL |
|
||||
@@ -52,7 +52,7 @@ npm start # runs server.js, serves API + SPA on the same port
|
||||
After deploying code that changes the schema, run the idempotent upgrade:
|
||||
|
||||
```sh
|
||||
npm run db:upgrade # repo root - upgrades the active backend
|
||||
npm run db:upgrade # repo root; upgrades the active backend
|
||||
# or, inside server/:
|
||||
DB_KIND=mysql npm run db:upgrade:mysql
|
||||
```
|
||||
@@ -72,7 +72,7 @@ docker compose up -d # boot MySQL + the app
|
||||
docker compose exec app sh -c "cd server && npm run seed"
|
||||
```
|
||||
|
||||
The app is then on `http://localhost:3002` (or whatever `CAELUM_PORT` is set to). MySQL data persists in the `caelum-db` volume - wipe with `docker compose down -v`. The compose file lives at the repo root; see [docker-compose.yml](docker-compose.yml) and the [`docker/initdb/`](docker/initdb/) scripts.
|
||||
The app is then on `http://localhost:3002` (or whatever `CAELUM_PORT` is set to). MySQL data persists in the `caelum-db` volume; wipe it with `docker compose down -v`. The compose file lives at the repo root; see [docker-compose.yml](docker-compose.yml) and the [`docker/initdb/`](docker/initdb/) scripts.
|
||||
|
||||
## Nox
|
||||
|
||||
@@ -105,7 +105,7 @@ session "spring-galaxies" {
|
||||
Run it without installing anything:
|
||||
|
||||
```sh
|
||||
# After npm publish - see RELEASING.md
|
||||
# After npm publish. See RELEASING.md
|
||||
npx @caelum/nox-runtime run program.nox
|
||||
```
|
||||
|
||||
@@ -159,7 +159,7 @@ Set `MYSQL_SPACEDB_DATABASE=` (empty) to disable SpaceDB routes.
|
||||
|
||||
### Populate the databases
|
||||
|
||||
Start the server cold - it auto-creates the schema via `initDb()` in [server/src/config/database.js](server/src/config/database.js). Then run the seed script to load sample sites, telescopes, proposals, and frames:
|
||||
Start the server cold. It auto-creates the schema via `initDb()` in [server/src/config/database.js](server/src/config/database.js). Then run the seed script to load sample sites, telescopes, proposals, and frames:
|
||||
|
||||
```sh
|
||||
cd server && npm run seed
|
||||
@@ -173,7 +173,7 @@ The seed creates two accounts:
|
||||
SpaceDB routes return 503 until the catalog is available.
|
||||
|
||||
**SQLite dev path (no MySQL):** drop the SpaceDB catalog file `db.sqlite3`
|
||||
at the repo root (it's gitignored - the dump is ~1.4 GB) and SpaceDB works
|
||||
at the repo root (it's gitignored; the dump is ~1.4 GB) and SpaceDB works
|
||||
immediately; the server reads it directly. Override the location with
|
||||
`SPACEDB_SQLITE_PATH` or `SPACEDB_PATH`. If the file is absent, SpaceDB
|
||||
cleanly reports 503 and the rest of the app is unaffected.
|
||||
@@ -210,12 +210,21 @@ The Nox language is a self-contained sub-project. See [nox/docs/](nox/docs/) for
|
||||
|
||||
## Testing
|
||||
|
||||
Everything runs on Node's built-in test runner. From the repo root, `npm test`
|
||||
runs all four suites concurrently; individually:
|
||||
|
||||
```sh
|
||||
cd server && npm test # 127 tests: API, lifecycle, DB contract, Stripe
|
||||
cd client && npm test # markdown renderer and log redaction
|
||||
cd nox/parser && npm test # parser, type checker (10/10 negative cases)
|
||||
cd nox/runtime && npm test # interpreter, CLI, rollback semantics
|
||||
cd nox/runtime && npm test # interpreter, CLI, REPL, rollback semantics
|
||||
```
|
||||
|
||||
CI runs both on every push.
|
||||
`npm run lint` runs ESLint over `server/src`, `client/src` and `scripts`.
|
||||
|
||||
CI runs the lint job, all four suites, and a client build on every push. The
|
||||
server suite runs twice, once per `DB_KIND` backend, so a change that works on
|
||||
SQLite but not MySQL fails before it ships.
|
||||
|
||||
## Contributing
|
||||
|
||||
@@ -223,10 +232,9 @@ Pull requests welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) for the developmen
|
||||
|
||||
## Support
|
||||
|
||||
Caelum is free and MIT-licensed. If it saved you time or you just like the
|
||||
project, you can [**☕ buy me a coffee**](https://buy.stripe.com/eVqaEX1S41hz5R42JVeQM00).
|
||||
Payments are handled securely by Stripe. Thank you - it genuinely helps keep
|
||||
development caffeinated.
|
||||
Caelum is free and MIT-licensed. If it saved you time, you can
|
||||
[buy me a coffee](https://buy.stripe.com/eVqaEX1S41hz5R42JVeQM00). Stripe
|
||||
handles the payment; nothing about the project is gated behind it.
|
||||
|
||||
## Security
|
||||
|
||||
|
||||
+2
-2
@@ -13,7 +13,7 @@ with Docker (see the README).
|
||||
|
||||
## Versioning
|
||||
|
||||
Pre-1.0 SemVer: every minor may break, every patch is safe. Breaking changes go in `CHANGELOG.md`. All five workspaces share one version number - keep them in sync.
|
||||
Pre-1.0 SemVer: every minor may break, every patch is safe. Breaking changes go in `CHANGELOG.md`. All five workspaces share one version number, so keep them in sync.
|
||||
|
||||
## Release checklist
|
||||
|
||||
@@ -21,7 +21,7 @@ Pre-1.0 SemVer: every minor may break, every patch is safe. Breaking changes go
|
||||
# 1. Bump versions across all five package.jsons. Pre-1.0 minor bump:
|
||||
# root, server, client, nox/parser, nox/runtime
|
||||
#
|
||||
# (Use find + sed, or do them by hand - they should all match.)
|
||||
# (Use find + sed, or do them by hand. They should all match.)
|
||||
#
|
||||
# 2. Move [Unreleased] to [<version>] in CHANGELOG.md and date it.
|
||||
#
|
||||
|
||||
@@ -6,6 +6,9 @@
|
||||
"author": "Paul Hitt",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
|
||||
+4
-4
@@ -16,7 +16,7 @@ const route = useRoute();
|
||||
// Auth screens, the public landing, and the public Nox pages all need this.
|
||||
// Routes that always use the full-screen (no-sidebar) layout: auth/marketing/docs
|
||||
// pages, plus the purchase flow (checkout + order) which is a standalone public
|
||||
// funnel. Shop + Shop Catalog are NOT here - for a signed-in user they live
|
||||
// funnel. Shop + Shop Catalog are NOT here; for a signed-in user they live
|
||||
// inside the portal (sidebar). A guest has no sidebar, so the `|| !auth.token`
|
||||
// below renders any portal-eligible page (e.g. the public /shop) full-screen.
|
||||
const FULLSCREEN_ROUTES = new Set(['login', 'register', 'landing', 'nox-docs', 'nox-examples', 'setup', 'status', 'checkout', 'shop-order']);
|
||||
@@ -27,11 +27,11 @@ function logout() {
|
||||
router.push('/');
|
||||
}
|
||||
|
||||
// The sidebar is ordered as the night's lifecycle - the same arc the landing
|
||||
// page tells - instead of by abstract data category. Read top to bottom it's a
|
||||
// The sidebar is ordered as the night's lifecycle, the same arc the landing
|
||||
// page tells, instead of by abstract data category. Read top to bottom it's a
|
||||
// story: an operator opens up their telescope (Your Observatory), someone books
|
||||
// time on it (Plan & Book), the session runs live (pinned above + surfaced in
|
||||
// Tonight), and the data lands in the archive (Archive) - all inside a
|
||||
// Tonight), and the data lands in the archive (Archive), all inside a
|
||||
// community. Grouping by the *arc* rather than by noun-buckets (Observe / Plan /
|
||||
// Data …) is what makes the nav feel like a flow instead of a pile of pages.
|
||||
// Tonight - what's happening now / next
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script setup>
|
||||
// Quiet version stamp at the bottom of the sidebar. Just the version + short
|
||||
// commit, so it's clear what's running without a DevTools trip. Deliberately
|
||||
// no hover panel, no health readout, no test buttons - an ops widget there
|
||||
// no hover panel, no health readout, no test buttons; an ops widget there
|
||||
// both read as corporate SaaS and popped up over the Logout button.
|
||||
// Build-time values come from Vite's `define` block (inlined, no runtime cost).
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup>
|
||||
// Caelum Lab - extracted from Research.vue (which had grown past 1600 lines).
|
||||
// Caelum Lab: extracted from Research.vue (which had grown past 1600 lines).
|
||||
//
|
||||
// Self-contained responsibilities:
|
||||
// - Pick a research target + optional archive frames
|
||||
@@ -60,13 +60,13 @@ function targetPayload() {
|
||||
|
||||
// Server-side preferences: did the user (or the bundled .env) supply an
|
||||
// Anthropic key? Lab disables Analyze when false. Server never echoes the
|
||||
// raw key - only a suffix + boolean.
|
||||
// raw key, only a suffix and a boolean.
|
||||
const prefs = ref({ has_anthropic_key: false, anthropic_api_key_suffix: null, anthropic_key_source: null });
|
||||
async function loadPrefs() {
|
||||
try { prefs.value = await api.get('/preferences'); } catch { /* defaults are fine */ }
|
||||
}
|
||||
|
||||
// Frames matching the picked target - best-effort by target_name LIKE.
|
||||
// Frames matching the picked target, best-effort by target_name LIKE.
|
||||
// Lazily loaded when the target changes; empty is fine (Claude can analyze
|
||||
// catalog metadata alone).
|
||||
const labFrames = ref([]);
|
||||
@@ -236,7 +236,7 @@ async function refineAnalysis() {
|
||||
}
|
||||
}
|
||||
|
||||
// "Try another lens" - re-run the same target/frames with a different
|
||||
// "Try another lens": re-run the same target/frames with a different
|
||||
// template. Saves the user from retyping the question.
|
||||
async function rerunWithTemplate(tplKey) {
|
||||
claude.value.template = tplKey;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script setup>
|
||||
// Observation cadence for one object: its frames over time, laned by filter,
|
||||
// markers sized by exposure. Pure-local (no photometry) - it answers "when,
|
||||
// markers sized by exposure. Pure-local (no photometry); it answers "when,
|
||||
// how often, and how well have we captured this?", the honest coverage view.
|
||||
// SVG, tokens only.
|
||||
import { computed } from 'vue';
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script setup>
|
||||
// In-app "buy me a coffee". The supporter picks an amount here and pays here:
|
||||
// the card step is Stripe's Embedded Checkout, mounted inside this modal, so
|
||||
// they never leave Caelum. Card fields live in Stripe's own iframe - this app
|
||||
// they never leave Caelum. Card fields live in Stripe's own iframe; this app
|
||||
// never sees or handles them.
|
||||
//
|
||||
// Falls back to a plain hosted payment link when the server reports Stripe is
|
||||
@@ -50,7 +50,7 @@ const bounds = computed(() => ({
|
||||
}));
|
||||
|
||||
// Mirrors the server's rule so the user gets instant feedback; the server
|
||||
// re-validates regardless - this is UX, not a security control.
|
||||
// re-validates regardless; this is UX, not a security control.
|
||||
const validationError = computed(() => {
|
||||
const a = amountCents.value;
|
||||
if (a == null) return 'Enter an amount.';
|
||||
@@ -130,7 +130,7 @@ async function proceed() {
|
||||
<div v-if="open" class="sp-overlay" @click.self="emit('close')">
|
||||
<div class="sp-modal" role="dialog" aria-modal="true" aria-labelledby="sp-title">
|
||||
<div class="sp-head">
|
||||
<h3 id="sp-title"><span aria-hidden="true">☕</span> Support Caelum</h3>
|
||||
<h3 id="sp-title">Support Caelum</h3>
|
||||
<button class="sp-x" aria-label="Close" @click="emit('close')">✕</button>
|
||||
</div>
|
||||
|
||||
@@ -185,7 +185,7 @@ async function proceed() {
|
||||
contribute through our Stripe page.
|
||||
</p>
|
||||
<a class="btn btn-primary sp-go" :href="config?.fallbackUrl" target="_blank" rel="noopener">
|
||||
☕ Continue to Stripe
|
||||
Continue to Stripe
|
||||
</a>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
@@ -52,12 +52,12 @@ const router = createRouter({ history: createWebHistory(), routes });
|
||||
//
|
||||
// 'nox' belongs here: the landing sells "Try Nox without signing up" and
|
||||
// Examples has an "Open in Console" button, but /nox required a token, so a
|
||||
// guest following that path was bounced to the landing - and the example the
|
||||
// guest following that path was bounced to the landing, and the example the
|
||||
// button had just written to localStorage was silently dropped. The server
|
||||
// already treats mock runs as public on purpose (see requireRealModeSafety in
|
||||
// routes/nox.js: /nox/check, /nox/examples and mock /nox/run take no auth,
|
||||
// while real mode demands both auth and an explicit confirmation), so the IDE
|
||||
// itself is safe to expose - the driver-touching path is gated server-side.
|
||||
// itself is safe to expose; the driver-touching path is gated server-side.
|
||||
const ALWAYS_PUBLIC = new Set(['nox', 'nox-docs', 'nox-examples', 'setup', 'status', 'shop', 'checkout', 'terms', 'privacy', 'guidelines', 'dmca']);
|
||||
|
||||
router.beforeEach((to) => {
|
||||
|
||||
@@ -45,7 +45,7 @@ export function initSentry(app, router) {
|
||||
* callers can grep the Sentry UI for it.
|
||||
*/
|
||||
/**
|
||||
* Tag subsequent Sentry events with the authed user - id + username + role
|
||||
* Tag subsequent Sentry events with the authed user: id + username + role
|
||||
* only, never email or password. Called from the auth store on login,
|
||||
* register, and refresh. clearSentryUser() reverses it on logout.
|
||||
*
|
||||
|
||||
@@ -8,13 +8,13 @@ function getToken() {
|
||||
//
|
||||
// Defensive against three classes of failure the old version surfaced as
|
||||
// opaque crashes:
|
||||
// 1. Network errors (server down, DNS, CORS preflight) - fetch rejects
|
||||
// 1. Network errors (server down, DNS, CORS preflight): fetch rejects
|
||||
// without producing a Response. Surface as "Network error talking to <path>".
|
||||
// 2. Empty bodies (proxy returns 500 with no payload) - res.json() throws
|
||||
// 2. Empty bodies (proxy returns 500 with no payload): res.json() throws
|
||||
// "Unexpected end of JSON input" in Chrome and the much worse
|
||||
// "The string did not match the expected pattern" in Safari. We
|
||||
// read text first and fall back gracefully.
|
||||
// 3. Non-JSON bodies (proxy returns HTML 502, plain text 500) - same
|
||||
// 3. Non-JSON bodies (proxy returns HTML 502, plain text 500): same
|
||||
// treatment. We return a sensible HTTP <status> message instead of
|
||||
// letting JSON.parse crash.
|
||||
async function request(path, options = {}) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Applies the user's theme + density preferences to the document. These used
|
||||
// to be saved to the server and then ignored - the toggles in /settings did
|
||||
// to be saved to the server and then ignored; the toggles in /settings did
|
||||
// nothing visible. This is the missing half: it reflects the prefs onto
|
||||
// <html data-theme data-density>, which the CSS in style.css keys off.
|
||||
//
|
||||
|
||||
@@ -17,7 +17,7 @@ export async function getStripe() {
|
||||
if (!cfg.enabled || !cfg.publishableKey) return null;
|
||||
// { stripeAccount } is REQUIRED when the server minted the client_secret on
|
||||
// a connected account. Omit it and Stripe.js rejects the secret, Elements
|
||||
// never mounts, and the supporter sees an empty box instead of a card form —
|
||||
// never mounts, and the supporter sees an empty box instead of a card form,
|
||||
// with nothing in the console to explain it. Cost hours on the Hitt Hosting
|
||||
// CRM before it was spotted.
|
||||
_stripePromise = cfg.stripeAccount
|
||||
|
||||
@@ -2,7 +2,7 @@ import { defineStore } from 'pinia';
|
||||
|
||||
// Build-a-list cart for the shop surfaced in the Setup Wizard. Persisted to
|
||||
// localStorage so it survives navigation and refresh. Caelum doesn't sell gear
|
||||
// directly - checkout hands the list off to Agena Astro (our affiliate
|
||||
// directly; checkout hands the list off to Agena Astro (our affiliate
|
||||
// retailer), so each item keeps its `source_url` to deep-link there. Prices are
|
||||
// a DISPLAY-only snapshot for a rough running total; Agena has live pricing.
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// Each call writes to the matching native console method so DevTools still
|
||||
// shows everything. ALL five levels (debug, info, warning, error, fatal)
|
||||
// forward to Sentry as events when VITE_ENABLE_SENTRY is truthy and sentry.js
|
||||
// was initialised. Capturing info/debug is high-volume - disable with
|
||||
// was initialised. Capturing info/debug is high-volume; disable with
|
||||
// VITE_ENABLE_SENTRY=false where that's too noisy.
|
||||
//
|
||||
// Defaults: enabled in prod builds, disabled in `vite dev` (override with
|
||||
|
||||
@@ -401,7 +401,7 @@ const networkCount = computed(() => frames.value.filter(f => f.visibility === 'n
|
||||
</div>
|
||||
</div>
|
||||
<div style="display:flex;gap:0.5rem">
|
||||
<RouterLink v-if="detail.target_name" :to="`/object/${encodeURIComponent(detail.target_name)}`" class="btn btn-sm btn-secondary">Deep dive →</RouterLink>
|
||||
<RouterLink v-if="detail.target_name" :to="`/object/${encodeURIComponent(detail.target_name)}`" class="btn btn-sm btn-secondary">Object dossier →</RouterLink>
|
||||
<button class="btn btn-sm" :class="detail.liked ? 'btn-primary' : 'btn-secondary'" @click="toggleLike">♥ {{ detail.likes_count }}</button>
|
||||
<button class="btn btn-sm" :class="detail.bookmarked ? 'btn-primary' : 'btn-secondary'" @click="toggleBookmark">★</button>
|
||||
<button class="btn btn-sm btn-secondary" title="Report this frame" @click="openReport('frame', detail.id, detail.target_name || detail.filename)">⚑ Report</button>
|
||||
@@ -582,7 +582,7 @@ const networkCount = computed(() => frames.value.filter(f => f.visibility === 'n
|
||||
</form>
|
||||
</template>
|
||||
<template v-else>
|
||||
<p style="margin:0.6rem 0 1rem">Thanks — your report has been submitted for review.</p>
|
||||
<p style="margin:0.6rem 0 1rem">Thanks. Your report has been submitted for review.</p>
|
||||
<div class="modal-actions">
|
||||
<button class="btn btn-primary" @click="showReport = false">Close</button>
|
||||
</div>
|
||||
|
||||
@@ -21,7 +21,7 @@ function buyLink(item) {
|
||||
}
|
||||
|
||||
// Open every item's Agena page in its own tab. Synthetic anchor clicks (vs
|
||||
// window.open) survive pop-up blockers far better since each reads as a genuine
|
||||
// window.open) survive pop-up blockers far better since each reads as a real
|
||||
// link click within the user gesture. Per-line links remain the reliable path.
|
||||
function openAll() {
|
||||
for (const i of cart.items) {
|
||||
|
||||
@@ -8,7 +8,7 @@ import { pillClass, pillLabel } from '../utils/state.js';
|
||||
const auth = useAuthStore();
|
||||
|
||||
// The dashboard is "Tonight": it reads down the same arc the landing tells and
|
||||
// the sidebar follows - your observatory → what's booked → what's live → the
|
||||
// the sidebar follows: your observatory → what's booked → what's live → the
|
||||
// data that lands. Each section is a window into one lifecycle beat and links
|
||||
// to its full page; the dashboard itself owns nothing, it orients you.
|
||||
const sites = ref([]);
|
||||
@@ -35,7 +35,7 @@ onMounted(async () => {
|
||||
|
||||
// "Your observatory" means the sites you actually run. GET /sites also returns
|
||||
// every network-visible site, so counting all of them would put other people's
|
||||
// observatories under "your night" - and hide the getting-started path from a
|
||||
// observatories under "your night", and hide the getting-started path from a
|
||||
// brand-new user who owns nothing. Scope to owner_id.
|
||||
const mySites = computed(() => sites.value.filter(s => s.owner_id === auth.user?.id));
|
||||
const onlineCount = computed(() => mySites.value.filter(s => s.status === 'online').length);
|
||||
@@ -54,7 +54,7 @@ const upcomingBookings = computed(() =>
|
||||
// A brand-new account has nothing of its own to roll up. Rather than cards that
|
||||
// say "Your observatory" over strangers' sites, show the same four-step path
|
||||
// the landing describes, each step a live link. Keyed off things that are
|
||||
// genuinely yours - owned sites, your bookings, your proposals.
|
||||
// actually yours: owned sites, your bookings, your proposals.
|
||||
const isNewUser = computed(() =>
|
||||
!loading.value && !mySites.value.length && !bookings.value.length && !proposals.value.length,
|
||||
);
|
||||
|
||||
@@ -48,8 +48,8 @@ const EFFECTIVE = 'July 20, 2026';
|
||||
address, telephone number, and email address.</li>
|
||||
<li>A statement that you have a good-faith belief that the use of the material in the
|
||||
manner complained of is not authorized by the copyright owner, its agent, or the law.</li>
|
||||
<li>A statement that the information in the notice is accurate, and — under penalty of
|
||||
perjury — that you are the copyright owner or are authorized to act on the owner's
|
||||
<li>A statement that the information in the notice is accurate, and, under penalty of
|
||||
perjury, that you are the copyright owner or are authorized to act on the owner's
|
||||
behalf.</li>
|
||||
</ol>
|
||||
<p>Upon receiving a valid notice, we will expeditiously remove or disable access to the
|
||||
|
||||
@@ -20,7 +20,7 @@ const EFFECTIVE = 'July 20, 2026';
|
||||
each other with real hardware, shared time, and public content. These Guidelines set the
|
||||
ground rules for using the Service and are part of our
|
||||
<RouterLink to="/terms">Terms of Service</RouterLink>. They apply everywhere you can post
|
||||
or interact — image frames, comments, likes, direct messages, profiles, session notes,
|
||||
or interact: image frames, comments, likes, direct messages, profiles, session notes,
|
||||
and the activity feed.</p>
|
||||
|
||||
<h2>What's not allowed</h2>
|
||||
@@ -28,7 +28,7 @@ const EFFECTIVE = 'July 20, 2026';
|
||||
<li><strong>Illegal content or activity.</strong> Don't post anything unlawful, or use
|
||||
Caelum to break the law.</li>
|
||||
<li><strong>Harassment and hate.</strong> No harassment, threats, bullying, or attacks on
|
||||
people based on who they are. Disagree about optics all you like — respect the person.</li>
|
||||
people based on who they are. Disagree about optics all you like, but respect the person.</li>
|
||||
<li><strong>Spam and manipulation.</strong> No spam, bulk unsolicited messaging, scams,
|
||||
or artificial inflation of likes, comments, or reputation.</li>
|
||||
<li><strong>Malware and abuse.</strong> No malware, phishing, or malicious links or
|
||||
@@ -50,14 +50,14 @@ const EFFECTIVE = 'July 20, 2026';
|
||||
</ul>
|
||||
|
||||
<h2>Sharing content responsibly</h2>
|
||||
<p>You choose the visibility of what you upload — private, network (visible to Caelum
|
||||
<p>You choose the visibility of what you upload: private, network (visible to Caelum
|
||||
users), or public. Set it deliberately, and remember that anything you make public or
|
||||
share can be seen, and potentially re-shared, by others.</p>
|
||||
|
||||
<h2>Consequences</h2>
|
||||
<p>We do not pre-screen content, but when something violates these Guidelines we may remove
|
||||
or restrict it and take action on the account — including warnings, temporary
|
||||
suspension, or permanent termination — at our discretion and without prior notice, as
|
||||
or restrict it and take action on the account, including warnings, temporary
|
||||
suspension, or permanent termination, at our discretion and without prior notice, as
|
||||
described in the <RouterLink to="/terms">Terms</RouterLink>. Users who repeatedly infringe
|
||||
others' intellectual-property rights will have their accounts suspended or terminated.</p>
|
||||
|
||||
|
||||
@@ -153,7 +153,7 @@ function goToNox() {
|
||||
<RouterLink to="/nox/examples">Try Nox</RouterLink>
|
||||
<button class="lp-coffee" type="button" @click="showSupport = true"
|
||||
title="Support Caelum">
|
||||
<span aria-hidden="true">☕</span><span>Buy me a coffee</span>
|
||||
<span>Buy me a coffee</span>
|
||||
</button>
|
||||
</nav>
|
||||
</div>
|
||||
@@ -266,7 +266,7 @@ function goToNox() {
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ── Nox showcase ────────────────────────────────────────── -->
|
||||
<!-- ── Nox section ──────────────────────────────────────────── -->
|
||||
<section class="lp-band lp-nox-band">
|
||||
<div class="lp-inner lp-nox">
|
||||
<div class="lp-nox-text">
|
||||
@@ -596,7 +596,7 @@ function goToNox() {
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
/* ── Nox showcase ── */
|
||||
/* ── Nox section ── */
|
||||
.lp-nox-band {
|
||||
border-top: 1px solid var(--border);
|
||||
background:
|
||||
|
||||
@@ -17,7 +17,7 @@ const STORAGE_KEY = 'nox.workspace.v1';
|
||||
// so it returns undefined and `.query` throws.
|
||||
const route = useRoute();
|
||||
// Guests reach /nox straight from the landing ("try it without signing up")
|
||||
// and render with no sidebar - without this bar they have no way back out.
|
||||
// and render with no sidebar; without this bar they have no way back out.
|
||||
const auth = useAuthStore();
|
||||
|
||||
const tabs = ref([]);
|
||||
@@ -185,7 +185,7 @@ onUnmounted(() => {
|
||||
watch([tabs, activeTabId], persist, { deep: true });
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Resource readiness strip - when Mode = Real hardware, parse the
|
||||
// Resource readiness strip: when Mode = Real hardware, parse the
|
||||
// program's `use telescope/dome NAME = "VALUE"` statements, resolve
|
||||
// each VALUE against configured hardware, and surface reachability so
|
||||
// the operator knows the program will hit real gear before Run.
|
||||
@@ -440,7 +440,7 @@ async function openHardwareWizard() {
|
||||
hwTelescopes.value = tels;
|
||||
hwEnclosures.value = encs;
|
||||
} catch {
|
||||
// Listing is optional - the wizard still works for discovery alone.
|
||||
// Listing is optional; the wizard still works for discovery alone.
|
||||
hwTelescopes.value = [];
|
||||
hwEnclosures.value = [];
|
||||
}
|
||||
@@ -479,7 +479,7 @@ function deviceKey(dev) {
|
||||
|
||||
function isAttachable(dev) {
|
||||
// Today we wire telescopes and domes. Cameras/focusers/filter wheels are
|
||||
// attached via the instruments table - a follow-up if needed.
|
||||
// attached via the instruments table; a follow-up if needed.
|
||||
const t = String(dev.DeviceType || '').toLowerCase();
|
||||
return t === 'telescope' || t === 'dome';
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ const selected = ref('');
|
||||
const loading = ref(true);
|
||||
const error = ref('');
|
||||
|
||||
// Inline-run state. Public, no-auth - uses /api/nox/run-stream in mock mode.
|
||||
// Inline-run state. Public, no-auth; uses /api/nox/run-stream in mock mode.
|
||||
const ops = ref([]);
|
||||
const runError = ref('');
|
||||
const running = ref(false);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup>
|
||||
// Object dossier - the deep-dive page for one object, reached from an archive
|
||||
// Object dossier: one page per object, reached from an archive
|
||||
// frame or a research card. Threads everything Caelum knows about it: frames
|
||||
// across telescopes, the observations that produced them, catalog identity,
|
||||
// prior analysis, a cadence chart, and an embedded Lab (analyze → schedulable
|
||||
|
||||
@@ -13,7 +13,7 @@ const error = ref('');
|
||||
const loading = ref(true);
|
||||
let timer = null;
|
||||
|
||||
// The webhook is the source of truth - don't trust the client redirect alone.
|
||||
// The webhook is the source of truth; don't trust the client redirect alone.
|
||||
// Poll the order until it settles, then stop.
|
||||
const SETTLED = new Set(['paid', 'paid_oversold', 'failed', 'canceled']);
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script setup>
|
||||
// Privacy Policy. Public, guest-viewable. Written to match the data Caelum
|
||||
// actually collects and the third parties it actually uses - not a generic
|
||||
// actually collects and the third parties it actually uses, not a generic
|
||||
// template. Governing entity: Extant 2000 LLC (VA).
|
||||
import { RouterLink } from 'vue-router';
|
||||
import LegalFooter from '../components/LegalFooter.vue';
|
||||
@@ -54,10 +54,10 @@ const EFFECTIVE = 'July 20, 2026';
|
||||
|
||||
<h2>2. How we use information</h2>
|
||||
<ul>
|
||||
<li>To provide, operate, and maintain the Service — authentication, hosting and
|
||||
<li>To provide, operate, and maintain the Service: authentication, hosting and
|
||||
displaying your content according to its visibility, delivering messages and
|
||||
notifications, and running observing sessions.</li>
|
||||
<li>To keep the Service safe — enforcing our
|
||||
<li>To keep the Service safe, by enforcing our
|
||||
<RouterLink to="/terms">Terms</RouterLink> and
|
||||
<RouterLink to="/guidelines">Community Guidelines</RouterLink>, reviewing reports,
|
||||
and preventing abuse.</li>
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
<script setup>
|
||||
// Research - the science feed. Pulls observation candidates from external
|
||||
// Research: the science feed. Pulls observation candidates from external
|
||||
// catalogs (MPC for NEOs, NASA Exoplanet Archive for transits, AAVSO for
|
||||
// variable stars), surfaces them as actionable cards, and routes the
|
||||
// variable stars), surfaces each as a card with a Schedule button, and
|
||||
// routes the
|
||||
// "Schedule" button through the same Observation snapshot + jobs queue
|
||||
// spine the daemon poll already uses.
|
||||
//
|
||||
@@ -63,7 +64,7 @@ const tools = ref({
|
||||
});
|
||||
const RESEARCH_CATEGORIES = ['neo', 'exoplanet_transit', 'variable_star', 'transient', 'satellite'];
|
||||
|
||||
// Add a target to the feed with no upstream fetch and no scheduling - the one
|
||||
// Add a target to the feed with no upstream fetch and no scheduling: the one
|
||||
// add path that works on an internet-less deploy. Surfaced both as the header
|
||||
// "+ Add research" modal and inside the Workshop.
|
||||
const showAddModal = ref(false);
|
||||
@@ -101,7 +102,7 @@ async function onAtlasJump({ ra, dec }) {
|
||||
runAtlas();
|
||||
}
|
||||
|
||||
// Per-card DSS toggles - sky preview embedded inline on existing cards.
|
||||
// Per-card DSS toggles: sky preview embedded inline on existing cards.
|
||||
const dssShown = ref({}); // { [targetId]: true }
|
||||
function toggleDss(target) {
|
||||
if (dssShown.value[target.id]) {
|
||||
@@ -141,9 +142,9 @@ async function toggleField(target) {
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Aladin Lite - interactive sky atlas (CDS, loaded from CDN on
|
||||
// ---- Aladin Lite: interactive sky atlas (CDS, loaded from CDN on
|
||||
// demand). Reuses a single in-page <script> load; subsequent inits are
|
||||
// instant. Per-card "⊕ atlas" complements the "◎ sky" DSS thumbnail -
|
||||
// instant. Per-card "⊕ atlas" complements the "◎ sky" DSS thumbnail;
|
||||
// DSS for a fast static glance, Aladin for interactive exploration with
|
||||
// catalog overlays.
|
||||
let aladinLoadPromise = null;
|
||||
@@ -349,7 +350,7 @@ function altAz(ra, dec, lat, lng, date) {
|
||||
const haR = deg2rad(ha), decR = deg2rad(dec), latR = deg2rad(lat);
|
||||
const sinAlt = Math.sin(decR) * Math.sin(latR) + Math.cos(decR) * Math.cos(latR) * Math.cos(haR);
|
||||
const alt = rad2deg(Math.asin(Math.max(-1, Math.min(1, sinAlt))));
|
||||
// Azimuth - not displayed but kept for completeness.
|
||||
// Azimuth: not displayed but kept for completeness.
|
||||
const cosAz = (Math.sin(decR) - Math.sin(deg2rad(alt)) * Math.sin(latR)) / (Math.cos(deg2rad(alt)) * Math.cos(latR));
|
||||
let az = rad2deg(Math.acos(Math.max(-1, Math.min(1, cosAz))));
|
||||
if (Math.sin(haR) > 0) az = 360 - az;
|
||||
@@ -373,7 +374,7 @@ function nextWindowFromSite(target, site) {
|
||||
else { if (alt > bestAlt) bestAlt = alt; }
|
||||
windowEnd = t;
|
||||
} else if (inWindow) {
|
||||
// First sustained window closed - return it.
|
||||
// First sustained window closed; return it.
|
||||
return { start: windowStart, end: windowEnd, maxAlt: bestAlt };
|
||||
}
|
||||
}
|
||||
@@ -797,7 +798,7 @@ function fmtRefreshed(meta) {
|
||||
:title="`Refresh from ${t.source_label}`">
|
||||
{{ refreshing[t.id] ? '↻ refreshing…' : '↻ refresh' }}
|
||||
</button>
|
||||
<RouterLink :to="`/object/${encodeURIComponent(t.designation)}`" class="btn btn-ghost btn-sm" title="Everything Caelum knows about this object">Deep dive →</RouterLink>
|
||||
<RouterLink :to="`/object/${encodeURIComponent(t.designation)}`" class="btn btn-ghost btn-sm" title="Everything Caelum knows about this object">Object dossier →</RouterLink>
|
||||
<button class="btn btn-primary btn-sm" @click="openSchedule(t)">Schedule</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -16,7 +16,7 @@ const showModal = ref(false);
|
||||
const editing = ref(null);
|
||||
const error = ref('');
|
||||
// Details popover for clicking a booking on the calendar grid. Distinct from
|
||||
// the edit modal - even own bookings open in "details" first so the click
|
||||
// the edit modal; even own bookings open in "details" first so the click
|
||||
// affordance is uniform (own + others' look the same on the grid).
|
||||
const viewing = ref(null);
|
||||
|
||||
@@ -138,13 +138,13 @@ function openCreate(prefill = {}) {
|
||||
showModal.value = true;
|
||||
}
|
||||
|
||||
// Today, at local midnight - used to disable past-date scheduling.
|
||||
// Today at local midnight. Used to disable past-date scheduling.
|
||||
const todayStart = computed(() => { const d = new Date(); d.setHours(0, 0, 0, 0); return d; });
|
||||
function isPastDay(day) { return day.date < todayStart.value; }
|
||||
|
||||
// Click on a day cell (anywhere not inside a booking event) → prefill the
|
||||
// create modal with this date so the user doesn't have to retype it.
|
||||
// Past days and adjacent-month padding cells are not clickable - you
|
||||
// Past days and adjacent-month padding cells are not clickable; you
|
||||
// can't book something that already happened.
|
||||
// A Date's LOCAL calendar date as YYYY-MM-DD. Never toISOString() for this:
|
||||
// it converts to UTC first, so west of Greenwich it can report tomorrow's
|
||||
@@ -209,7 +209,7 @@ async function saveBooking() {
|
||||
// Client-side guard: a same-day booking that crosses midnight must say so
|
||||
// explicitly. Catch the user mistake of leaving end_date blank with an
|
||||
// end_time earlier than start_time (which produces a negative window
|
||||
// that the server now refuses anyway - surface it nicer here).
|
||||
// that the server now refuses anyway; surface it nicer here).
|
||||
const startDate = form.value.start_date;
|
||||
const endDate = form.value.end_date || form.value.start_date;
|
||||
const startTs = new Date(`${startDate}T${form.value.start_time}`).getTime();
|
||||
|
||||
@@ -36,7 +36,7 @@ async function save() {
|
||||
error.value = '';
|
||||
try {
|
||||
prefs.value = await api.patch('/preferences', prefs.value);
|
||||
// Apply theme + density immediately - this is what makes the toggles do
|
||||
// Apply theme + density immediately; this is what makes the toggles do
|
||||
// something visible instead of silently saving to the server.
|
||||
applyAppearance({ theme: prefs.value.theme, density: prefs.value.density });
|
||||
savedFlash.value = true;
|
||||
|
||||
@@ -21,7 +21,7 @@ const loading = ref(true);
|
||||
const error = ref('');
|
||||
|
||||
// Shop: real products (Agena Astro-sourced) the operator curates. Loaded
|
||||
// best-effort - if the shop isn't configured the whole section stays hidden.
|
||||
// best-effort; if the shop isn't configured the whole section stays hidden.
|
||||
const shopEnabled = ref(false);
|
||||
const shopProducts = ref([]);
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// you can share https://caelum.network/status during an incident and
|
||||
// people see real subsystem state without needing access to the app.
|
||||
//
|
||||
// No auth, no router guards needed - the underlying endpoint is public
|
||||
// No auth, no router guards needed; the underlying endpoint is public
|
||||
// and emits only operational data (no row contents, no user identities).
|
||||
|
||||
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
|
||||
@@ -33,7 +33,7 @@ async function refresh() {
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
// Best-effort history fetch - falls back silently to an empty
|
||||
// Best-effort history fetch; falls back silently to an empty
|
||||
// spark-bar so the page still loads if the table is missing.
|
||||
try {
|
||||
const r = await fetch('/api/health/history?limit=60', { cache: 'no-store' });
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script setup>
|
||||
// Terms of Service. Public, guest-viewable (see ALWAYS_PUBLIC in router.js).
|
||||
// General legal template written to match what Caelum actually does - not a
|
||||
// General legal template written to match what Caelum actually does, not a
|
||||
// substitute for attorney review. Governing entity: Extant 2000 LLC (VA).
|
||||
import { RouterLink } from 'vue-router';
|
||||
import LegalFooter from '../components/LegalFooter.vue';
|
||||
@@ -71,8 +71,8 @@ const EFFECTIVE = 'July 20, 2026';
|
||||
into these Terms by reference.</p>
|
||||
|
||||
<h2>7. Content moderation and removal</h2>
|
||||
<p>We do not pre-screen User Content, but we may — at our discretion and without prior
|
||||
notice — remove or restrict any content, and suspend or terminate any account, that we
|
||||
<p>We do not pre-screen User Content, but we may, at our discretion and without prior
|
||||
notice, remove or restrict any content, and suspend or terminate any account, that we
|
||||
believe violates these Terms, the Community Guidelines, or applicable law, or that
|
||||
creates risk or legal exposure for Caelum or others. You can report content to us using
|
||||
the in-app <strong>Report</strong> action or by emailing
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Lightweight Nox syntax highlighter for static code previews (landing
|
||||
// page, docs, examples page). Matches the palette used by the IDE.
|
||||
// Not suitable for interactive editing - for that use the CodeMirror mode
|
||||
// Not suitable for interactive editing; for that use the CodeMirror mode
|
||||
// in ./language.js.
|
||||
|
||||
const HARD_KEYWORDS = new Set([
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
// Tiny markdown renderer used by the IDE doc modal and the standalone
|
||||
// /nox/docs page. Handles enough of the format to read our own docs:
|
||||
// headings, fenced code, inline code, bullet lists, paragraphs, bold,
|
||||
// links, and pipe tables. Not spec-conformant - never feed it untrusted
|
||||
// links, and pipe tables. Not spec-conformant; never feed it untrusted
|
||||
// markdown.
|
||||
|
||||
function escape(s) {
|
||||
// Escape quotes too: inline() interpolates link hrefs/titles into double-quoted
|
||||
// attributes, so an unescaped " in a [label](href) lets crafted markdown break
|
||||
// out of the attribute and inject event handlers (DOM-XSS). Matters because the
|
||||
// Lab renders LLM output through this - a prompt-injection surface.
|
||||
// Lab renders LLM output through this; a prompt-injection surface.
|
||||
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
||||
.replace(/"/g, '"').replace(/'/g, ''');
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// Run with `node --test` (no Vite, no vitest). Vite-specific
|
||||
// `import.meta.env.*` reads in the source files evaluate to undefined
|
||||
// here, which is fine — the helpers fall through to their default
|
||||
// here, which is fine; the helpers fall through to their default
|
||||
// branches (Sentry off-by-default outside a Vite build).
|
||||
|
||||
import { test } from 'node:test';
|
||||
@@ -63,7 +63,7 @@ test('client log: error with an Error instance is not stringified into [object O
|
||||
try {
|
||||
log.error('wrap:', new Error('inner'));
|
||||
assert.equal(c.out.error.length, 1);
|
||||
// Console.error preserves Error objects — what matters is the call
|
||||
// Console.error preserves Error objects; what matters is the call
|
||||
// happened with both args, which captureConsole joins with ' '.
|
||||
assert.match(c.out.error[0], /inner|Error/);
|
||||
} finally { c.restore(); }
|
||||
|
||||
@@ -18,7 +18,7 @@ function buildMeta() {
|
||||
const META = buildMeta();
|
||||
|
||||
// Sentry sourcemap upload + release tagging. Only runs when SENTRY_AUTH_TOKEN
|
||||
// is set in the build env — meaning local `npm run build` stays fast and
|
||||
// is set in the build env, meaning local `npm run build` stays fast and
|
||||
// silent, while a release build (with the token set) uploads sourcemaps so
|
||||
// the dashboard shows readable stacks.
|
||||
// org+project default to the public DSN's IDs.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# Caelum — PRODUCTION stack for the OVH VPS (135.148.121.177).
|
||||
# Caelum: PRODUCTION stack for the OVH VPS (135.148.121.177).
|
||||
#
|
||||
# Unlike docker-compose.yml (local: builds from source, publishes a host port),
|
||||
# this PULLS the prebuilt image from the GitLab Container Registry and joins the
|
||||
@@ -6,7 +6,7 @@
|
||||
# the `caelum` container by service name on :3000.
|
||||
#
|
||||
# Routing + TLS are handled by a plain Traefik v3 (Docker-provider label
|
||||
# routing + Let's Encrypt HTTP-01) — see the `edge` stack on the box. The
|
||||
# routing + Let's Encrypt HTTP-01); see the `edge` stack on the box. The
|
||||
# traefik.* labels on the caelum service below declare the router/cert. The app
|
||||
# container exposes NO host port; it's only reachable inside the `web` network.
|
||||
# The MySQL containers are on a private internal network only.
|
||||
@@ -89,7 +89,7 @@ services:
|
||||
driver: json-file
|
||||
options: { max-size: "10m", max-file: "3" }
|
||||
|
||||
# SpaceDB — the read-only NASA/JPL catalog (~1.5M asteroids/comets). Separate
|
||||
# SpaceDB: the read-only NASA/JPL catalog (~1.5M asteroids/comets). Separate
|
||||
# MySQL instance/volume from the app DB; the app connects via MYSQL_SPACEDB_*.
|
||||
# Provisioned from its own env_file so MYSQL_DATABASE=caelum_spacedb doesn't
|
||||
# collide with caelum-db's caelum_app. Data loaded from sql/spacedb.sql.
|
||||
@@ -116,7 +116,7 @@ services:
|
||||
driver: json-file
|
||||
options: { max-size: "10m", max-file: "3" }
|
||||
|
||||
# The edge Traefik's `web` network already exists on the VPS — join it, don't
|
||||
# The edge Traefik's `web` network already exists on the VPS, so join it, don't
|
||||
# create it (`docker network create web` is part of edge setup).
|
||||
# `internal` is private to this stack (app ↔ db); not exposed to other products.
|
||||
networks:
|
||||
|
||||
+1
-1
@@ -58,7 +58,7 @@ services:
|
||||
MYSQL_USER: ${MYSQL_USER:-caelum}
|
||||
MYSQL_PASSWORD: ${MYSQL_PASSWORD:-change-me}
|
||||
MYSQL_DATABASE: ${MYSQL_DATABASE:-caelum_app}
|
||||
# SpaceDB (optional — leave empty to disable /spacedb routes)
|
||||
# SpaceDB (optional; leave empty to disable /spacedb routes)
|
||||
MYSQL_SPACEDB_HOST: db
|
||||
MYSQL_SPACEDB_PORT: 3306
|
||||
MYSQL_SPACEDB_USER: ${MYSQL_USER:-caelum}
|
||||
|
||||
+9
-9
@@ -1,8 +1,8 @@
|
||||
// Caelum lint config — minimal on purpose.
|
||||
// Caelum lint config: minimal on purpose.
|
||||
//
|
||||
// CLAUDE.md says "no over-engineering." This config exists to catch the
|
||||
// drift that bit us tonight (unused vars, unreachable branches, broken
|
||||
// template references in Vue) — NOT to enforce style. There is no
|
||||
// template references in Vue), NOT to enforce style. There is no
|
||||
// formatter; do not add one.
|
||||
//
|
||||
// Run: npm run lint # report
|
||||
@@ -30,28 +30,28 @@ const baseRules = {
|
||||
'no-cond-assign': ['error', 'except-parens'],
|
||||
// Stop the `==` vs `===` foot-gun.
|
||||
'eqeqeq': ['warn', 'always', { null: 'ignore' }],
|
||||
// Catches `await` inside a sync function — common when refactoring.
|
||||
// Catches `await` inside a sync function, common when refactoring.
|
||||
'no-async-promise-executor': 'error',
|
||||
// Catches dead promises (no .then/.catch and not awaited).
|
||||
'no-unused-expressions': ['warn', {
|
||||
allowShortCircuit: true,
|
||||
allowTernary: true,
|
||||
}],
|
||||
// Off — Node 22 introduced this and it nags about every `throw new Error(msg)`
|
||||
// Off: Node 22 introduced this and it nags about every `throw new Error(msg)`
|
||||
// unless you adopt the `cause` option. Not worth a codebase-wide retrofit.
|
||||
'preserve-caught-error': 'off',
|
||||
// Treat as warning — usually fine but sometimes you legitimately reassign
|
||||
// Treat as warning: usually fine but sometimes you legitimately reassign
|
||||
// before an early return; the lint produces a lot of false positives on
|
||||
// multi-branch route handlers.
|
||||
'no-useless-assignment': 'off',
|
||||
};
|
||||
|
||||
// Vue-specific rules — catch broken template references like the ones the
|
||||
// Vue-specific rules: catch broken template references like the ones the
|
||||
// dead-code report found (`@click="addMentionedTarget(name)"` where the fn
|
||||
// doesn't exist). vue/no-undef-components catches typo'd component names.
|
||||
const vueRules = {
|
||||
...vue.configs['flat/recommended'].rules,
|
||||
// Allow multi-word component names — view-style names ("Research") are fine.
|
||||
// Allow multi-word component names: view-style names ("Research") are fine.
|
||||
'vue/multi-word-component-names': 'off',
|
||||
// We use very long template lines for grid/inline forms; don't bikeshed.
|
||||
'vue/max-attributes-per-line': 'off',
|
||||
@@ -75,7 +75,7 @@ export default [
|
||||
'sql/**',
|
||||
'db.sqlite3',
|
||||
'**/*.min.js',
|
||||
'nox/parser/src/grammar/**', // chevrotain DSL — false positives galore
|
||||
'nox/parser/src/grammar/**', // chevrotain DSL: false positives galore
|
||||
],
|
||||
},
|
||||
|
||||
@@ -119,7 +119,7 @@ export default [
|
||||
ecmaVersion: 2024,
|
||||
sourceType: 'module',
|
||||
globals: {
|
||||
// Standard browser globals — the Vue files run in the DOM.
|
||||
// Standard browser globals: the Vue files run in the DOM.
|
||||
console: 'readonly', setTimeout: 'readonly', setInterval: 'readonly',
|
||||
clearTimeout: 'readonly', clearInterval: 'readonly',
|
||||
fetch: 'readonly', AbortController: 'readonly', AbortSignal: 'readonly',
|
||||
|
||||
@@ -118,17 +118,30 @@ Real-hardware mode is intentionally unavailable - the REPL re-executes the cumul
|
||||
|
||||
### `nox help`
|
||||
|
||||
Print usage.
|
||||
Print usage and exit 0. `--help` and `-h` do the same from any position. An
|
||||
unknown command, or a command called without the file it needs, prints the same
|
||||
usage text but exits 1.
|
||||
|
||||
## Flags
|
||||
|
||||
| Flag | Applies to | Effect |
|
||||
| -------------- | ---------- | ------------------------------------- |
|
||||
| `--quiet`, `-q`| `run` | Print only the `N ops` summary |
|
||||
| `--help`, `-h` | any | Print usage and exit 0 |
|
||||
|
||||
## Exit codes
|
||||
|
||||
| Code | Meaning |
|
||||
| ---- | ----------------------------------------------- |
|
||||
| 0 | Success |
|
||||
| 1 | Type check failed, or runtime failed under run/ops |
|
||||
| 2 | File not found |
|
||||
| 3 | Runtime error during execution |
|
||||
| 4 | Parse error |
|
||||
| Code | Meaning |
|
||||
| ---- | ---------------------------------------------------- |
|
||||
| 0 | Success |
|
||||
| 1 | Type check failed, or the CLI was called wrong |
|
||||
| 2 | File not found |
|
||||
| 3 | Runtime error during execution |
|
||||
| 4 | Parse error |
|
||||
|
||||
`check` and `run` share exit 1 for diagnostics, so a CI gate can treat any
|
||||
non-zero as "do not ship this program". If you need to tell a bad script from a
|
||||
bad invocation, 2, 3 and 4 are unambiguous.
|
||||
|
||||
## CI integration
|
||||
|
||||
|
||||
+125
-29
@@ -2,7 +2,12 @@
|
||||
|
||||
Mounted at `/api/nox`. Source: [server/src/routes/nox.js](../../../server/src/routes/nox.js).
|
||||
|
||||
All endpoints accept and return JSON unless noted. Authentication piggybacks on the Observatory auth layer; the routes themselves do not require auth in the current build.
|
||||
All endpoints accept and return JSON unless noted. `/check`, the two mock-mode
|
||||
run endpoints, `/examples`, `/docs-search` and `/docs` are open, so the "try Nox
|
||||
without signing up" console works for anonymous visitors. Running in `"real"`
|
||||
mode is the exception: it reaches live telescope drivers, so it requires both an
|
||||
`Authorization: Bearer <token>` header and an explicit `confirmed: true` in the
|
||||
request body.
|
||||
|
||||
## `POST /api/nox/check`
|
||||
|
||||
@@ -20,14 +25,23 @@ Type-check a program. Does not execute.
|
||||
{ "diagnostics": [] }
|
||||
```
|
||||
|
||||
**Response 400** when `source` is missing or not a string.
|
||||
|
||||
Each diagnostic:
|
||||
|
||||
```json
|
||||
{ "line": 3, "column": 7, "message": "..." }
|
||||
```
|
||||
|
||||
A program the parser cannot read at all still returns 200, with one diagnostic
|
||||
that has no `line` or `column`:
|
||||
|
||||
```json
|
||||
{ "diagnostics": [{ "severity": "error", "message": "..." }] }
|
||||
```
|
||||
|
||||
That keeps a hard parse error rendering inline in the editor gutter instead of
|
||||
surfacing as a 500. Reserve 400 for a malformed request: `source` missing, or
|
||||
not a string.
|
||||
|
||||
## `POST /api/nox/run`
|
||||
|
||||
Type-check, then execute. Buffers the full op log and returns it at the end.
|
||||
@@ -37,39 +51,57 @@ Type-check, then execute. Buffers the full op log and returns it at the end.
|
||||
```json
|
||||
{
|
||||
"source": "...",
|
||||
"mode": "mock", // or "real"
|
||||
"policy": { "ticks": 1, "intervalMs": 0 } // optional
|
||||
"mode": "mock",
|
||||
"policy": { "ticks": 1, "intervalMs": 0 }
|
||||
}
|
||||
```
|
||||
|
||||
`mode` is `"mock"` (default) or `"real"`; `policy` is optional. Real mode also
|
||||
requires `"confirmed": true` in the body.
|
||||
|
||||
**Response 200**
|
||||
|
||||
```json
|
||||
{
|
||||
"log": [
|
||||
{ "kind": "T:Astra-1", "op": "slew", "args": {"target": {...}}, "t": 1737000000000 },
|
||||
...
|
||||
]
|
||||
{ "kind": "T:Astra-1", "op": "slew", "args": { "target": {} }, "t": 1737000000000 }
|
||||
],
|
||||
"summary": { "T:Astra-1": { "slew": 1, "expose": 5 } }
|
||||
}
|
||||
```
|
||||
|
||||
**Response 400** for type errors, runtime errors, or missing source. The body contains `{ "error": "<message>", "log": [...] }` with whatever ops ran before the failure.
|
||||
`summary` counts ops per resource so a client can render "1 slew, 5 exposures"
|
||||
without walking the log itself.
|
||||
|
||||
**Response 400** for type errors, runtime errors, an unknown `mode`, or a
|
||||
missing `source`. The body is `{ "error": "<message>", "log": [...] }`, carrying
|
||||
whatever ops ran before the failure.
|
||||
|
||||
**Response 403** when `mode` is `"real"` and the body omits `confirmed: true`.
|
||||
The body includes a `hint` describing the dry-run-then-confirm flow.
|
||||
|
||||
**Response 401** when `mode` is `"real"`, `confirmed` is set, and the bearer
|
||||
token is missing or invalid. A suspended account gets 403 from the auth layer.
|
||||
|
||||
## `POST /api/nox/run-stream`
|
||||
|
||||
Same as `/run` but streams Server-Sent Events. Use when the program is long-running or the client wants to render the op log live.
|
||||
Same as `/run`, but streams Server-Sent Events. Use it when the program is
|
||||
long-running or the client wants to render the op log live.
|
||||
|
||||
**Body** identical to `/run`.
|
||||
**Body** identical to `/run`, and gated the same way.
|
||||
|
||||
**Response** `text/event-stream`.
|
||||
**Response** `text/event-stream`. Errors raised before the stream opens (bad
|
||||
`source`, unknown `mode`, unconfirmed real mode) come back as JSON with the
|
||||
status codes listed under `/run`. Once the stream opens the status is 200, and a
|
||||
failure arrives as an `error` event.
|
||||
|
||||
**Events**
|
||||
|
||||
| Event | Data shape | Meaning |
|
||||
| ------- | ----------------------------------- | ----------------------------- |
|
||||
| `op` | `{ kind, op, args, t }` | One operation executed. |
|
||||
| `done` | `{ count }` | Program finished cleanly. |
|
||||
| `error` | `{ message }` | Program threw. |
|
||||
| Event | Data shape | Meaning |
|
||||
| ------- | ------------------------- | ------------------------- |
|
||||
| `op` | `{ kind, op, args, t }` | One operation executed. |
|
||||
| `done` | `{ count }` | Program finished cleanly. |
|
||||
| `error` | `{ message }` | Program threw. |
|
||||
|
||||
**Example consumer (browser fetch)**
|
||||
|
||||
@@ -95,41 +127,105 @@ while (true) {
|
||||
}
|
||||
```
|
||||
|
||||
`EventSource` will not work here, because it can only issue GET requests and a
|
||||
program source is too long to survive a query string.
|
||||
|
||||
## `GET /api/nox/examples`
|
||||
|
||||
Return the bundled example programs.
|
||||
Return the bundled example programs, sorted by filename.
|
||||
|
||||
**Response 200**
|
||||
|
||||
```json
|
||||
[
|
||||
{ "name": "01-hello-slew.nox", "source": "..." },
|
||||
{ "name": "02-messier-marathon.nox", "source": "..." },
|
||||
...
|
||||
{ "name": "02-messier-marathon.nox", "source": "..." }
|
||||
]
|
||||
```
|
||||
|
||||
Useful for the Vue console's example picker. Files are read from `nox/examples/*.nox` on each request.
|
||||
This backs the Vue console's example picker. Files are read from
|
||||
`nox/examples/*.nox` on each request, so editing an example shows up without a
|
||||
restart.
|
||||
|
||||
## `GET /api/nox/docs-search`
|
||||
|
||||
Full-text search over the markdown in `nox/docs`. The index is built on the
|
||||
first request and cached in-process until the docs directory's mtime advances.
|
||||
|
||||
**Query**
|
||||
|
||||
| Param | Default | Notes |
|
||||
| ------- | ------- | ------------------------ |
|
||||
| `q` | none | Blank `q` returns empty results, not an error. |
|
||||
| `limit` | `10` | Clamped to 1–50. |
|
||||
|
||||
**Response 200**
|
||||
|
||||
```json
|
||||
{
|
||||
"results": [
|
||||
{
|
||||
"score": 12.4,
|
||||
"path": "book/08-parallel-and-rollback.md",
|
||||
"anchor": "rollback-handlers",
|
||||
"title": "Parallel and Rollback",
|
||||
"sectionTitle": "Rollback handlers",
|
||||
"snippet": "…every branch registers its own on-rollback…"
|
||||
}
|
||||
],
|
||||
"total": 7,
|
||||
"indexed": 21
|
||||
}
|
||||
```
|
||||
|
||||
`total` is the match count before `limit` is applied; `indexed` is the number of
|
||||
passages in the index.
|
||||
|
||||
**Response 503** when the host has no docs directory, which is the case for
|
||||
deployments that ship the server without `nox/docs`.
|
||||
|
||||
## `GET /api/nox/docs/<path>`
|
||||
|
||||
Serve one documentation file as `text/markdown`. The path is relative to
|
||||
`nox/docs`, so `/api/nox/docs/book/01-why-nox.md` returns that chapter.
|
||||
|
||||
**Response 400** for an undecodable path, or one that escapes `nox/docs` after
|
||||
resolution. **Response 404** for a path that is missing, or is a directory.
|
||||
|
||||
## Modes
|
||||
|
||||
`mode: "mock"` runs with the in-memory mock driver. Operations log but do not touch hardware. Use for development and dry runs.
|
||||
`mode: "mock"` runs with the in-memory mock driver. Operations log but do not
|
||||
touch hardware. Use it for development and dry runs.
|
||||
|
||||
`mode: "real"` builds a driver that resolves resource names against the `telescopes` and `enclosures` tables and forwards calls to `telescope-control.slewTo`, `external-drivers.domeAction`, and similar services. Operations that do not yet have a backing service log without effect.
|
||||
`mode: "real"` builds a driver that resolves resource names against the
|
||||
`telescopes` and `enclosures` tables and forwards calls to
|
||||
`telescope-control.slewTo`, `external-drivers.domeAction`, and similar services.
|
||||
Operations with no backing service yet log without effect.
|
||||
|
||||
Real mode carries two independent gates, so neither a UI bug nor a hand-rolled
|
||||
client can slew a telescope by accident: the request must be authenticated, and
|
||||
it must carry `confirmed: true`. The intended flow is to run the program in mock
|
||||
mode, show the operator the op log, and resend with the flag set.
|
||||
|
||||
## Policy options
|
||||
|
||||
When the program contains a `policy "..." { ... }` block, the runtime evaluates rules on a tick loop.
|
||||
When the program contains a `policy "..." { ... }` block, the runtime evaluates
|
||||
rules on a tick loop.
|
||||
|
||||
```json
|
||||
{ "policy": { "ticks": 600, "intervalMs": 1000 } }
|
||||
```
|
||||
|
||||
Default `ticks: 1, intervalMs: 0` runs each rule once on entry. Higher values run as a daemon. `halt` inside a rule aborts the loop.
|
||||
The default, `ticks: 1, intervalMs: 0`, runs each rule once on entry. Higher
|
||||
values run as a daemon. A `halt` inside a rule aborts the loop.
|
||||
|
||||
## Errors
|
||||
|
||||
| HTTP | Cause |
|
||||
| ---- | --------------------------------------------------------- |
|
||||
| 400 | Missing source, source not a string, type errors, runtime errors |
|
||||
| 500 | Bug in the runtime; check server logs |
|
||||
| HTTP | Cause |
|
||||
| ---- | ----- |
|
||||
| 400 | Missing source, source not a string, unknown mode, type error, runtime error, or a docs path that escapes the docs root |
|
||||
| 401 | Real mode without a valid bearer token |
|
||||
| 403 | Real mode without `confirmed: true` |
|
||||
| 404 | Docs path not found |
|
||||
| 500 | Bug in the runtime or the docs index; check server logs |
|
||||
| 503 | Docs directory absent on this host |
|
||||
|
||||
@@ -21,20 +21,25 @@ Execute a Nox program against a driver.
|
||||
|
||||
```js
|
||||
const { log } = await run(source, {
|
||||
strict: true, // run checkSource first; throw on diagnostics
|
||||
driver: customDriver, // override the default mock driver
|
||||
strict: true, // default: type-check first, throw on diagnostics
|
||||
driver: customDriver, // default: a fresh mock driver
|
||||
onOp: entry => ..., // called synchronously for every op
|
||||
policy: { ticks: 60, intervalMs: 1000 }, // for policy daemons
|
||||
policy: { ticks: 60, intervalMs: 1000 }, // default: {}, rules run once
|
||||
});
|
||||
```
|
||||
|
||||
Returns an object with `log: [opEntry]`. Each entry shape:
|
||||
Every option has a default, so `await run(source)` type-checks against the mock
|
||||
driver and returns the op log. Returns an object with `log: [opEntry]`, one
|
||||
entry per operation:
|
||||
|
||||
```js
|
||||
{ kind: "T:Astra-1", op: "slew", args: { target: ... }, t: 1737000000000 }
|
||||
```
|
||||
|
||||
If `strict` is true and the source has diagnostics, `run` throws before executing.
|
||||
With `strict` left at its default, a source with diagnostics makes `run` throw
|
||||
before anything executes, and the thrown `Error` message lists every diagnostic.
|
||||
Pass `strict: false` to skip the check, which is what the REPL does after it has
|
||||
already called `checkSource` on the same buffer.
|
||||
|
||||
## `checkSource(source) -> { diagnostics }`
|
||||
|
||||
@@ -50,9 +55,19 @@ for (const d of diagnostics) {
|
||||
A diagnostic shape:
|
||||
|
||||
```js
|
||||
{ line: 3, column: 7, message: "..." }
|
||||
{
|
||||
line: 3,
|
||||
column: 7,
|
||||
message: "unknown resource kind: telescop",
|
||||
suggest: "did you mean 'telescope'?", // optional
|
||||
seeAlso: [{ title: "Resources", href: "..." }], // optional
|
||||
}
|
||||
```
|
||||
|
||||
`suggest` and `seeAlso` are present only where the checker has a specific fix to
|
||||
offer. `nox check` and the REPL print them as `hint:` and `see:` lines; a custom
|
||||
tool should treat both as optional.
|
||||
|
||||
## `parseSource(source) -> Cst`
|
||||
|
||||
Returns the Chevrotain CST. Useful for tooling that walks the syntax tree.
|
||||
|
||||
@@ -180,7 +180,7 @@ export const MODULES = new Proxy(STATIC_MODULES, {
|
||||
// ---------- Implicit context providers ----------
|
||||
// Each provider exposes a Map<name, Type> of field bindings that are
|
||||
// brought into scope when their head identifier appears in a requires or
|
||||
// safety predicate. `time` and resource kinds don't add bindings — their
|
||||
// safety predicate. `time` and resource kinds don't add bindings; their
|
||||
// args reference globals or named resources directly.
|
||||
export const CONTEXT_PROVIDERS = {
|
||||
weather: () => Weather.fields,
|
||||
|
||||
@@ -744,7 +744,7 @@ function iterableElement(t) {
|
||||
}
|
||||
|
||||
// Narrow types in a scope based on a condition known to be true.
|
||||
// Currently handles `x?` (presence test on identifier) — narrows Optional<T> to T.
|
||||
// Currently handles `x?` (presence test on identifier): narrows Optional<T> to T.
|
||||
function narrowOnTrue(cond, scope) {
|
||||
if (!cond) return scope;
|
||||
if (cond.type === "Optional" && cond.expr && cond.expr.type === "Ident") {
|
||||
|
||||
@@ -69,10 +69,10 @@ export const After = kw("After", "after");
|
||||
export const Before = kw("Before", "before");
|
||||
|
||||
// Soft keywords (matched as Identifier by the lexer; parser uses image checks):
|
||||
// step — in for-loop step clause
|
||||
// reached — in when-rule trailing word
|
||||
// rollback — in `on rollback { ... }` (also valid as a callable, e.g. `rollback()`)
|
||||
// telescope / dome / camera / filter_wheel / focuser — resource kinds in `use ...`
|
||||
// step - in for-loop step clause
|
||||
// reached - in when-rule trailing word
|
||||
// rollback - in `on rollback { ... }` (also valid as a callable, e.g. `rollback()`)
|
||||
// telescope / dome / camera / filter_wheel / focuser - resource kinds in `use ...`
|
||||
|
||||
// ---------- literals ----------
|
||||
// Unit-suffixed numbers must come BEFORE NumberLit so the lexer doesn't
|
||||
@@ -175,7 +175,7 @@ export function tokenize(source) {
|
||||
const result = NoxLexer.tokenize(source);
|
||||
if (result.errors.length > 0) {
|
||||
const e = result.errors[0];
|
||||
throw new Error(`Lex error at ${e.line}:${e.column} — ${e.message}`);
|
||||
throw new Error(`Lex error at ${e.line}:${e.column}: ${e.message}`);
|
||||
}
|
||||
return result.tokens;
|
||||
}
|
||||
|
||||
@@ -274,7 +274,7 @@ export class NoxParser extends CstParser {
|
||||
$.SUBRULE($.Block);
|
||||
});
|
||||
|
||||
// `on rollback { ... }` — `rollback` is a soft keyword (Identifier with that image).
|
||||
// `on rollback { ... }`; `rollback` is a soft keyword (Identifier with that image).
|
||||
$.RULE("OnRollbackStmt", () => {
|
||||
$.CONSUME(T.On);
|
||||
$.CONSUME(T.Identifier); // semantic: image must be "rollback"
|
||||
@@ -494,7 +494,7 @@ export class NoxParser extends CstParser {
|
||||
|
||||
// Named arg: `identifier : expr`. Positional: bare `expr`.
|
||||
// We need to distinguish without true backtracking. An `Identifier`
|
||||
// followed by `:` (but NOT `::` or `:=` — neither exists here) is a name.
|
||||
// followed by `:` (but NOT `::` or `:=`, neither exists here) is a name.
|
||||
$.RULE("Arg", () => {
|
||||
$.OR([
|
||||
{
|
||||
@@ -589,7 +589,7 @@ export class NoxParser extends CstParser {
|
||||
]);
|
||||
});
|
||||
|
||||
// `(T1, T2[, ...])` — at least two elements so it doesn't collide with a
|
||||
// `(T1, T2[, ...])`: at least two elements so it doesn't collide with a
|
||||
// parenthesized type expression (we don't currently support those).
|
||||
$.RULE("TupleType", () => {
|
||||
$.CONSUME(T.LParen);
|
||||
@@ -659,7 +659,7 @@ function isLambdaAhead($) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// True at the start of a statement boundary — used to know when `return`
|
||||
// True at the start of a statement boundary, used to know when `return`
|
||||
// or `yield` has no expression operand.
|
||||
function startsBlockEnd($) {
|
||||
const t = $.LA(1).tokenType;
|
||||
@@ -681,7 +681,7 @@ function isTypedConstructorAhead($) {
|
||||
depth--;
|
||||
if (depth === 0) return $.LA(i + 1).tokenType === T.LParen;
|
||||
} else if (
|
||||
// tokens that can't appear inside a type-arg list — fail fast
|
||||
// tokens that can't appear inside a type-arg list: fail fast
|
||||
tok.tokenType === T.Semicolon ||
|
||||
tok.tokenType === T.LBrace ||
|
||||
tok.tokenType === T.RBrace
|
||||
@@ -702,7 +702,7 @@ export function parse(tokens) {
|
||||
if (parserInstance.errors.length > 0) {
|
||||
const e = parserInstance.errors[0];
|
||||
const loc = e.token ? `${e.token.startLine}:${e.token.startColumn}` : "?";
|
||||
throw new Error(`Parse error at ${loc} — ${e.message}`);
|
||||
throw new Error(`Parse error at ${loc}: ${e.message}`);
|
||||
}
|
||||
return cst;
|
||||
}
|
||||
|
||||
@@ -144,7 +144,7 @@ export function assignable(expected, actual) {
|
||||
if (expected.kind === "Prim" && expected.name === "Float"
|
||||
&& actual.kind === "Prim" && actual.name === "Int") return true;
|
||||
if (expected.kind === "Optional" && assignable(expected.element, actual)) return true;
|
||||
// Optional<T> is NOT implicitly assignable to T — callers must guard with
|
||||
// Optional<T> is NOT implicitly assignable to T; callers must guard with
|
||||
// `if x? { ... }` so flow-sensitive narrowing peels the Optional.
|
||||
if (expected.kind === "Union") {
|
||||
return expected.members.some(m => assignable(m, actual));
|
||||
|
||||
@@ -128,7 +128,7 @@ function doParse(src) {
|
||||
// appended, then we re-check + re-run the whole buffer fresh on the
|
||||
// mock driver. The new op log is diffed against the prior run so we
|
||||
// only display ops produced by the latest input. Mock driver is pure
|
||||
// — re-execution has no side effects — so this is cheap and lets the
|
||||
// (re-execution has no side effects), so this is cheap and lets the
|
||||
// REPL keep persistent scope across inputs (use, let, fn).
|
||||
//
|
||||
// Type errors don't commit the line to the buffer, so the user can
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//
|
||||
// v0.1 ships a small hand-verified subset. Real deployments should drop a
|
||||
// JSON catalog into nox/runtime/catalogs/<name>.json (loaded lazily via
|
||||
// loadCatalogFile) — that file overrides / extends the builtin map.
|
||||
// loadCatalogFile); that file overrides / extends the builtin map.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "caelum",
|
||||
"version": "0.4.4",
|
||||
"version": "0.5.1",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "caelum",
|
||||
"version": "0.4.4",
|
||||
"version": "0.5.1",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^10.0.1",
|
||||
|
||||
@@ -98,16 +98,16 @@ let buffer = '';
|
||||
let statementCount = 0;
|
||||
|
||||
for await (const line of rl) {
|
||||
// Skip the dump's own header pragmas — we emit our own per-chunk header.
|
||||
// Skip the dump's own header pragmas; we emit our own per-chunk header.
|
||||
if (buffer === '' && /^\s*SET (FOREIGN_KEY_CHECKS|NAMES)\b/.test(line)) continue;
|
||||
// Skip top-level `-- ...` comments at start of buffer (they'd get orphaned).
|
||||
// (Comments INSIDE a buffered statement are fine — they ride along.)
|
||||
// (Comments INSIDE a buffered statement are fine; they ride along.)
|
||||
|
||||
buffer += line + '\n';
|
||||
|
||||
// A SQL statement ends when a line ends with `;`.
|
||||
// mysql2 escape() encodes literal newlines inside strings as \n, so a real
|
||||
// newline cannot appear inside a quoted value — safe to split on \n-after-`;`.
|
||||
// newline cannot appear inside a quoted value, safe to split on \n-after-`;`.
|
||||
if (line.endsWith(';')) {
|
||||
const bufBytes = Buffer.byteLength(buffer);
|
||||
// Rotate to next chunk BEFORE writing if this statement would push us over,
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* The server code expects to run from the `server/` directory (so relative
|
||||
* paths like `./data/observatory.db` resolve), so we chdir before starting
|
||||
* the app. We keep this file free of top-level `await` and load the app via
|
||||
* dynamic import() — that keeps the async graph (the TLA in
|
||||
* dynamic import(). That keeps the async graph (the TLA in
|
||||
* src/config/database.js) self-contained, so the file stays safe to require()
|
||||
* from a CommonJS host without ERR_REQUIRE_ASYNC_MODULE.
|
||||
*/
|
||||
|
||||
@@ -6,6 +6,9 @@
|
||||
"author": "Paul Hitt",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "DB_KIND=${DB_KIND:-sqlite} node --watch src/index.js",
|
||||
"dev:mysql": "DB_KIND=mysql node --watch src/index.js",
|
||||
|
||||
@@ -59,10 +59,10 @@ export function translateDdl(mysqlDdl) {
|
||||
// KEY name (col, col) → drop (use CREATE INDEX separately)
|
||||
.replace(/(^|,)\s*UNIQUE\s+KEY\s+\w+\s*\(([^)]+)\)/gim, '$1 UNIQUE ($2)')
|
||||
.replace(/(^|,)\s*KEY\s+\w+\s*\([^)]+\)\s*(?=,|\s*\))/gim, '$1')
|
||||
// Strip MySQL-style FULLTEXT/SPATIAL key declarations (defensive - not
|
||||
// Strip MySQL-style FULLTEXT/SPATIAL key declarations (defensive, not
|
||||
// currently used in our schema but harmless).
|
||||
.replace(/(^|,)\s*(FULLTEXT|SPATIAL)\s+KEY\s+\w+\s*\([^)]+\)\s*(?=,|\s*\))/gim, '$1')
|
||||
// Column types. Order matters - match longest first.
|
||||
// Column types. Order matters: match longest first.
|
||||
.replace(/\bVARCHAR\s*\(\s*\d+\s*\)/gi, 'TEXT')
|
||||
.replace(/\bCHAR\s*\(\s*\d+\s*\)/gi, 'TEXT')
|
||||
.replace(/\bLONGTEXT\b/gi, 'TEXT')
|
||||
@@ -183,16 +183,16 @@ export const appPool = {
|
||||
};
|
||||
|
||||
// SpaceDB on SQLite. The catalog ships as a ~1.4 GB Django-schema SQLite
|
||||
// file (db.sqlite3 at the repo root) - the same source migrate.js pushes
|
||||
// file (db.sqlite3 at the repo root), the same source migrate.js pushes
|
||||
// into MySQL. In the SQLite dev path there's no MySQL to point at, so we
|
||||
// read that file directly and expose a mysql2-compatible pool shim. The
|
||||
// /api/spacedb route only ever does `const [rows] = await pool.query(...)`
|
||||
// with portable SQL (SELECT, ?, LIMIT, backtick quotes - all valid in
|
||||
// with portable SQL (SELECT, ?, LIMIT, backtick quotes; all valid in
|
||||
// SQLite), so it works unchanged.
|
||||
//
|
||||
// Resolution order: SPACEDB_SQLITE_PATH → SPACEDB_PATH (also used by
|
||||
// migrate.js) → <repoRoot>/db.sqlite3. If the file is absent we export
|
||||
// null so the route degrades to a clean 503 instead of crashing - same
|
||||
// null so the route degrades to a clean 503 instead of crashing; same
|
||||
// contract as a missing MySQL spacedb.
|
||||
function resolveSpacedbPath() {
|
||||
const override = process.env.SPACEDB_SQLITE_PATH || process.env.SPACEDB_PATH;
|
||||
@@ -236,7 +236,7 @@ export const spacedbPool = buildSqliteSpacedbPool();
|
||||
//
|
||||
// For fresh databases the translated DDL creates everything. For existing
|
||||
// databases (seeded before later columns landed) we run COLUMN_MIGRATIONS
|
||||
// via SQLite's PRAGMA table_info to add anything missing - same shape as
|
||||
// via SQLite's PRAGMA table_info to add anything missing, same shape as
|
||||
// the MySQL addColumnIfMissing path.
|
||||
export async function initDb() {
|
||||
const conn = open();
|
||||
@@ -253,7 +253,7 @@ export async function initDb() {
|
||||
// SQLite ALTER doesn't support every MySQL spec verbatim. Most fail
|
||||
// due to defaults referencing functions or NOT NULL without a default
|
||||
// on a populated table. Log and continue so one bad row doesn't block
|
||||
// boot - callers handling that column will see NULL until it's set.
|
||||
// boot; callers handling that column will see NULL until it's set.
|
||||
log.warn(`[db-sqlite] column migration ${table}.${column} skipped: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,13 +3,13 @@
|
||||
// The HTTP server and background tick services start at boot *before*
|
||||
// bootDb()'s initDb() has finished applying the schema (initDb runs in the
|
||||
// background so /api/health is reachable while the DB is cold). Services
|
||||
// that query tables on their very first tick - public-feed, health-history -
|
||||
// that query tables on their very first tick (public-feed, health-history)
|
||||
// would otherwise race the `CREATE TABLE IF NOT EXISTS` DDL and log a
|
||||
// spurious "table doesn't exist" warning that surfaces in Sentry on every
|
||||
// cold start. They `await dbReady` (or `dbReady.then(...)`) before the first
|
||||
// query; index.js calls markDbReady() once initDb() succeeds.
|
||||
//
|
||||
// Only the first tick needs gating - by the time a service's interval fires
|
||||
// Only the first tick needs gating: by the time a service's interval fires
|
||||
// (15s/60s later) the idempotent DDL has long completed.
|
||||
|
||||
let resolveReady;
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// The canonical CREATE TABLE in schema-mysql.js already includes these
|
||||
// columns for fresh installs. This list exists for EXISTING databases
|
||||
// (Mysql production deploys or SQLite files seeded before the columns
|
||||
// landed) - each backend's initDb() walks the list and ALTER TABLEs in
|
||||
// landed); each backend's initDb() walks the list and ALTER TABLEs in
|
||||
// anything missing.
|
||||
//
|
||||
// Type spellings here are MySQL-flavored but pass through to SQLite via
|
||||
|
||||
@@ -252,7 +252,8 @@ CREATE TABLE IF NOT EXISTS observations (
|
||||
-- Research targets: science-driven observation candidates pulled from
|
||||
-- external catalogs (MPC for NEOs, NASA Exoplanet Archive for transits,
|
||||
-- AAVSO for variable stars). The Research view (/research) renders these
|
||||
-- as actionable cards; "Schedule" creates an Observation snapshot. We
|
||||
-- as cards with a Schedule button; "Schedule" creates an Observation
|
||||
-- snapshot. We
|
||||
-- cache the targets in our own table rather than hitting external APIs
|
||||
-- on every page load - a background refresher (TODO) keeps them current.
|
||||
CREATE TABLE IF NOT EXISTS research_targets (
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* Idempotent database upgrade.
|
||||
*
|
||||
* Run this after deploying code that changes the schema (new tables, new
|
||||
* columns). Safe to run repeatedly - it never drops or rewrites data.
|
||||
* columns). Safe to run repeatedly: it never drops or rewrites data.
|
||||
*
|
||||
* node src/db-upgrade.js # upgrade the active backend (DB_KIND)
|
||||
* npm run db:upgrade # from server/
|
||||
|
||||
+11
-11
@@ -1,4 +1,4 @@
|
||||
// MUST be the first import - populates process.env before auth.js (and
|
||||
// MUST be the first import: populates process.env before auth.js (and
|
||||
// anything else) evaluates JWT_SECRET / ANTHROPIC_API_KEY / MYSQL_* at
|
||||
// module load time. ESM hoists imports and runs side-effects in source
|
||||
// order, so putting the dotenv call in a separate preload module is
|
||||
@@ -58,7 +58,7 @@ import { initSentry } from './services/sentry.js';
|
||||
|
||||
// The version, read from server/package.json at boot. npm_package_version is
|
||||
// only set when started via npm; the Docker image runs `node server.js`, so a
|
||||
// hardcoded fallback is what actually gets served - and it goes stale silently
|
||||
// hardcoded fallback is what actually gets served, and it goes stale silently
|
||||
// on every release. Read the real thing instead.
|
||||
function readPkgVersion() {
|
||||
try {
|
||||
@@ -70,17 +70,17 @@ const PKG_VERSION = readPkgVersion();
|
||||
|
||||
// Fire Sentry init early. Async because @sentry/node is lazy-imported only
|
||||
// when actually enabled (NODE_ENV=production or ENABLE_SENTRY=true), so
|
||||
// tests + dev don't pay the load cost. Fire-and-forget - by the time the
|
||||
// tests + dev don't pay the load cost. Fire-and-forget: by the time the
|
||||
// first error happens, init has long since completed.
|
||||
initSentry({ version: PKG_VERSION || 'unknown' }).catch(() => {});
|
||||
|
||||
const app = express();
|
||||
const server = createServer(app);
|
||||
|
||||
// Explicit CORS allowlist instead of a wildcard - see config/origins.js, which
|
||||
// Explicit CORS allowlist instead of a wildcard. See config/origins.js, which
|
||||
// also serves routes that need to build an absolute URL back into the SPA.
|
||||
function corsOrigin(origin, cb) {
|
||||
// No Origin header = same-origin, curl, or server-to-server - allow.
|
||||
// No Origin header = same-origin, curl, or server-to-server; allow.
|
||||
if (!origin || ALLOWED_ORIGINS.includes(origin)) return cb(null, true);
|
||||
cb(new Error('Not allowed by CORS'));
|
||||
}
|
||||
@@ -89,11 +89,11 @@ const io = new SocketIO(server, { cors: { origin: ALLOWED_ORIGINS } });
|
||||
app.set('io', io);
|
||||
|
||||
// Trust the first reverse-proxy hop so req.ip reflects X-Forwarded-For
|
||||
// (the Traefik edge proxy in prod) - needed for accurate per-IP rate limiting.
|
||||
// (the Traefik edge proxy in prod), needed for accurate per-IP rate limiting.
|
||||
app.set('trust proxy', 1);
|
||||
|
||||
// Canonical host: 301 www.* → apex in production (SPA + API share one origin,
|
||||
// so this keeps a single canonical URL). Generic - strips a leading "www.".
|
||||
// so this keeps a single canonical URL). Generic: strips a leading "www.".
|
||||
app.use((req, res, next) => {
|
||||
const host = req.headers.host || '';
|
||||
if (process.env.NODE_ENV === 'production' && host.startsWith('www.')) {
|
||||
@@ -164,7 +164,7 @@ app.get('/api/health/history', async (req, res) => {
|
||||
res.json({ probes: rows });
|
||||
});
|
||||
|
||||
// External probe receiver - scripts/probe-uptime.mjs POSTs here from
|
||||
// External probe receiver: scripts/probe-uptime.mjs POSTs here from
|
||||
// cron/launchd so external observations end up in the same spark-bar.
|
||||
// Shared-secret only; if EXTERNAL_PROBE_SECRET is unset on the server
|
||||
// the endpoint refuses ALL requests (fail-closed). Same insert path
|
||||
@@ -326,7 +326,7 @@ const stopTelescopePositions = safeInterval('telescope-position', async () => {
|
||||
}, 1000, { unref: true });
|
||||
|
||||
// JSON error handler. LimitExceeded errors from services/limits.js
|
||||
// carry a structured `body` payload - pass it through verbatim so the
|
||||
// carry a structured `body` payload; pass it through verbatim so the
|
||||
// client can render "you hit the cap on archive.frames_per_user (200/200)"
|
||||
// without parsing the message string.
|
||||
app.use((err, req, res, next) => {
|
||||
@@ -345,7 +345,7 @@ const PORT = process.env.PORT || 3002;
|
||||
// retry with capped exponential backoff. /api/health stays at 503 until the
|
||||
// app DB becomes reachable. The previous behavior (process.exit on first
|
||||
// failure) caused docker compose to enter a tight restart loop on transient
|
||||
// MySQL outages - see TODOS.md item K.
|
||||
// MySQL outages. See TODOS.md item K.
|
||||
const NODE_ENV = process.env.NODE_ENV || 'development';
|
||||
server.listen(PORT, () => {
|
||||
log.info(`Caelum API running on http://localhost:${PORT} env=${NODE_ENV}`);
|
||||
@@ -396,7 +396,7 @@ async function autoSeedIfEmpty() {
|
||||
for (;;) {
|
||||
try {
|
||||
await initDb();
|
||||
// Schema is now applied - release the boot-time tick services that
|
||||
// Schema is now applied: release the boot-time tick services that
|
||||
// gate their first DB query on this (public-feed, health-history).
|
||||
markDbReady();
|
||||
if (attempt > 0) log.info(`[caelum] DB reachable after ${attempt + 1} attempts`);
|
||||
|
||||
@@ -13,7 +13,7 @@ function hashToken(t) { return crypto.createHash('sha256').update(t).digest('hex
|
||||
|
||||
// Methods that only read state. A `read`-scoped API token is allowed these;
|
||||
// anything that mutates requires `write` (or `daemon`). JWT sessions are not
|
||||
// scope-limited - a logged-in human has full account power.
|
||||
// scope-limited; a logged-in human has full account power.
|
||||
const READ_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
|
||||
function tokenAllowsMethod(scopes, method) {
|
||||
const set = new Set(String(scopes || '').split(',').map(s => s.trim()).filter(Boolean));
|
||||
@@ -23,7 +23,7 @@ function tokenAllowsMethod(scopes, method) {
|
||||
|
||||
// Suspension choke point. A suspended account keeps read access (so it can see
|
||||
// the account + the reason) but cannot mutate anything. We only pay for the
|
||||
// status lookup on mutating requests - GET/HEAD/OPTIONS skip it entirely - so
|
||||
// status lookup on mutating requests (GET/HEAD/OPTIONS skip it entirely), so
|
||||
// the read hot path is unchanged. Login is separately refused in auth.js, this
|
||||
// closes the window where an already-issued 7-day token is still valid.
|
||||
async function blockIfSuspended(req, res) {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
// Shared permission helpers. Centralized so every route uses the same
|
||||
// definition of "can this user write to this site's hardware" - the
|
||||
// definition of "can this user write to this site's hardware". The
|
||||
// audit found many routes with no check at all, which made it possible
|
||||
// for any authenticated user to act on another operator's gear.
|
||||
//
|
||||
// All assert* helpers send a 403 response and return false on deny -
|
||||
// All assert* helpers send a 403 response and return false on deny;
|
||||
// the caller should `if (!await assertCanEditSite(...)) return;`.
|
||||
|
||||
import db from '../config/database.js';
|
||||
@@ -25,7 +25,7 @@ export async function canEditSite(siteId, user) {
|
||||
}
|
||||
|
||||
// True if user can schedule observations / commit work to this telescope.
|
||||
// Same trust as canEditSite - owner, operator, OR observer role at site.
|
||||
// Same trust as canEditSite: owner, operator, OR observer role at site.
|
||||
// (Observer can commit observations through the daemon job queue.)
|
||||
export async function canScheduleOnTelescope(telescopeId, user) {
|
||||
if (!telescopeId) return false;
|
||||
@@ -73,8 +73,9 @@ export async function canViewFrame(frame, user) {
|
||||
if (frame.uploader_id === user.id) return true;
|
||||
return canScheduleOnTelescope(frame.telescope_id, user);
|
||||
}
|
||||
// canEditFrame: who may mutate a frame's derived data (crossmatch/analysis) -
|
||||
// uploader, site member, or admin. Mirrors the PUT/DELETE frame checks.
|
||||
// canEditFrame decides who may mutate a frame's derived data (crossmatch or
|
||||
// analysis): the uploader, a site member, or an admin. Mirrors the PUT and
|
||||
// DELETE frame checks.
|
||||
export async function canEditFrame(frame, user) {
|
||||
if (!frame) return false;
|
||||
if (user.role === 'admin') return true;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Admin account moderation. Suspend / unsuspend users - the enforcement
|
||||
// Admin account moderation. Suspend / unsuspend users: the enforcement
|
||||
// mechanism behind the ToS content-removal and repeat-infringer policies.
|
||||
//
|
||||
// A suspended account:
|
||||
|
||||
@@ -1,3 +1,25 @@
|
||||
// The imaging archive: frame upload, metadata, social reads, and the two
|
||||
// derived-science writes (SDSS crossmatch, Claude analysis). Mounted at
|
||||
// /api/archive; every route needs authentication.
|
||||
//
|
||||
// GET /api/archive -> frames visible to the caller
|
||||
// GET /api/archive/:id -> one frame with its detail
|
||||
// POST /api/archive/upload -> multipart file, multer to disk
|
||||
// POST /api/archive -> register a frame by URL
|
||||
// PUT /api/archive/:id DELETE /:id
|
||||
// GET /api/archive/file/:name -> serve the stored bytes
|
||||
// POST /api/archive/query -> structured search
|
||||
// POST /api/archive/:id/comments DELETE /:frameId/comments/:commentId
|
||||
// POST /api/archive/:id/like POST /:id/bookmark
|
||||
// POST /api/archive/:id/sdss-crossmatch
|
||||
// POST /api/archive/:id/analyze
|
||||
//
|
||||
// Uploads land in server/data/uploads and the ingest pipeline (plate-solve,
|
||||
// source extraction, photometry) runs fire-and-forget afterwards, so a slow
|
||||
// pipeline never holds the response open. The two derived-science routes write
|
||||
// onto the frame row, so they are restricted to the uploader, a site member,
|
||||
// or an admin.
|
||||
|
||||
import { Router } from 'express';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
import multer from 'multer';
|
||||
@@ -135,7 +157,7 @@ router.post('/upload', authenticate, upload.single('file'), async (req, res) =>
|
||||
try { fs.unlinkSync(req.file.path); } catch {}
|
||||
return res.status(400).json({ error: `invalid frame_type "${frame_type}"` });
|
||||
}
|
||||
// Telescope perm - caller must be a member of the owning site (or admin).
|
||||
// Telescope perm: caller must be a member of the owning site (or admin).
|
||||
// Without this any authenticated user could attribute a frame to anyone's
|
||||
// telescope and consume their archive against another user's quota.
|
||||
const ok = await assertCanScheduleOnTelescope(telescope_id, req.user, res);
|
||||
@@ -183,14 +205,14 @@ router.post('/upload', authenticate, upload.single('file'), async (req, res) =>
|
||||
file_url, req.file.size, visibility || 'private',
|
||||
description || null, JSON.stringify(tagsArr), JSON.stringify(fits_headers)]);
|
||||
|
||||
// observation_id is optional - when a daemon uploads frames during a
|
||||
// observation_id is optional; when a daemon uploads frames during a
|
||||
// scheduled observation it sets this to link the frame back to the
|
||||
// observation record. JSON-body POST handler below has the same wiring.
|
||||
|
||||
invalidateUsage(req.user.id, 'archive.frames_per_user');
|
||||
invalidateUsage(req.user.id, 'archive.storage_mb_per_user');
|
||||
|
||||
// Fire-and-forget - pipeline runs (plate-solve/extract/photometry) in
|
||||
// Fire-and-forget; pipeline runs (plate-solve/extract/photometry) in
|
||||
// the background and updates analysis_json when it finishes. We don't
|
||||
// await so a slow stage never blocks the upload response.
|
||||
ingestFrame(id);
|
||||
@@ -328,7 +350,7 @@ router.post('/:id/bookmark', authenticate, async (req, res) => {
|
||||
router.post('/:id/sdss-crossmatch', authenticate, async (req, res) => {
|
||||
const frame = await db.get('SELECT ra, dec_coord, visibility, uploader_id, telescope_id FROM archive_frames WHERE id = ?', [req.params.id]);
|
||||
if (!frame) return res.status(404).json({ error: 'Frame not found' });
|
||||
// Writes sdss_crossmatch_json onto the frame - restrict to uploader/site/admin.
|
||||
// Writes sdss_crossmatch_json onto the frame; restrict to uploader/site/admin.
|
||||
if (!await canEditFrame(frame, req.user)) return res.status(403).json({ error: "You can't modify this frame." });
|
||||
if (frame.ra == null || frame.dec_coord == null) return res.status(400).json({ error: 'Frame has no coordinates for cross-matching' });
|
||||
|
||||
@@ -368,7 +390,7 @@ router.post('/:id/sdss-crossmatch', authenticate, async (req, res) => {
|
||||
router.post('/:id/analyze', authenticate, async (req, res) => {
|
||||
const frame = await db.get('SELECT * FROM archive_frames WHERE id = ?', [req.params.id]);
|
||||
if (!frame) return res.status(404).json({ error: 'Frame not found' });
|
||||
// Writes analysis_json onto the frame - restrict to uploader/site/admin.
|
||||
// Writes analysis_json onto the frame; restrict to uploader/site/admin.
|
||||
if (!await canEditFrame(frame, req.user)) return res.status(403).json({ error: "You can't modify this frame." });
|
||||
|
||||
let headers = {};
|
||||
|
||||
@@ -1,3 +1,29 @@
|
||||
// Astra instances: a full observatory control surface for one site's gear,
|
||||
// driven through the Astra client rather than a raw protocol. Mounted at
|
||||
// /api/astra; every route needs authentication.
|
||||
//
|
||||
// GET/POST/DELETE /api/astra/instances[/:id]
|
||||
// POST /api/astra/instances/:id/connect | /disconnect
|
||||
// GET /api/astra/instances/:id/status | /position | /weather
|
||||
// POST /api/astra/instances/:id/slew | /abort
|
||||
// POST /api/astra/instances/:id/track/start | /stop
|
||||
// POST/GET /api/astra/instances/:id/autoguide/{start,stop,status}
|
||||
// POST/GET /api/astra/instances/:id/autofocus/{start,status}
|
||||
// POST/GET /api/astra/instances/:id/platesolve[/result]
|
||||
// POST/GET /api/astra/instances/:id/expose | /camera/status
|
||||
// POST /api/astra/instances/:id/camera/abort
|
||||
// POST /api/astra/instances/:id/enclosure/open | /close
|
||||
// GET /api/astra/weather/:siteId
|
||||
// GET/POST/DELETE /api/astra/downtimes[/:id]
|
||||
// GET/POST /api/astra/archive
|
||||
//
|
||||
// These instances drive physical hardware, so gateInstance() below requires
|
||||
// site-edit rights on every /instances/:id route before the call reaches
|
||||
// services/astra-client.js. Instance rows are always column-listed rather than
|
||||
// `SELECT ai.*`, because astra_instances.api_key is the credential that drives
|
||||
// slew, expose and open-dome. Downtime windows must end strictly after they
|
||||
// start.
|
||||
|
||||
import { Router } from 'express';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
import db from '../config/database.js';
|
||||
@@ -8,7 +34,7 @@ import { getOrCreateClient, removeClient } from '../services/astra-client.js';
|
||||
const router = Router();
|
||||
|
||||
// Resolve an Astra instance's owning site for permission checks. Astra
|
||||
// instances drive physical hardware (slew, expose, open dome) - every
|
||||
// instances drive physical hardware (slew, expose, open dome); every
|
||||
// mutating endpoint MUST gate on site membership, not just authentication.
|
||||
async function loadInstanceSite(instanceId) {
|
||||
return db.get('SELECT site_id FROM astra_instances WHERE id = ?', [instanceId]);
|
||||
@@ -274,7 +300,7 @@ router.get('/downtimes', authenticate, async (req, res) => {
|
||||
router.post('/downtimes', authenticate, async (req, res) => {
|
||||
const { site_id, enclosure_id, telescope_id, reason, start_time, end_time, description } = req.body;
|
||||
if (!site_id || !start_time || !end_time) return res.status(400).json({ error: 'site_id, start_time, and end_time are required' });
|
||||
// end must be strictly after start - otherwise a one-second-wide downtime
|
||||
// end must be strictly after start; otherwise a one-second-wide downtime
|
||||
// can poison conflict checks.
|
||||
if (new Date(end_time) <= new Date(start_time)) {
|
||||
return res.status(400).json({ error: 'end_time must be after start_time' });
|
||||
|
||||
@@ -1,3 +1,14 @@
|
||||
// Account registration, login, and identity lookup. Mounted at /api/auth.
|
||||
//
|
||||
// POST /api/auth/register { email, username, password } -> { user, token }
|
||||
// POST /api/auth/login { email, password } -> { user, token }
|
||||
// GET /api/auth/me -> the caller's row
|
||||
//
|
||||
// The first account to register becomes `admin`; every later one is
|
||||
// `observer`. Both write paths are rate limited, and login refuses a
|
||||
// suspended account outright (middleware/auth.js blocks tokens already
|
||||
// issued to one).
|
||||
|
||||
import { Router } from 'express';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
|
||||
@@ -1,3 +1,19 @@
|
||||
// Telescope time: the booking rows that turn granted proposal time into a
|
||||
// window on a specific instrument. Mounted at /api/bookings; every route needs
|
||||
// authentication.
|
||||
//
|
||||
// GET /api/bookings/telescope/:telescopeId -> that telescope's calendar
|
||||
// GET /api/bookings/my -> the caller's bookings
|
||||
// GET /api/bookings/visible -> plus collaborator access
|
||||
// GET /api/bookings/proposal/:proposalId -> one proposal's bookings
|
||||
// POST /api/bookings -> book a window
|
||||
// PUT /api/bookings/:id -> reschedule or retitle
|
||||
// DELETE /api/bookings/:id -> cancel
|
||||
//
|
||||
// A booking's displayed state comes from SESSION_STATE_SQL in
|
||||
// utils/booking-state.js, never from a re-derivation in the client. See
|
||||
// DESIGN.md for why that is a presentation-layer invariant.
|
||||
|
||||
import { Router } from 'express';
|
||||
import { aggregateRequestGroup } from '../services/lifecycle.js';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
@@ -50,7 +66,7 @@ router.get('/my', authenticate, async (req, res) => {
|
||||
// Every booking the user legitimately has visibility into, so the Schedule
|
||||
// calendar agrees with the Request-Group Backlog shown on the same page.
|
||||
// Before this, the calendar used /bookings/my (own bookings only) while the
|
||||
// backlog showed proposal-wide RG state - a request group could read
|
||||
// backlog showed proposal-wide RG state; a request group could read
|
||||
// "SCHEDULED · 1 booked" yet never appear on the calendar because the
|
||||
// booking belonged to another proposal member. Union of:
|
||||
// 1. bookings the user owns
|
||||
|
||||
@@ -1,3 +1,16 @@
|
||||
// Hardware inventory: enclosures, telescopes, and the instruments bolted to
|
||||
// them. This is the configuration database, separate from the live control
|
||||
// paths in control.js and astra.js. Mounted at /api/configdb; every route
|
||||
// needs authentication.
|
||||
//
|
||||
// POST /api/configdb/enclosures PUT/DELETE /enclosures/:id
|
||||
// GET /api/configdb/telescopes GET /telescopes/:id
|
||||
// POST /api/configdb/telescopes PUT/DELETE /telescopes/:id
|
||||
// POST /api/configdb/instruments DELETE /instruments/:id
|
||||
//
|
||||
// Per-plan caps are charged to the SITE OWNER rather than the editor, and
|
||||
// session locks block edits to hardware that is mid-observation.
|
||||
|
||||
import { Router } from 'express';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
import db from '../config/database.js';
|
||||
@@ -89,7 +102,7 @@ router.post('/telescopes', authenticate, async (req, res) => {
|
||||
if (!enc) return res.status(404).json({ error: 'Enclosure not found' });
|
||||
if (!(await canEditSite(req.user.id, enc.site_id)) && req.user.role !== 'admin') return res.status(403).json({ error: 'Not authorized' });
|
||||
|
||||
// Limit applies to the SITE OWNER, not the editor - keeps the cap
|
||||
// Limit applies to the SITE OWNER, not the editor; keeps the cap
|
||||
// meaningful when an editor adds telescopes to someone else's site.
|
||||
const site = await db.get('SELECT owner_id FROM sites WHERE id = ?', [enc.site_id]);
|
||||
if (site?.owner_id) {
|
||||
|
||||
@@ -1,3 +1,17 @@
|
||||
// Direct mount control over the Stellarium protocol: connect, slew, read back
|
||||
// position. Mounted at /api/control. Every route needs authentication, and
|
||||
// canControl() below then requires admin, site ownership, or membership at the
|
||||
// telescope's site.
|
||||
//
|
||||
// POST /api/control/:telescopeId/connect -> dial the driver
|
||||
// POST /api/control/:telescopeId/disconnect -> hang up, force status idle
|
||||
// POST /api/control/:telescopeId/slew -> { ra, dec }
|
||||
// GET /api/control/:telescopeId/position -> live RA/Dec
|
||||
// GET /api/control/:telescopeId/status -> connection + mount state
|
||||
//
|
||||
// The ASCOM Alpaca equivalents live in hardware.js, and services/
|
||||
// telescope-control.js holds the connection pool both of them share.
|
||||
|
||||
import { Router } from 'express';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
import db from '../config/database.js';
|
||||
|
||||
@@ -1,3 +1,28 @@
|
||||
// ASCOM Alpaca hardware: driver discovery, connection tests, per-device driver
|
||||
// assignment, live state reads, weather stations, and third-party integrations.
|
||||
// Mounted at /api/hardware.
|
||||
//
|
||||
// GET/POST /api/hardware/discover[/host] -> scan for Alpaca devices
|
||||
// POST /api/hardware/test -> probe one driver
|
||||
// GET /api/hardware/resolve -> name to RA/Dec
|
||||
// PUT /api/hardware/telescopes/:id/driver GET /:id/state
|
||||
// POST /api/hardware/telescopes/:id/slew
|
||||
// PUT /api/hardware/instruments/:id/driver GET /:id/state
|
||||
// PUT /api/hardware/enclosures/:id/driver
|
||||
// POST /api/hardware/enclosures/:id/dome/:action GET /:id/dome/state
|
||||
// GET/POST /api/hardware/sites/:siteId/weather-stations
|
||||
// PATCH/DELETE /api/hardware/weather-stations/:id
|
||||
// POST /api/hardware/weather-stations/:id/poll
|
||||
// GET/POST /api/hardware/sites/:siteId/integrations
|
||||
// DELETE /api/hardware/integrations/:id GET /:id/events
|
||||
// GET /api/hardware/site/:siteId -> the site's whole rig
|
||||
// POST /api/hardware/webhook/:token -> inbound, token-authorized
|
||||
//
|
||||
// Everything except the webhook needs authentication and site rights; the
|
||||
// webhook authorizes on its path token instead. A stored `api_key` is a
|
||||
// third-party credential, so it is redacted on read, and any route that makes
|
||||
// an outbound fetch with one is restricted to site members.
|
||||
|
||||
import { Router } from 'express';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
import crypto from 'crypto';
|
||||
@@ -130,7 +155,7 @@ router.post('/telescopes/:id/slew', authenticate, async (req, res) => {
|
||||
if (!(await canEditSite(tel.site_id, req.user))) return res.status(403).json({ error: 'Not authorized' });
|
||||
const { ra, dec } = req.body;
|
||||
if (ra == null || dec == null) return res.status(400).json({ error: 'ra and dec required' });
|
||||
// Hardware can't physically slew to nonsense - refuse before sending to driver.
|
||||
// Hardware can't physically slew to nonsense; refuse before sending to driver.
|
||||
if (typeof ra !== 'number' || ra < 0 || ra >= 24) return res.status(400).json({ error: 'ra must be 0..24 hours' });
|
||||
if (typeof dec !== 'number' || dec < -90 || dec > 90) return res.status(400).json({ error: 'dec must be -90..+90 degrees' });
|
||||
if (tel.driver_type === 'alpaca') {
|
||||
@@ -162,7 +187,7 @@ router.put('/instruments/:id/driver', authenticate, async (req, res) => {
|
||||
router.get('/instruments/:id/state', authenticate, async (req, res) => {
|
||||
const inst = await loadInstrument(req.params.id);
|
||||
if (!inst) return res.status(404).json({ error: 'Instrument not found' });
|
||||
// Live state via Alpaca isn't wired yet - return the DB record only. When
|
||||
// Live state via Alpaca isn't wired yet; return the DB record only. When
|
||||
// we add an instrument driver, populate `live` from a hardware-driver call.
|
||||
res.json({ id: inst.id, name: inst.name, type: inst.type, driver_type: inst.driver_type, live: null });
|
||||
});
|
||||
@@ -170,7 +195,7 @@ router.get('/instruments/:id/state', authenticate, async (req, res) => {
|
||||
// --- Weather Stations ---
|
||||
router.get('/sites/:siteId/weather-stations', authenticate, async (req, res) => {
|
||||
const rows = await db.all(`SELECT * FROM weather_stations WHERE site_id = ? ORDER BY created_at ASC`, [req.params.siteId]);
|
||||
// api_key is a third-party credential (e.g. OpenWeatherMap) - redact for
|
||||
// api_key is a third-party credential (e.g. OpenWeatherMap); redact for
|
||||
// non-editors. Editors get a `has_api_key` flag instead of the raw value.
|
||||
const isEditor = await canEditSite(req.params.siteId, req.user);
|
||||
for (const r of rows) {
|
||||
@@ -219,7 +244,7 @@ router.delete('/weather-stations/:id', authenticate, async (req, res) => {
|
||||
router.post('/weather-stations/:id/poll', authenticate, async (req, res) => {
|
||||
const ws = await db.get('SELECT * FROM weather_stations WHERE id = ?', [req.params.id]);
|
||||
if (!ws) return res.status(404).json({ error: 'Station not found' });
|
||||
// Polling makes an outbound fetch using the site's stored api_key - restrict
|
||||
// Polling makes an outbound fetch using the site's stored api_key; restrict
|
||||
// to site editors so it can't be abused to burn another site's quota / SSRF.
|
||||
if (!(await canEditSite(ws.site_id, req.user))) return res.status(403).json({ error: 'Not authorized' });
|
||||
try {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// An "observatory daemon" is a small process running at a remote
|
||||
// observatory that polls Caelum for work, executes Nox programs locally
|
||||
// against real hardware drivers, and PUTs results back. This is the same
|
||||
// shape SatNOGS's station daemon uses, adapted for telescopes - the job
|
||||
// shape SatNOGS's station daemon uses, adapted for telescopes; the job
|
||||
// payload carries the full Nox program instead of an RF (freq, mode,
|
||||
// baud) tuple.
|
||||
//
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// GET /api/limits/me - returns the caller's caps and current usage so
|
||||
// GET /api/limits/me: returns the caller's caps and current usage so
|
||||
// the UI can render a "you're at 180/200 frames" panel before they hit
|
||||
// the wall. Unlimited entries (no cap configured) are reported as null
|
||||
// so the client can render them as "∞" rather than a bogus number.
|
||||
|
||||
@@ -1,3 +1,16 @@
|
||||
// Direct messages between two operators. Mounted at /api/messages; every route
|
||||
// needs authentication.
|
||||
//
|
||||
// GET /api/messages -> threads with unread counts
|
||||
// GET /api/messages/with/:username -> one thread, marks it read
|
||||
// POST /api/messages/with/:username -> send, emits over Socket.IO
|
||||
// DELETE /api/messages/with/:username -> delete the thread for BOTH
|
||||
// GET /api/messages/unread-count -> badge count
|
||||
//
|
||||
// A thread is keyed by the sorted user-id pair, so (a,b) and (b,a) are the
|
||||
// same row and no membership check beyond that pair is needed. DELETE is
|
||||
// mutual by design: there is no per-user hide.
|
||||
|
||||
import { Router } from 'express';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
import db from '../config/database.js';
|
||||
@@ -70,14 +83,14 @@ router.post('/with/:username', authenticate, async (req, res) => {
|
||||
res.status(201).json(message);
|
||||
});
|
||||
|
||||
// Deletes the whole conversation for BOTH participants - there is no per-user
|
||||
// Deletes the whole conversation for BOTH participants; there is no per-user
|
||||
// hide column, and adding one for a two-person thread is more machinery than
|
||||
// this needs. The confirm dialog client-side says so explicitly.
|
||||
router.delete('/with/:username', authenticate, async (req, res) => {
|
||||
const other = await db.get('SELECT id, username FROM users WHERE username = ?', [req.params.username]);
|
||||
if (!other) return res.status(404).json({ error: 'User not found' });
|
||||
// canonicalPair includes the caller, so only threads the caller belongs to
|
||||
// can ever match - no separate membership check needed.
|
||||
// can ever match, no separate membership check needed.
|
||||
const [a, b] = canonicalPair(req.user.id, other.id);
|
||||
const thread = await db.get('SELECT * FROM dm_threads WHERE user_a = ? AND user_b = ?', [a, b]);
|
||||
if (!thread) return res.status(404).json({ error: 'No conversation' });
|
||||
|
||||
@@ -1,3 +1,24 @@
|
||||
// The federation surface: public counters, cross-site discovery, site profiles
|
||||
// and reviews, booking requests between operators, and the leaderboard.
|
||||
// Mounted at /api/network.
|
||||
//
|
||||
// GET /api/network/public/stats | /public/recent -> unauthenticated
|
||||
// GET /api/network/search | /discover | /feed
|
||||
// GET /api/network/bookmarks POST /sites/:id/bookmark
|
||||
// GET /api/network/sites/:id/profile | /calendar
|
||||
// GET/POST/DELETE /api/network/sites/:id/reviews[/mine]
|
||||
// GET/POST/DELETE /api/network/sites/:id/comments[/:commentId]
|
||||
// POST/GET /api/network/sites/:id/booking-requests
|
||||
// GET /api/network/booking-requests/mine
|
||||
// PATCH/DELETE /api/network/booking-requests/:id
|
||||
// GET /api/network/users/:username/profile | /frames
|
||||
// GET /api/network/stats/:metric | /leaderboard
|
||||
//
|
||||
// The two /public routes back the landing page, so they are unauthenticated
|
||||
// and degrade to zeros rather than a 500 when the DB is cold. Public profiles
|
||||
// never carry email or role; only /users/:username/profile for the caller
|
||||
// themselves does.
|
||||
|
||||
import { Router } from 'express';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
import db from '../config/database.js';
|
||||
@@ -42,13 +63,13 @@ router.get('/public/stats', async (_req, res) => {
|
||||
telescopes: Number(telescopes?.c) || 0,
|
||||
});
|
||||
} catch {
|
||||
// Don't 500 a public read - return zeros so the landing tile stays
|
||||
// Don't 500 a public read; return zeros so the landing tile stays
|
||||
// graceful when the DB is cold.
|
||||
res.json({ frames: 0, sites: 0, telescopes: 0 });
|
||||
}
|
||||
});
|
||||
|
||||
// Public recent-activity feed for the landing page. Unauth by design -
|
||||
// Public recent-activity feed for the landing page. Unauth by design;
|
||||
// returns aggregated events with NO user PII, NO message bodies, only
|
||||
// what's already public ("M51 captured 3h ago at Mountain Peak"). Pulls
|
||||
// recent frames and confirmed bookings from public+network surfaces only.
|
||||
@@ -56,7 +77,7 @@ router.get('/public/stats', async (_req, res) => {
|
||||
//
|
||||
// One subject appears at most once. A target is normally shot several times
|
||||
// in a night across filters, so "the most recent N frames" collapsed into the
|
||||
// same object repeated - the feed read as "M31 · L, M31 · Ha, M31 · OIII"
|
||||
// same object repeated; the feed read as "M31 · L, M31 · Ha, M31 · OIII"
|
||||
// instead of showing what the network is actually working on. We over-fetch
|
||||
// and keep only the newest row per subject, so the caller still gets `limit`
|
||||
// events but they're `limit` *distinct* ones.
|
||||
@@ -115,7 +136,7 @@ router.get('/public/recent', async (req, res) => {
|
||||
// Collapse to one event per subject, newest wins (the list is already
|
||||
// sorted newest-first, so the first sighting is the one to keep). Keyed
|
||||
// by kind too: a "Jupiter" frame and a "Jupiter & Saturn" session are
|
||||
// genuinely different events and both deserve a row.
|
||||
// different events and both deserve a row.
|
||||
const seen = new Set();
|
||||
const distinct = [];
|
||||
for (const e of events) {
|
||||
@@ -636,7 +657,7 @@ router.get('/stats/:metric', authenticate, async (req, res) => {
|
||||
if (metric === 'users') {
|
||||
// id/username/created_at only. This is the Leaderboard drill-down, open to
|
||||
// any authenticated user, so it must match the public-profile stance in
|
||||
// /users/:username/profile below - email and role are not other people's
|
||||
// /users/:username/profile below; email and role are not other people's
|
||||
// business, and every other metric here is scoped to public/network too.
|
||||
cols = 'id, username, created_at';
|
||||
body = `FROM users${cutoff ? ' WHERE created_at >= ?' : ''}`;
|
||||
@@ -652,7 +673,7 @@ router.get('/stats/:metric', authenticate, async (req, res) => {
|
||||
body = `FROM telescopes t JOIN enclosures e ON t.enclosure_id = e.id JOIN sites s ON e.site_id = s.id WHERE s.visibility IN ('public','network')`;
|
||||
order = 'ORDER BY t.aperture_mm DESC';
|
||||
description = 'Telescopes at public + network observatories (window does not filter telescopes)';
|
||||
// No cutoff filter for telescopes - but skip the param push if cutoff is set.
|
||||
// No cutoff filter for telescopes, but skip the param push if cutoff is set.
|
||||
} else if (metric === 'public_frames') {
|
||||
cols = 'af.id, af.target_name, af.filter, af.exposure_time, af.created_at, u.username as uploader, t.name as telescope';
|
||||
body = `FROM archive_frames af LEFT JOIN users u ON af.uploader_id = u.id LEFT JOIN telescopes t ON af.telescope_id = t.id WHERE af.visibility IN ('public','network')${cutoff ? ' AND af.created_at >= ?' : ''}`;
|
||||
@@ -751,7 +772,7 @@ router.get('/leaderboard', authenticate, async (req, res) => {
|
||||
|
||||
// --- User profile (public stats) ---
|
||||
router.get('/users/:username/profile', authenticate, async (req, res) => {
|
||||
// Public profile - do NOT expose email or role to other users.
|
||||
// Public profile: do NOT expose email or role to other users.
|
||||
const u = await db.get('SELECT id, username, created_at FROM users WHERE username = ?', [req.params.username]);
|
||||
if (!u) return res.status(404).json({ error: 'User not found' });
|
||||
const sites_owned = await db.all(`SELECT id, name, code, visibility FROM sites WHERE owner_id = ? AND visibility IN ('public','network')`, [u.id]);
|
||||
|
||||
@@ -1,3 +1,17 @@
|
||||
// Notifications and the Inbox aggregate behind them. Mounted at
|
||||
// /api/notifications; every route needs authentication.
|
||||
//
|
||||
// GET /api/notifications/inbox -> everything needing attention
|
||||
// GET /api/notifications -> the raw list (?unread=1&limit=)
|
||||
// GET /api/notifications/count -> unread badge count
|
||||
// POST /api/notifications/:id/read | /read-all
|
||||
// DELETE /api/notifications/:id
|
||||
//
|
||||
// /inbox is the one place that answers "what needs me?", so it returns
|
||||
// notifications plus the caller's outstanding booking requests, the requests
|
||||
// waiting on their approval, and their upcoming sessions in a single read.
|
||||
// DESIGN.md calls this the one home for that question.
|
||||
|
||||
import { Router } from 'express';
|
||||
import db from '../config/database.js';
|
||||
import { authenticate } from '../middleware/auth.js';
|
||||
|
||||
+18
-11
@@ -1,8 +1,15 @@
|
||||
// HTTP routes for the Nox language: type-check and execute programs.
|
||||
// HTTP routes for the Nox language: type-check programs, execute them, and
|
||||
// serve the bundled docs and examples. Mounted at /api/nox by src/index.js.
|
||||
//
|
||||
// POST /api/nox/check { source } -> { diagnostics }
|
||||
// POST /api/nox/run { source, mode? } -> { log, error? } mode: "mock" | "real" (default "mock")
|
||||
// GET /api/nox/examples -> [{ name, source }]
|
||||
// POST /api/nox/check { source } -> { diagnostics }
|
||||
// POST /api/nox/run { source, mode?, policy? } -> { log, summary }
|
||||
// POST /api/nox/run-stream { source, mode?, policy? } -> text/event-stream
|
||||
// GET /api/nox/examples -> [{ name, source }]
|
||||
// GET /api/nox/docs-search ?q=&limit= -> { results, total }
|
||||
// GET /api/nox/docs/<path> -> text/markdown
|
||||
//
|
||||
// `mode` is "mock" (default) or "real". Real mode is gated by
|
||||
// requireRealModeSafety below. Reference docs: nox/docs/reference/http-api.md.
|
||||
|
||||
import { Router } from 'express';
|
||||
import fs from 'node:fs/promises';
|
||||
@@ -18,7 +25,7 @@ import { log } from '../services/log.js';
|
||||
const router = Router();
|
||||
|
||||
// `mode: 'real'` reaches live telescope drivers and MUST be authenticated AND
|
||||
// carry an explicit `confirmed: true` flag (defense in depth - the client UI
|
||||
// carry an explicit `confirmed: true` flag (defense in depth, the client UI
|
||||
// preview is one safety layer, this server check is the other). `mode: 'mock'`
|
||||
// stays frictionless so the "Try Nox without signing up" landing keeps working.
|
||||
const VALID_MODES = new Set(['mock', 'real']);
|
||||
@@ -102,11 +109,11 @@ router.post('/run', requireRealModeSafety, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Streaming variant: pushes each op as a Server-Sent Event so the client
|
||||
// can render the log in real time. Source travels via query string (sent
|
||||
// as a POST body would require fetch + ReadableStream on the client).
|
||||
// GET /api/nox/run-stream?mode=mock (source in body via POST trick below)
|
||||
// Express SSE convention: text/event-stream; per-event `data: <json>\n\n`.
|
||||
// Streaming variant of /run: pushes each op as a Server-Sent Event so the
|
||||
// client can render the log while the program is still executing. The request
|
||||
// stays a POST (the source can be kilobytes, and a query string caps out), so
|
||||
// the browser reads the response with fetch + ReadableStream rather than
|
||||
// EventSource. SSE wire format: `event: <name>\ndata: <json>\n\n` per event.
|
||||
router.post('/run-stream', requireRealModeSafety, async (req, res) => {
|
||||
const { source, mode = 'mock', policy } = req.body || {};
|
||||
if (typeof source !== 'string') return res.status(400).json({ error: 'source required' });
|
||||
@@ -156,7 +163,7 @@ router.get('/docs-search', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Serve documentation markdown. Self-contained handler - no reliance on
|
||||
// Serve documentation markdown. Self-contained handler, no reliance on
|
||||
// serve-static's error shape or Express wildcard semantics, both of which
|
||||
// vary between Express 4 and 5 and bit us before.
|
||||
router.use('/docs', async (req, res) => {
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
// PUT /api/observations/:id/result -> daemon reports state transition
|
||||
// PUT /api/observations/:id/vet -> human vets the observation (good/bad/failed)
|
||||
//
|
||||
// The "snapshot" idea - copy site coords + telescope capabilities + Nox
|
||||
// program + ephemeris-source onto the row at creation time - is the
|
||||
// The "snapshot" idea (copy site coords + telescope capabilities + Nox
|
||||
// program + ephemeris-source onto the row at creation time) is the
|
||||
// SatNOGS reproducibility pattern. Reasons:
|
||||
// • renames/reconfigs don't retroactively change what an observation saw
|
||||
// • the observation outlives the rows it points at (a deleted site
|
||||
@@ -68,7 +68,7 @@ router.post('/', authenticate, async (req, res) => {
|
||||
// Permission check: caller must be able to schedule on the telescope's
|
||||
// parent site. Allowed when caller is the site owner OR a site_member
|
||||
// (any role above "viewer"), OR admin role. Visibility=public/network
|
||||
// is NOT enough on its own - you can SEE a public site but not commit
|
||||
// is NOT enough on its own; you can SEE a public site but not commit
|
||||
// observations to its hardware without explicit access.
|
||||
if (!await assertCanScheduleOnTelescope(telescope_id, req.user, res)) return;
|
||||
|
||||
@@ -117,7 +117,7 @@ router.put('/:id/result', authenticate, async (req, res) => {
|
||||
if (!obs) return res.status(404).json({ error: 'observation not found' });
|
||||
|
||||
// Only members of the owning site (or admin) can post results. This is what
|
||||
// a daemon-issued `cae_*` token will hit - same auth as the human path.
|
||||
// a daemon-issued `cae_*` token will hit; same auth as the human path.
|
||||
if (!await assertCanScheduleOnTelescope(obs.telescope_id, req.user, res)) return;
|
||||
|
||||
// State-transition guard: refuse to re-COMPLETE an observation that already
|
||||
@@ -179,7 +179,7 @@ router.put('/:id/vet', authenticate, async (req, res) => {
|
||||
);
|
||||
|
||||
// Move the per-site successful counter only on transitions in/out of
|
||||
// good - keeps the counter consistent across re-vettings.
|
||||
// good; keeps the counter consistent across re-vettings.
|
||||
if (previousGood !== nowGood) {
|
||||
if (site) {
|
||||
const delta = nowGood ? 1 : -1;
|
||||
|
||||
@@ -1,3 +1,16 @@
|
||||
// Observation plans: reusable target lists an operator builds once and then
|
||||
// replays into a request group or a live session. Mounted at /api/plans; every
|
||||
// route needs authentication.
|
||||
//
|
||||
// GET/POST /api/plans GET/PATCH/DELETE /:id
|
||||
// POST /api/plans/:id/targets PATCH/DELETE /:id/targets/:targetId
|
||||
// POST /api/plans/:id/clone-as-request-group/:proposalId
|
||||
// POST /api/plans/:id/load-into/:bookingId
|
||||
//
|
||||
// A plan is a template, so the two clone routes copy targets rather than
|
||||
// linking them. Editing the plan afterwards leaves the request group and the
|
||||
// session alone.
|
||||
|
||||
import { Router } from 'express';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
import db from '../config/database.js';
|
||||
@@ -67,7 +80,7 @@ router.patch('/:id', authenticate, async (req, res) => {
|
||||
if (!plan) return res.status(404).json({ error: 'Plan not found' });
|
||||
if (plan.owner_id !== req.user.id && req.user.role !== 'admin') return res.status(403).json({ error: 'Not authorized' });
|
||||
const { name, description, is_public, proposal_id } = req.body;
|
||||
// If linking to a proposal, the caller must be PI/CI of that proposal -
|
||||
// If linking to a proposal, the caller must be PI/CI of that proposal;
|
||||
// otherwise anyone could attach their plan to an unrelated proposal and
|
||||
// poison its plan listing.
|
||||
if (proposal_id !== undefined && proposal_id) {
|
||||
|
||||
@@ -1,3 +1,16 @@
|
||||
// Per-user preferences: theme, density, default visibility for new frames and
|
||||
// sessions, muted notification types, and the caller's own Anthropic key.
|
||||
// Mounted at /api/preferences; both routes need authentication.
|
||||
//
|
||||
// GET /api/preferences -> the row, redacted
|
||||
// PATCH /api/preferences -> partial update
|
||||
//
|
||||
// The Anthropic key is never echoed back. Reads return a four-character
|
||||
// suffix, a boolean, and whether the key came from the user or from the
|
||||
// server's own ANTHROPIC_API_KEY, so the UI can say "configured by server"
|
||||
// instead of asking for a key that is already there. In PATCH, an absent field
|
||||
// means leave alone and an explicit null means clear.
|
||||
|
||||
import { Router } from 'express';
|
||||
import db from '../config/database.js';
|
||||
import { authenticate } from '../middleware/auth.js';
|
||||
@@ -14,7 +27,7 @@ async function loadOrInit(userId) {
|
||||
// FK constraint fails when the JWT's user_id no longer exists in
|
||||
// the users table (typical after dev:reset wipes/reseeds). Return
|
||||
// a defaulted prefs object so the endpoint doesn't 500 and the
|
||||
// client UI can still render - auth flow handles re-login.
|
||||
// client UI can still render; auth flow handles re-login.
|
||||
return {
|
||||
user_id: userId,
|
||||
theme: 'dark', density: 'comfortable',
|
||||
|
||||
@@ -1,3 +1,21 @@
|
||||
// Observing proposals and the request groups inside them, the Caelum analogue
|
||||
// of a TAC submission. Mounted at /api/proposals; every route needs
|
||||
// authentication.
|
||||
//
|
||||
// GET/POST /api/proposals GET/PUT/DELETE /:id
|
||||
// POST/DELETE /api/proposals/:id/members[/:userId]
|
||||
// POST /api/proposals/:id/request-groups
|
||||
// PATCH /api/proposals/:id/request-groups/:rgId[/state]
|
||||
// PATCH /api/proposals/:id/request-groups/:rgId/requests/:reqId/state
|
||||
// POST /api/proposals/:id/request-groups/:rgId/save-as-plan
|
||||
// DELETE /api/proposals/:id/request-groups/:rgId
|
||||
// GET /api/proposals/request-groups/mine
|
||||
// GET /api/proposals/request-groups/:rgId
|
||||
//
|
||||
// Only a PI or CI may mutate a proposal. Request-group state aggregates from
|
||||
// its child requests (services/lifecycle.js), so a group is never stamped with
|
||||
// a state its requests contradict.
|
||||
|
||||
import { Router } from 'express';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
import db from '../config/database.js';
|
||||
@@ -141,7 +159,7 @@ router.post('/:id/request-groups', authenticate, async (req, res) => {
|
||||
|
||||
// Per-request validation: every telescope_id (if provided) must exist AND
|
||||
// the caller must be allowed to schedule on it. Catch bad telescope_ids
|
||||
// before writing - otherwise requests sit in PENDING forever.
|
||||
// before writing; otherwise requests sit in PENDING forever.
|
||||
for (const r of reqs) {
|
||||
if (!r.target_name) return res.status(400).json({ error: 'each request needs target_name' });
|
||||
if (r.telescope_id) {
|
||||
@@ -296,7 +314,7 @@ router.delete('/:id/members/:userId', authenticate, async (req, res) => {
|
||||
// Note the 1-arg GROUP_CONCAT below: it defaults to a ',' separator in BOTH
|
||||
// dialects. The 2-arg form is a separator in SQLite but a per-row concat in
|
||||
// MySQL, so GROUP_CONCAT(target_name, ', ') returned "M31, ,M42, " on prod.
|
||||
// MySQL spells the separator with a SEPARATOR keyword, which SQLite rejects -
|
||||
// MySQL spells the separator with a SEPARATOR keyword, which SQLite rejects,
|
||||
// there is no 2-arg syntax common to both backends.
|
||||
router.get('/request-groups/mine', authenticate, async (req, res) => {
|
||||
const state = req.query.state;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// and Community Guidelines: any authenticated user can flag public UGC
|
||||
// (frames, comments, profiles, messages); admins triage the queue.
|
||||
//
|
||||
// Deliberately minimal - one insert on report, an admin list, an admin status
|
||||
// Deliberately minimal: one insert on report, an admin list, an admin status
|
||||
// update. Enforcement (removing content, suspending accounts) happens through
|
||||
// the existing archive/admin routes; a report is just the signal.
|
||||
import { Router } from 'express';
|
||||
@@ -17,7 +17,7 @@ const router = Router();
|
||||
// enough that a user flagging several bad items in a sitting is never blocked.
|
||||
const reportLimiter = rateLimit({ windowMs: 10 * 60_000, max: 30 });
|
||||
|
||||
// Closed enums - reject anything else so the moderation queue stays filterable
|
||||
// Closed enums; reject anything else so the moderation queue stays filterable
|
||||
// and a crafted request can't inject arbitrary strings into the columns.
|
||||
const CONTENT_TYPES = new Set(['frame', 'comment', 'profile', 'message']);
|
||||
const REASONS = new Set(['spam', 'harassment', 'infringement', 'illegal', 'other']);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Research feed - science-driven observation candidates sourced from
|
||||
// Research feed: science-driven observation candidates sourced from
|
||||
// external catalogs (MPC, NASA Exoplanet Archive, AAVSO). The /research
|
||||
// page renders these as actionable cards; "Schedule" routes through the
|
||||
// page renders each one as a card with a Schedule button, which routes
|
||||
// through the
|
||||
// same Observation snapshot + jobs queue spine that powers the daemon.
|
||||
//
|
||||
// GET /api/research/feed?category=neo|exoplanet_transit|variable_star
|
||||
@@ -10,8 +11,8 @@
|
||||
// The feed is paginated by recency of `updated_at` so the freshest
|
||||
// alerts (urgent NEOs, current transits) bubble up. The schedule action
|
||||
// builds a Nox program from the target's recommended filters/exposure
|
||||
// metadata and POSTs an Observation with the full snapshot pre-filled -
|
||||
// the daemon polling /api/jobs will pick it up like any other job.
|
||||
// metadata and POSTs an Observation with the full snapshot pre-filled.
|
||||
// The daemon polling /api/jobs will pick it up like any other job.
|
||||
|
||||
import { Router } from 'express';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
@@ -86,7 +87,7 @@ router.get('/feed', authenticate, async (req, res) => {
|
||||
res.json(rows);
|
||||
});
|
||||
|
||||
// Manually add a target to the feed - no upstream fetch, no scheduling. Every
|
||||
// Manually add a target to the feed: no upstream fetch, no scheduling. Every
|
||||
// other add path (SIMBAD resolve, the pull tools) needs the internet, which
|
||||
// leaves the offline box unable to add research at all. This closes that gap
|
||||
// and answers "add research without scheduling anything": importTargets is
|
||||
@@ -116,7 +117,7 @@ router.post('/targets', authenticate, async (req, res) => {
|
||||
res.status(201).json(result);
|
||||
});
|
||||
|
||||
// Object dossier - everything Caelum knows about one object, keyed by name.
|
||||
// Object dossier: everything Caelum knows about one object, keyed by name.
|
||||
// 100% local (zero outbound calls) so it renders on the internet-less box;
|
||||
// catalog identity / SIMBAD stay a lazy, optional client call. This is the
|
||||
// deep-dive target reached from an archive frame or a research card.
|
||||
@@ -147,7 +148,7 @@ router.get('/object/:name', authenticate, async (req, res) => {
|
||||
LIMIT 200
|
||||
`, [uid, name]);
|
||||
|
||||
// How many more frames merely *contain* the name (M31 vs M310) - surfaced
|
||||
// How many more frames merely *contain* the name (M31 vs M310), surfaced
|
||||
// as a count so the UI can offer them without silently lumping them in.
|
||||
const fuzzyRow = await db.get(`
|
||||
SELECT COUNT(*) AS c FROM archive_frames af
|
||||
@@ -155,7 +156,7 @@ router.get('/object/:name', authenticate, async (req, res) => {
|
||||
AND af.target_name LIKE ? AND LOWER(af.target_name) <> LOWER(?)
|
||||
`, [uid, `%${name}%`, name]);
|
||||
|
||||
// Observations independent of frames - most frames have a null
|
||||
// Observations independent of frames; most frames have a null
|
||||
// observation_id, so provenance comes from here, keyed by name.
|
||||
const observations = await db.all(`
|
||||
SELECT o.id, o.state, o.start_time, o.end_time, o.vetted_status, o.vetting_reason,
|
||||
@@ -204,7 +205,7 @@ router.get('/object/:name', authenticate, async (req, res) => {
|
||||
framesOut.push(f);
|
||||
}
|
||||
|
||||
// Aggregate stats in JS (portable - no GROUP BY / GROUP_CONCAT).
|
||||
// Aggregate stats in JS (portable, no GROUP BY / GROUP_CONCAT).
|
||||
const uniq = (arr) => [...new Set(arr.filter(Boolean))];
|
||||
const stats = {
|
||||
frame_count: framesOut.length,
|
||||
@@ -294,7 +295,7 @@ router.post('/:targetId/schedule', authenticate, async (req, res) => {
|
||||
`, [telescope_id]);
|
||||
if (!ctx) return res.status(404).json({ error: 'telescope not found' });
|
||||
|
||||
// Permission check: same as direct observation create - caller must be
|
||||
// Permission check: same as direct observation create; caller must be
|
||||
// a member of the telescope's owning site, otherwise they're attempting
|
||||
// to book hardware they don't have access to.
|
||||
if (!await assertCanScheduleOnTelescope(telescope_id, req.user, res)) return;
|
||||
@@ -396,7 +397,7 @@ router.post('/tools/ephemeris', authenticate, async (req, res) => {
|
||||
} catch (e) { res.status(502).json({ error: `Horizons lookup failed: ${e.message}` }); }
|
||||
});
|
||||
|
||||
// Name resolver - turn any catalog/common name into RA/Dec via SIMBAD.
|
||||
// Name resolver: turn any catalog/common name into RA/Dec via SIMBAD.
|
||||
// GET because it's a pure lookup; results are safe to cache.
|
||||
router.get('/tools/resolve', authenticate, async (req, res) => {
|
||||
const { name } = req.query || {};
|
||||
@@ -464,7 +465,7 @@ router.post('/tools/field-scan', authenticate, async (req, res) => {
|
||||
} catch (e) { res.status(502).json({ error: `Field scan failed: ${e.message}` }); }
|
||||
});
|
||||
|
||||
// Claude Lab - scientific analysis powered by the user's Anthropic key.
|
||||
// Claude Lab: scientific analysis powered by the user's Anthropic key.
|
||||
// Server pulls the target + frame headers + SpaceDB matches and builds
|
||||
// the prompt so the browser never sees the key or the synthesis logic.
|
||||
router.get('/tools/analyze/templates', authenticate, (_req, res) => {
|
||||
|
||||
@@ -1,3 +1,21 @@
|
||||
// The live session: what happens while a booking's window is open. Targets,
|
||||
// exposures, notes, collaborators, and the weather trace for the night.
|
||||
// Mounted at /api/sessions; every route needs authentication.
|
||||
//
|
||||
// GET /api/sessions/active -> sessions running now
|
||||
// GET /api/sessions/:bookingId -> one session, full detail
|
||||
// GET /api/sessions/:bookingId/weather -> the night's weather trace
|
||||
// GET /api/sessions/:bookingId/summary -> counts for the wrap-up
|
||||
// PATCH /api/sessions/:bookingId/visibility -> private/network/public
|
||||
// POST /api/sessions/:bookingId/targets PATCH/DELETE .../:targetId
|
||||
// POST /api/sessions/:bookingId/exposures -> log a frame as it lands
|
||||
// POST /api/sessions/:bookingId/notes DELETE .../notes/:noteId
|
||||
// POST /api/sessions/:bookingId/collaborators DELETE .../:userId
|
||||
//
|
||||
// Writes emit over Socket.IO so every collaborator's view updates without a
|
||||
// poll. A collaborator can log exposures and notes; only the owner can change
|
||||
// visibility or the collaborator list.
|
||||
|
||||
import { Router } from 'express';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
import db from '../config/database.js';
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// Money is integer minor units (cents) end-to-end. The DB is the source of
|
||||
// truth for catalog/price/inventory; Stripe Product/Price are a mirror kept
|
||||
// in sync by admin actions, and the charged amount is ALWAYS computed
|
||||
// server-side from shop_products - never from the client, never from Stripe.
|
||||
// server-side from shop_products; never from the client, never from Stripe.
|
||||
//
|
||||
// Catalog management is admin-only. Checkout requires a logged-in user.
|
||||
// The webhook handler is exported separately so index.js can mount it with a
|
||||
@@ -25,7 +25,7 @@ const router = Router();
|
||||
const CATEGORIES = new Set(['mount', 'ota', 'camera', 'filter_wheel', 'focuser', 'computer', 'dome', 'accessory']);
|
||||
|
||||
// Payment/checkout paths fail closed until Stripe is configured. The public
|
||||
// catalog (/config, /products) is NOT gated on Stripe - the shop runs as an
|
||||
// catalog (/config, /products) is NOT gated on Stripe; the shop runs as an
|
||||
// Agena Astro affiliate, so the catalog must show even with no payment backend.
|
||||
function requireShop(req, res, next) {
|
||||
if (!isShopEnabled()) return res.status(503).json({ error: 'Shop is not configured' });
|
||||
@@ -331,7 +331,7 @@ router.put('/admin/products/:id', requireShop, authenticate, requireRole('admin'
|
||||
await db.run('UPDATE shop_products SET stripe_price_id = ? WHERE id = ?', [price.id, row.id]);
|
||||
}
|
||||
} else if (stripe) {
|
||||
// Row never synced - do the full create now.
|
||||
// Row never synced; do the full create now.
|
||||
await syncProductToStripe(await db.get('SELECT * FROM shop_products WHERE id = ?', [row.id]));
|
||||
}
|
||||
} catch (e) {
|
||||
@@ -426,7 +426,7 @@ export async function shopWebhookHandler(req, res) {
|
||||
log.info(`[shop] webhook received: ${event.type} (${event.id})`);
|
||||
|
||||
// Exactly-once: the event-id ledger is the gate. A duplicate insert means
|
||||
// we've already processed this event - ack and skip.
|
||||
// we've already processed this event; ack and skip.
|
||||
try {
|
||||
await db.run('INSERT INTO shop_webhook_events (id, type) VALUES (?, ?)', [event.id, event.type]);
|
||||
} catch {
|
||||
@@ -465,7 +465,7 @@ async function handlePaymentSucceeded(pi) {
|
||||
const oversold = [];
|
||||
await db.tx(async (t) => {
|
||||
for (const it of items) {
|
||||
// Guarded conditional decrement - atomic on both backends. changes=0
|
||||
// Guarded conditional decrement, atomic on both backends. changes=0
|
||||
// means insufficient stock (rare; the checkout soft-check guards it).
|
||||
const r = await t.run(
|
||||
'UPDATE shop_products SET inventory_count = inventory_count - ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? AND inventory_count >= ?',
|
||||
|
||||
@@ -1,3 +1,18 @@
|
||||
// Observatory sites, the top-level entity everything else hangs off: an
|
||||
// enclosure belongs to a site, a telescope belongs to an enclosure. Mounted at
|
||||
// /api/sites; every route needs authentication.
|
||||
//
|
||||
// GET /api/sites -> sites visible to the caller
|
||||
// GET /api/sites/:id -> one site, with a trust metric
|
||||
// POST /api/sites -> create (caller becomes owner)
|
||||
// PUT /api/sites/:id -> update (owner or operator)
|
||||
// DELETE /api/sites/:id -> delete (owner only)
|
||||
// POST /api/sites/:id/members -> grant a role at this site
|
||||
// DELETE /api/sites/:id/members/:userId -> revoke it
|
||||
//
|
||||
// Writes are refused while a session is locked on the site's hardware, so a
|
||||
// running observation never has its configuration changed underneath it.
|
||||
|
||||
import { Router } from 'express';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
import db from '../config/database.js';
|
||||
@@ -59,7 +74,7 @@ router.get('/:id', authenticate, async (req, res) => {
|
||||
|
||||
const downtimes = await db.all("SELECT * FROM downtimes WHERE site_id = ? AND end_time > CURRENT_TIMESTAMP ORDER BY start_time ASC", [site.id]);
|
||||
|
||||
// Derived trust metric - single read instead of an aggregate. The
|
||||
// Derived trust metric, single read instead of an aggregate. The
|
||||
// counters live on the row (see sites schema + migrations.js) and are
|
||||
// moved by /api/observations/:id/result and /api/observations/:id/vet.
|
||||
const success_rate = (site.total_observations > 0)
|
||||
|
||||
@@ -1,3 +1,19 @@
|
||||
// SpaceDB catalog reads: roughly 1.5M asteroids and comets sourced from
|
||||
// NASA/JPL, plus close approaches and Sentry risk rows. Mounted at
|
||||
// /api/spacedb; every route needs authentication.
|
||||
//
|
||||
// GET /api/spacedb/objects -> search and filter the catalog
|
||||
// GET /api/spacedb/objects/:slug -> one object
|
||||
// GET /api/spacedb/close-approaches -> upcoming approaches
|
||||
// GET /api/spacedb/orbit-classes -> the class vocabulary
|
||||
// GET /api/spacedb/sentry -> impact-risk rows
|
||||
// GET /api/spacedb/stats -> catalog counters
|
||||
//
|
||||
// This is the second, independent database (see CLAUDE.md). A router-level
|
||||
// guard returns 503 for every route when `spacedbPool` is null, which is the
|
||||
// supported no-catalog state rather than a failure: the rest of Caelum runs
|
||||
// fine without it.
|
||||
|
||||
import { Router } from 'express';
|
||||
import { spacedbPool } from '../config/database.js';
|
||||
import { authenticate } from '../middleware/auth.js';
|
||||
@@ -160,7 +176,7 @@ router.get('/stats', authenticate, async (req, res) => {
|
||||
});
|
||||
|
||||
// Best-effort small-body lookup by designation, for the object dossier.
|
||||
// Returns null (never throws) when the catalog is absent - the internet-less
|
||||
// Returns null (never throws) when the catalog is absent; the internet-less
|
||||
// box has no spacedbPool, and a deep-sky object simply isn't in a small-body
|
||||
// catalog. This is the local SpaceDB thread in the object page: a NEO/comet
|
||||
// research object resolves straight to its orbital elements + close approaches.
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
// "Buy me a coffee" - a one-off support payment with a caller-chosen amount.
|
||||
// "Buy me a coffee": a one-off support payment with a caller-chosen amount.
|
||||
//
|
||||
// Deliberately NOT part of routes/shop.js: the shop sells catalogue rows with
|
||||
// authoritative DB prices, inventory and an order record. This has no product,
|
||||
// no stock and no order - it's a tip. Sharing that code would mean teaching the
|
||||
// no stock and no order; it's a tip. Sharing that code would mean teaching the
|
||||
// order pipeline about a line item that doesn't exist.
|
||||
//
|
||||
// Uses hosted Stripe Checkout rather than the shop's PaymentIntent + Elements
|
||||
// flow: card details are then entered on Stripe's own page and never touch
|
||||
// Caelum. The only thing we hand Stripe is an amount.
|
||||
//
|
||||
// Unauthenticated by design - supporters shouldn't need an account - which is
|
||||
// exactly why the amount is validated here and the endpoint is rate limited.
|
||||
// Unauthenticated by design, because supporters shouldn't need an account.
|
||||
// That is exactly why the amount is validated here and the endpoint is rate
|
||||
// limited.
|
||||
import { Router } from 'express';
|
||||
import { getStripe, isShopEnabled } from '../services/stripe.js';
|
||||
import { rateLimit } from '../middleware/rate-limit.js';
|
||||
@@ -57,7 +58,7 @@ router.get('/config', (_req, res) => {
|
||||
|
||||
router.post('/checkout', supportLimiter, async (req, res) => {
|
||||
if (!isShopEnabled()) {
|
||||
// Not an error the user can act on - tell the client to use the link.
|
||||
// Not an error the user can act on; tell the client to use the link.
|
||||
return res.status(503).json({ error: 'Support checkout is not configured', fallbackUrl: FALLBACK_LINK });
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,13 @@
|
||||
// Personal API tokens, the credential an observatory daemon uses instead of a
|
||||
// password. Mounted at /api/tokens; every route needs a logged-in human.
|
||||
//
|
||||
// GET /api/tokens -> the caller's tokens (hash never returned)
|
||||
// POST /api/tokens -> { ...row, token } (the only time it is shown)
|
||||
// DELETE /api/tokens/:id -> 204, sets revoked_at
|
||||
//
|
||||
// Only the SHA-256 hash and a 12-character prefix are stored, so a lost token
|
||||
// cannot be recovered, only revoked.
|
||||
|
||||
import { Router } from 'express';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
import crypto from 'crypto';
|
||||
@@ -8,7 +18,7 @@ const router = Router();
|
||||
|
||||
// Scopes enforced today: only the *string* is stored, not interpreted at
|
||||
// auth time. Until middleware actually checks `scopes` against the request,
|
||||
// constrain creation to the names we plan to honor - accidental typos like
|
||||
// constrain creation to the names we plan to honor; accidental typos like
|
||||
// "all", "*", or "scheule" would silently grant nothing later.
|
||||
const VALID_TOKEN_SCOPES = new Set(['read', 'write', 'daemon']);
|
||||
|
||||
|
||||
@@ -4,12 +4,12 @@
|
||||
// DB_KIND=mysql node src/seed-shop.js # prod-shaped DB
|
||||
//
|
||||
// Prices/inventory are a SNAPSHOT taken from agenaastro.com product pages and
|
||||
// are integer cents. The DB is the source of truth from here on - verify and
|
||||
// are integer cents. The DB is the source of truth from here on; verify and
|
||||
// adjust in the admin UI (/shop/admin); retail prices drift. Idempotent:
|
||||
// upserts by source_url, so re-running refreshes price/inventory/name without
|
||||
// duplicating rows or clobbering products you added by hand.
|
||||
//
|
||||
// Agena is a telescope retailer - it carries scopes, mounts, cameras and
|
||||
// Agena is a telescope retailer: it carries scopes, mounts, cameras and
|
||||
// accessories, but NOT observatory domes/roll-off roofs, so no 'dome' rows are
|
||||
// seeded. Add those by hand if you find a supplier.
|
||||
//
|
||||
|
||||
+14
-14
@@ -35,7 +35,7 @@ for (const t of tables) {
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// users - a small community so feed / leaderboard / messages have life
|
||||
// users: a small community so feed / leaderboard / messages have life
|
||||
// ------------------------------------------------------------------
|
||||
const USERS = [
|
||||
['admin@observatory.local', 'admin', 'admin123', 'admin'],
|
||||
@@ -63,7 +63,7 @@ const adminId = u.admin, observerId = u.observer;
|
||||
// show real states: simulator, stellarium, alpaca.
|
||||
// ------------------------------------------------------------------
|
||||
// site spec: [name, code, owner, lat, lon, alt, tz, visibility, status, about]
|
||||
// `about` stays factual - location, sky quality, altitude. Marketing prose
|
||||
// `about` stays factual: location, sky quality, altitude. Marketing prose
|
||||
// here reads as invented filler on the public landing feed, which pulls
|
||||
// these names straight through.
|
||||
const SITES = [
|
||||
@@ -223,7 +223,7 @@ for (const [key, pid, sub, name, tcode, state, reqs] of RGS) {
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// bookings - every RG-linked booking's window matches its RG state, plus
|
||||
// bookings: every RG-linked booking's window matches its RG state, plus
|
||||
// a few standalone (no-proposal) bookings for variety.
|
||||
// booking: [tcode, user, title, startH, durH, status, vis, proposalId, rgKey]
|
||||
// ------------------------------------------------------------------
|
||||
@@ -246,7 +246,7 @@ for (const [tcode, user, title, startH, durH, status, vis, pid, rgKey] of BOOKIN
|
||||
null, vis, pid, rgKey ? rg[rgKey].id : null]);
|
||||
}
|
||||
|
||||
// active IN_PROGRESS session (NGC 7000) - collaborators, notes, exposures
|
||||
// active IN_PROGRESS session (NGC 7000): collaborators, notes, exposures
|
||||
const active = bookingIds.find(b => b.rgKey === 'na');
|
||||
await db.run('INSERT INTO session_collaborators (booking_id, user_id, invited_by) VALUES (?, ?, ?)', [active.id, adminId, u.nova]);
|
||||
await db.run('INSERT INTO session_collaborators (booking_id, user_id, invited_by) VALUES (?, ?, ?)', [active.id, observerId, u.nova]);
|
||||
@@ -262,7 +262,7 @@ for (let i = 0; i < 6; i++) {
|
||||
done ? 'COMPLETED' : 'RUNNING', dt(hoursFromNow(-0.4 + i * 0.1)), done ? dt(hoursFromNow(-0.3 + i * 0.1)) : null]);
|
||||
}
|
||||
|
||||
// past COMPLETED session (2024 PT5) - needs completed exposures so the
|
||||
// past COMPLETED session (2024 PT5), needs completed exposures so the
|
||||
// COMPLETED request-group state has supporting evidence and matches the
|
||||
// lifecycle COMPLETED criterion (completedExposures > 0).
|
||||
const doneSession = bookingIds.find(b => b.rgKey === 'pt5');
|
||||
@@ -300,7 +300,7 @@ await db.run('INSERT INTO downtimes (id, site_id, telescope_id, reason, start_ti
|
||||
[uuid(), site.LAU, tel.ESP120, 'WEATHER', dt(daysFromNow(-1)), dt(daysFromNow(3)), 'Storm system - dome sealed until conditions improve']);
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// archive frames - broad target + filter + visibility mix
|
||||
// archive frames: broad target + filter + visibility mix
|
||||
// ------------------------------------------------------------------
|
||||
const insertFrame = (...a) => db.run(
|
||||
`INSERT INTO archive_frames (id, telescope_id, uploader_id, filename, frame_type, target_name, ra, dec_coord, filter, exposure_time, date_obs, airmass, fwhm_arcsec, visibility, description, tags, fits_headers_json, wcs_solved, file_size_bytes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, a);
|
||||
@@ -356,7 +356,7 @@ await db.run('INSERT INTO archive_comments (id, frame_id, user_id, body) VALUES
|
||||
[uuid(), social[0].id, observerId, 'What was the seeing on this one?']);
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// observations - the spine of the platform. Each one is the immutable
|
||||
// observations, the spine of the platform. Each one is the immutable
|
||||
// record of "telescope T ran Nox program P at time W and saw the
|
||||
// following frames." Snapshot fields (site coords, telescope caps,
|
||||
// ephemeris source, Nox source) are FROZEN onto the row at create
|
||||
@@ -400,7 +400,7 @@ function noxProgram({ telescopeCode, target, exposureSec, filter, count }) {
|
||||
`use telescope T = "${telescopeCode}"`,
|
||||
`T.slew(${slewArg})`,
|
||||
];
|
||||
// Filter is a named arg on T.expose - there is no T.filter() method.
|
||||
// Filter is a named arg on T.expose; there is no T.filter() method.
|
||||
const filterArg = filter ? `, filter: "${filter}"` : '';
|
||||
for (let i = 0; i < (count || 1); i++) {
|
||||
lines.push(`T.expose(${exposureSec}s${filterArg})`);
|
||||
@@ -444,7 +444,7 @@ const OBSERVATIONS = [
|
||||
['RC600', 'M51', 202.4696, 47.1952,'Ha', 900, 6, 'COMPLETED', 50, 310, 80, 14, 'good', null, 'nova'],
|
||||
['RC600', 'M101', 210.8025, 54.3491,'OIII',900, 6, 'COMPLETED', 30, 330, 84, 4, 'good', null, 'nova'],
|
||||
|
||||
// C8SE (BYO) - public-feed planetary work. Fewer obs so this stays in
|
||||
// C8SE (BYO): public-feed planetary work. Fewer obs so this stays in
|
||||
// experimental probation.
|
||||
['C8SE', 'Jupiter', 63.0, 18.5, null, 0.05, 1000, 'COMPLETED', 100, 260, 55, 8, 'good', 'GRS captured, lucky imaging stack', 'observer'],
|
||||
['C8SE', 'Saturn', 297.0, -18.0, null, 0.1, 500, 'COMPLETED', 110, 250, 45, 6, 'good', null, 'observer'],
|
||||
@@ -457,7 +457,7 @@ const OBSERVATIONS = [
|
||||
// ESP120 (LAU - weathered-in, aurora only, deeply experimental).
|
||||
['ESP120','Aurora', 0, 60, null, 2, 80, 'COMPLETED', 0, 180, 70, 1, 'good', 'auroral arc, time-lapse', 'lyra'],
|
||||
|
||||
// SCHEDULED future PENDING observation for the M51 booking - this is the
|
||||
// SCHEDULED future PENDING observation for the M51 booking; this is the
|
||||
// job a polling daemon will pick up. Lifecycle proof: GET /api/jobs?
|
||||
// telescope_id=CDK14 must return THIS record.
|
||||
['CDK14', 'M51', 202.4696, 47.1952,'L', 300, 10, 'PENDING', 50, 310, 80, -2, 'unknown', null, 'admin'],
|
||||
@@ -555,7 +555,7 @@ for (const srow of sitesRows) {
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// research targets - the science feed that drives the /research view.
|
||||
// research targets, the science feed that drives the /research view.
|
||||
// Real designations from MPC / NASA Exoplanet Archive / AAVSO so the
|
||||
// cards look like the actual thing an observer would see. A future
|
||||
// background refresher will swap this static list for live API pulls;
|
||||
@@ -608,7 +608,7 @@ const RESEARCH_TARGETS = [
|
||||
'NASA Exoplanet Archive', 'https://exoplanetarchive.ipac.caltech.edu/overview/HD%20189733',
|
||||
{ filters_recommended: ['B', 'V', 'R'], exposure_per_filter_s: 30 }],
|
||||
|
||||
// Transient events - supernovae, tidal disruption events, kilonovae.
|
||||
// Transient events: supernovae, tidal disruption events, kilonovae.
|
||||
// Sourced from TNS (Transient Name Server) + Open Astronomy Catalog.
|
||||
// These have the shortest fuse: brightness fades over days–weeks, so
|
||||
// urgency is intrinsic. The Workshop tab's "Pull recent transients"
|
||||
@@ -684,7 +684,7 @@ for (const [owner, name, descr, pub, targets] of PLANS) {
|
||||
// ------------------------------------------------------------------
|
||||
// site reviews, comments, bookmarks
|
||||
// ------------------------------------------------------------------
|
||||
// Ratings only - the numbers drive the site-profile aggregate. The prose
|
||||
// Ratings only; the numbers drive the site-profile aggregate. The prose
|
||||
// bodies were invented testimonials ("Atacama is unreal", "Bortle 2 truly
|
||||
// delivers") and read exactly like generated review filler; a star rating
|
||||
// with no write-up is the common real case anyway.
|
||||
@@ -739,7 +739,7 @@ await thread('admin', 'observer', [
|
||||
// notifications (mix of read/unread for admin + observer)
|
||||
// ------------------------------------------------------------------
|
||||
// Notifications are system-generated, so each one must correspond to a fact
|
||||
// the seed actually established - otherwise the Inbox contradicts every
|
||||
// the seed actually established; otherwise the Inbox contradicts every
|
||||
// other page. The dropped rows were fiction: a "booking_confirmed" for an
|
||||
// M101 run that is seeded PENDING with no booking at all, a frame_comment
|
||||
// from a comment that no longer exists, and a frame_like citing a fixed
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Alpaca camera translator.
|
||||
//
|
||||
// Implements the methods Nox programs call most: cooldown, expose, and
|
||||
// shutter. Image data isn't streamed back to the client - the camera writes
|
||||
// shutter. Image data isn't streamed back to the client; the camera writes
|
||||
// to local storage on the host running the Alpaca server, and Caelum's
|
||||
// archive ingest path picks it up. The Nox runtime gets an Image{filter}
|
||||
// handle so downstream operations (stack, dither, etc.) can reference it.
|
||||
@@ -40,7 +40,7 @@ export async function alpacaCooldown(row, targetDegC, { timeoutMs = 600_000, tol
|
||||
}
|
||||
|
||||
// Trigger an exposure and wait for it to complete. Duration is in seconds.
|
||||
// We don't download image bytes here - that's an archive-ingest concern.
|
||||
// We don't download image bytes here; that's an archive-ingest concern.
|
||||
export async function alpacaExpose(row, durationS, { isLight = true, timeoutPadMs = 30_000 } = {}) {
|
||||
const d = dev(row);
|
||||
await ensureConnected(d);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Archive ingest pipeline - single platform thread that runs on every
|
||||
// Archive ingest pipeline: single platform thread that runs on every
|
||||
// frame the moment it lands, regardless of who put it there (web upload,
|
||||
// session capture, or observatory daemon PUT).
|
||||
//
|
||||
@@ -7,7 +7,7 @@
|
||||
//
|
||||
// Tomorrow: plate-solve via astrometry.net, source extract via sep,
|
||||
// photometry via Synphot/photutils. Each external piece slots in here
|
||||
// behind the same one-call interface - the caller never grows a new
|
||||
// behind the same one-call interface; the caller never grows a new
|
||||
// dependency.
|
||||
|
||||
import db from '../config/database.js';
|
||||
@@ -30,7 +30,7 @@ export async function ingestFrame(frameId) {
|
||||
stages: [],
|
||||
};
|
||||
|
||||
// Stage 1: plate-solving. Stub today - we don't actually solve, we
|
||||
// Stage 1: plate-solving. Stub today: we don't actually solve, we
|
||||
// just mark the frame as needing it. When astrometry.net is wired in,
|
||||
// this is the one place that changes.
|
||||
if (!frame.wcs_solved) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Claude analysis - server-side wrapper around the Anthropic Messages API
|
||||
// Claude analysis: server-side wrapper around the Anthropic Messages API
|
||||
// for the /research Caelum Lab tool.
|
||||
//
|
||||
// Why server-side: the user pastes their own Anthropic key into account
|
||||
@@ -77,7 +77,7 @@ One \`\`\`nox block per distinct visit/observation so each can be scheduled
|
||||
independently. Multiple visits = multiple blocks.
|
||||
|
||||
You may add natural-language explanation BEFORE OR AFTER each block, but
|
||||
the actionable program must be in a real \`\`\`nox block.
|
||||
the program you want run must be in a real \`\`\`nox block.
|
||||
|
||||
# Optional - mention related targets
|
||||
|
||||
@@ -92,7 +92,7 @@ M110
|
||||
NGC 224
|
||||
\`\`\`
|
||||
|
||||
Only include this block when the related targets are genuinely useful for
|
||||
Only include this block when the related targets are useful for
|
||||
the observer's task - not as filler.
|
||||
|
||||
# Context
|
||||
@@ -201,8 +201,9 @@ export async function analyze({ apiKey, target, frames, spacedbMatches, question
|
||||
|
||||
// The analysis call reaches api.anthropic.com. A deploy with no outbound
|
||||
// network (or a blocked host) otherwise surfaces a bare "fetch failed";
|
||||
// classifyFetchError turns that into an actionable message, matching the
|
||||
// research tools. Generous timeout - a full analysis can take 30-60s.
|
||||
// classifyFetchError turns that into a message the operator can act on,
|
||||
// matching the
|
||||
// research tools. Generous timeout; a full analysis can take 30-60s.
|
||||
const ctrl = new AbortController();
|
||||
const timer = setTimeout(() => ctrl.abort(), ANALYSIS_TIMEOUT_MS);
|
||||
let res;
|
||||
|
||||
@@ -5,8 +5,8 @@ function nextTxn() { return ++_txn; }
|
||||
|
||||
// SSRF guard. Operators legitimately point drivers at LAN/loopback hosts
|
||||
// (ASCOM Alpaca runs on 192.168.x / 127.0.0.1), so we do NOT block private
|
||||
// ranges. We DO block the link-local 169.254.0.0/16 block - that's never a
|
||||
// telescope and is the cloud metadata service (169.254.169.254) - plus any
|
||||
// ranges. We DO block the link-local 169.254.0.0/16 block; that's never a
|
||||
// telescope and is the cloud metadata service (169.254.169.254), plus any
|
||||
// non-http(s) scheme. host may be a bare hostname or come from a URL.
|
||||
function assertAllowedHost(host) {
|
||||
const h = String(host || '').toLowerCase().replace(/^\[|\]$/g, '');
|
||||
@@ -213,7 +213,7 @@ export function startWeatherStationPolling(io) {
|
||||
async function pollAll() {
|
||||
// "Due to poll?" filter happens in JS so the query is portable across
|
||||
// MySQL and SQLite (MySQL has DATE_ADD/INTERVAL, SQLite doesn't share
|
||||
// the same syntax). N is small - at most one row per configured station.
|
||||
// the same syntax). N is small: at most one row per configured station.
|
||||
const all = await db.all('SELECT * FROM weather_stations WHERE enabled = 1');
|
||||
const now = Date.now();
|
||||
const stations = all.filter(s => {
|
||||
|
||||
@@ -119,8 +119,8 @@ export async function readTelescopeState(profile) {
|
||||
if (profile.driver_type !== 'alpaca') return null;
|
||||
const args = { host: profile.driver_host, port: profile.driver_port, deviceType: 'telescope', deviceNumber: profile.driver_device_number ?? 0 };
|
||||
// Capture the first probe failure so an unreachable mount reports WHY,
|
||||
// instead of silently returning all-null (which consumers - the Hardware
|
||||
// dashboard and the Nox resource strip - mis-read as "ok / reachable").
|
||||
// instead of silently returning all-null (which consumers such as the
|
||||
// Hardware dashboard and the Nox resource strip mis-read as "reachable").
|
||||
let firstErr = null;
|
||||
const probe = (action) => alpacaCall('GET', { ...args, action })
|
||||
.catch(e => { if (!firstErr) firstErr = e.message || String(e); return null; });
|
||||
@@ -129,7 +129,7 @@ export async function readTelescopeState(profile) {
|
||||
probe('tracking'), probe('name'),
|
||||
]);
|
||||
// A live Alpaca mount answers at least name + slewing. If every probe
|
||||
// failed, the server is unreachable - say so explicitly.
|
||||
// failed, the server is unreachable; say so explicitly.
|
||||
const reachable = [ra, dec, slewing, tracking, name].some(v => v !== null);
|
||||
if (!reachable) return { reachable: false, error: firstErr || 'unreachable' };
|
||||
return { reachable: true, ra, dec, slewing, tracking, name };
|
||||
|
||||
@@ -18,7 +18,7 @@ async function tick() {
|
||||
const status = appDb === 'up' ? 'ok' : 'degraded';
|
||||
// status/app_db/spacedb are VARCHAR(16). probeDb returns "down: <code>"
|
||||
// on failure (e.g. "down: ECONNREFUSED" = 18 chars) which overflows the
|
||||
// column and aborts the insert. Clamp to fit - the spark-bar keys off the
|
||||
// column and aborts the insert. Clamp to fit; the spark-bar keys off the
|
||||
// up/down prefix and only shows the rest as a tooltip detail.
|
||||
const fit = v => (v == null ? v : String(v).slice(0, 16));
|
||||
await db.run(
|
||||
@@ -35,7 +35,7 @@ async function tick() {
|
||||
export function startHealthHistory() {
|
||||
// First tick once the schema is ready so the spark-bar has at least one
|
||||
// cell on cold start. Gating on dbReady avoids racing the boot-time
|
||||
// initDb() that creates health_history - an un-gated immediate tick logged
|
||||
// initDb() that creates health_history; an un-gated immediate tick logged
|
||||
// a spurious "table doesn't exist" warning on every cold start (Sentry
|
||||
// CAELUMNETWORK-10). By the time the 60s interval fires the DDL is ready.
|
||||
dbReady.then(tick);
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
import { log } from './log.js';
|
||||
|
||||
let _fetch = (...a) => globalThis.fetch(...a);
|
||||
// Test seam - inject a fake fetch. Pass null to restore the real one.
|
||||
// Test seam: inject a fake fetch. Pass null to restore the real one.
|
||||
export function __setFetchForTest(fn) { _fetch = fn || ((...a) => globalThis.fetch(...a)); }
|
||||
|
||||
function crmCfg() { return { url: (process.env.CRM_API_URL || '').replace(/\/$/, ''), key: process.env.CRM_API_KEY || '' }; }
|
||||
@@ -111,7 +111,7 @@ export async function syncOrder(order, items) {
|
||||
partial.books_invoice_id = inv?.invoice?.id || null;
|
||||
}
|
||||
|
||||
// Payment - marks the invoice paid. Remote dedups by reference, so this is
|
||||
// Payment: marks the invoice paid. Remote dedups by reference, so this is
|
||||
// safe to re-run.
|
||||
if (partial.books_invoice_id) {
|
||||
await apiCall(cfg, `/api/books/invoices/${partial.books_invoice_id}/payments`, 'POST', {
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
// - a JSON file path (e.g. /etc/caelum/limits.json)
|
||||
// - an inline JSON string (e.g. '{"default":{"archive.frames_per_user":200}}')
|
||||
//
|
||||
// Schema (all keys are optional - a missing key means UNLIMITED):
|
||||
// Schema (all keys are optional; a missing key means UNLIMITED):
|
||||
// {
|
||||
// "default": { "<key>": <number>, ... },
|
||||
// "byRole": { "<role>": { "<key>": <number>, ... } }
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user