diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index b10b3c4..f9e4f8e 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -46,14 +46,17 @@ jobs: verify: needs: changes if: needs.changes.outputs.code == 'true' - runs-on: ubuntu-latest + runs-on: windows-latest + defaults: + run: + shell: bash steps: - uses: actions/checkout@v5 - uses: actions/setup-python@v6 with: - python-version: "3.11" - - name: Install CivicCore release wheel - run: python -m pip install https://github.com/CivicSuite/civiccore/releases/download/v0.3.0/civiccore-0.3.0-py3-none-any.whl + python-version: "3.13" + - name: Install Townlight Core pinned revision + run: python -m pip install "git+https://github.com/townlight/core.git@2f6ba9be4a95e3772dc47a3682ac780c5283b626" - name: Install package run: python -m pip install -e ".[dev]" - name: Run release gate diff --git a/AGENTS.md b/AGENTS.md index 64acad8..54af85e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,27 +2,31 @@ # Townlight Communications Agent Board -## Operating Contract +## Current contract -- Upstream suite spec: `townlight/townlight/docs/CivicSuiteUnifiedSpec.md`, especially the Townlight Communications catalog entry and suite-wide non-negotiables. -- Townlight Communications supports source-backed public explainers, meeting summaries, ordinance summaries, newsletters, FAQs, and audience-specific draft variants. -- AGPL-3.0-only for code (with the TownLight Public Institution Exception for qualifying deployments), CC BY 4.0 for documentation. -- Every change must keep docs, tests, browser QA evidence, and version surfaces in sync. +- Townlight Communications `0.2.0` is a development candidate. Scope is defined by `COMMUNICATIONS-DESIGN.md`; this file replaces superseded `0.1.1` prototype mandates. +- Windows only. Hold software tag and software publication until explicitly authorized. +- Canonical verification is the Windows suite runtime plus the named affected checks. Do not add extra gates. +- The standalone `main.py` is a prototype, not the production workflow server. -## Hard Boundaries +## Publication authority -- Townlight Communications never publishes autonomously, creates campaign or advocacy content, provides legal advice, certifies translations, posts to social media, or updates a communications system of record. -- Townlight Communications v0.1.1 must not call live LLMs or live publishing/social-media/communications systems. -- Every generated artifact is a draft requiring staff review, citation verification, approval, and publication through official city channels. -- Townlight Communications depends on Townlight Core; Townlight Core must never depend on Townlight Communications. -- Townlight Communications may reference Townlight Meetings, Townlight Code, and Townlight Access concepts only through released APIs or deterministic sample data in v0.1.1. +- Unattended publication is authorized ONLY for the exact staff-approved revision, through the host, to website and email. +- Do not add social, advertising/campaign, legal-advice, or translation-certification capabilities. +- No silent fallback: missing, private, stale, mismatched, or unapproved content must remain blocked and visibly reported. +- Reuse existing administrator, city-staff, and clerk roles and native authentication. -## Verification +## Source and history boundaries -Run before push or release: +- Preserve the private/public source boundary. Source eligibility is verified at runtime against the actual module; user-supplied eligibility flags cannot authorize publication. +- Revisions are immutable with SHA256 provenance. Editing clears approval and correction preserves prior revisions. +- Records archive must contain the exact published revision, source references, attachments, and receipts, and return a real identifier before any correction. +- Use explicit migrations and preserve existing affected headless checks. +- Preserve ordered correction and withdrawal sequences; stale content must not be resurrected. -```bash -bash scripts/verify-release.sh -``` +## Architecture and workflow -Browser QA evidence is required for `docs/index.html` and `/civiccomms` whenever visible UI changes. +- Preserve dependency direction: Townlight Core never depends on Townlight Communications. +- DeepSeek1017 performs low-risk implementation; Codex coordinates integration and review. +- Keep documentation, tests, and version surfaces synchronized with approved scope. +- Code is AGPL-3.0-only with the TownLight Public Institution Exception; documentation is CC BY 4.0. diff --git a/CHANGELOG.md b/CHANGELOG.md index 122b603..f7b845a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,17 @@ All notable changes to CivicComms will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). +## [Unreleased] + +### 0.2.0 candidate + +- Added editorial immutable revision approval and correction/withdrawal without reviving stale revisions. +- Added approved source snapshot and public attachment capture. +- Added scheduled website and email publication through the host service. +- Added subscriber confirmation, preference management, and unsubscribe support. +- Added Records archive storage for published bytes and receipts behind the separate Records permission. +- Not included in the released Windows 1.9.3.2 suite; installed candidate acceptance is still pending. + ## [0.1.1] - 2026-04-28 ### Added diff --git a/COMMUNICATIONS-DESIGN.md b/COMMUNICATIONS-DESIGN.md new file mode 100644 index 0000000..981cab7 --- /dev/null +++ b/COMMUNICATIONS-DESIGN.md @@ -0,0 +1,19 @@ +# Communications implementation design — approved scope + +Owner: Scott. Windows only. Build after311 source integration; installed acceptance in one combined signed candidate. No software tag/publication approval yet. + +## Interface and roles +Reuse staff shell/navigation, native session and existing administrator/city-staff/clerk grants. New Communications workspace: saved draft list/filter, source picker, editor, exact-revision preview, Access review, review/approval, schedule, delivery status, correction/withdrawal and Records archive. Resident portal: approved article list/detail, subscriptions/preferences/unsubscribe. No resident account exposes staff drafts or private source data. Keyboard navigation, labelled controls, errors beside fields, visible queued/delivered/failed states, destructive actions confirmed. + +## Durable domain contract +Use townlight-comms0.2.0 / townlight_comms, current townlight-core1.3.0.dev2. SQLAlchemy schema townlight_comms. Explicit migration; SQLite tests use schema translation, production bootstrap false. Immutable revisions with SHA256 canonical public content and source snapshots. Articles retain current revision/state, approval hash/actor/time, schedule and publication history. Edit clears approval; correction preserves old revision. Optimistic revision and database transactions prevent two-PC lost updates. HTML is not trusted: store/render plain text and escaped paragraphs. Attachments have actual bytes/hash/limits and public-review status. + +Source references carry kind,id,revision,title,public URL,digest and public eligibility verified by runtime against actual module. User-supplied eligibility flags cannot authorize publication. Supported kinds meetings/code/notice/311 aggregate/parks; parks connector completed in Parks phase. Missing/private/stale source blocks approval; manual authored source-backed content does not need AI. Access report and translations retain exact source/output and revision provenance; staff approval remains explicit. + +Publication task atomically snapshots exact approved revision, channels website/email and due time. Host claims due tasks with leases; native app need not stay open. Website manifest kind article travels through existing PublisherQueue/portal authenticated receiver, actual receipt URL/hash captured. Correction/withdrawal use ordered sequence, cannot resurrect stale content. Email uses existing311 SMTPTransport with separate Comms durable outbox: deterministic message ID, retries only known unsent, uncertain send is visible and not automatically retried. Subscriptions are opt-in, private tokens hashed, preferences/unsubscribe exclude future mail. No social/ad campaign channels. + +## Boundaries +Runtime /desktop/v1/communications under native staff auth; browser commands use fixed native allowlist and shared-host gateway, no arbitrary URL. Portal incoming resident operations use encrypted authenticated inbox/pump patterns; desktop service stays private. Records archive contains actual published revisions/source refs/attachments/receipts and returns real identifier; Data only explicit approved aggregate publication metrics if required by existing plan, no subscriber list. Reuse existing city configuration and encrypted SMTP settings, no new auth provider. + +## Meaningful acceptance +Domain tests prove edit invalidation, stale review, private source rejection, atomic concurrent edits, schedule leases, exact bytes, correction/withdrawal, subscriber privacy and safe retry. HTTP tests trace real receiving contracts and portal receiver, UI tests actual visible controls with explicit native doubles. Final installed Windows candidate proves staff two-PC sourced author/edit/approve/schedule, app closed host publishes to portal and controlled SMTP, correction/withdrawal/history/Records retrieval, restart survival. Source tests are not installed acceptance. diff --git a/README.md b/README.md index 60ced9d..b890a9d 100644 --- a/README.md +++ b/README.md @@ -1,65 +1,23 @@ -> **Parked foundation — outside the released Windows suite.** This repository contains exploratory/support code, not a completed Townlight product. It is not installed or supported by Windows 1.8.1.1. Historical examples, package names and dependency pins below describe this foundation and must not be used as current suite installation instructions. Use the [released Windows suite, current modules and acceptance limits](https://townlight.github.io/versions.html). +# Townlight Communications 0.2.0 development candidate - +Townlight Communications is the development candidate for the Townlight Windows staff Communications screen. It is not included in the released Windows 1.9.3.2 suite. Distribution name: `townlight-comms`; import name: `townlight_comms`; current dependency: Townlight Core 1.3.0.dev2 (`townlight-core 1.3.0.dev2`). -# Townlight Communications +The canonical application is the Communications workspace in the Townlight Windows staff shell, using existing administrator, city-staff and clerk roles, plus a separate Records permission for archive access. The repository's standalone `main.py` remains a prototype for draft helpers. It is not a secured workflow server, and its commands are not production deployment instructions. -Townlight Communications is the Townlight module for source-backed public explainers, meeting summaries, ordinance summaries, newsletters, FAQs, and audience-specific draft variants. +## Workflow -Current state: **v0.1.1 public communications foundation plus draft persistence release**. This repo ships a FastAPI package, health/root endpoints, documentation gates, deterministic source-readiness review, meeting summary draft outlines, optional database-backed source review and meeting summary draft records, ordinance explainer drafts, newsletter scaffolds, FAQ prompts, audience-variant drafts, and accessible public sample UI at `/civiccomms`. It does **not** ship autonomous publication, campaign or advocacy content, legal advice, certified translation, live LLM calls, social media posting, or communications system-of-record integrations. +- Draft and save content from selected Meetings, Code, Notice or 311 sources. The Parks adapter remains pending until the Parks phase. +- Run an Access check, review and approve one exact revision, then schedule website and email publication. +- Archive the published revision to Records BEFORE editing, correcting, or withdrawing it; Records access requires the separate Records permission. +- Correct or withdraw published content without reviving stale revisions. +- Capture approved source snapshots and public attachments. Private source content cannot be published. - +Publication is transactional: approved revision snapshots, website and email tasks, and status are durable in PostgreSQL. A host service claims due work with leases, so the native app need not stay open. The website path uses the existing authenticated portal receiver. -## What Townlight Communications Does +Website publication uses the host-configured portal credential and origin. Normal operation uses an unattended host service, not an operator's open window. Email uses city settings shared with 311 SMTP. Subscribers must confirm email and can manage preferences or unsubscribe. Queued means pending, not SMTP accepted. Only sent means SMTP accepted the message, not human receipt; failed and uncertain sends are shown separately, and uncertain sends are never retried automatically. -- Check that draft work starts from named source material and citations. -- Create deterministic meeting summary draft outlines. -- Persist source review and meeting summary draft records when `CIVICCOMMS_DRAFT_DB_URL` is configured. -- Create plain-language ordinance explainer draft scaffolds. -- Build newsletter and FAQ draft structures from source items. -- Produce audience-specific variants without changing source facts. -- Demonstrate a public communications-support UI at `/civiccomms`. +The Records archive stores actual published bytes and receipts and returns a real identifier. It requires the separate Records role permission. - +Status: source-level checks passed for this development candidate, but installed Windows candidate acceptance is still pending. Do not describe this module as completed or released. The existing download at https://github.com/townlight/townlight/releases/latest explicitly does not include Communications. -## What Townlight Communications Does Not Do - -- It does not publish or post autonomously. -- It does not produce campaign, advocacy, or partisan content. -- It does not provide legal advice. -- It does not certify translations or accessibility compliance. -- It does not call live LLMs in v0.1.1. -- It does not replace a communications system of record. - -## API Surface - -- `GET /` returns the shipped/planned boundary. -- `GET /health` returns package and Townlight Core versions. -- `GET /civiccomms` returns the accessible public sample UI. -- `POST /api/v1/civiccomms/source-review` returns source-readiness checks. -- `GET /api/v1/civiccomms/source-review/{review_id}` retrieves a persisted source review when `CIVICCOMMS_DRAFT_DB_URL` is configured. -- `POST /api/v1/civiccomms/meeting-summary` returns a meeting summary draft outline and a `summary_id` when persistence is configured. -- `GET /api/v1/civiccomms/meeting-summary/{summary_id}` retrieves a persisted meeting summary when `CIVICCOMMS_DRAFT_DB_URL` is configured. -- `POST /api/v1/civiccomms/ordinance-summary` returns a plain-language explainer draft. -- `POST /api/v1/civiccomms/newsletter` returns a newsletter draft outline. -- `POST /api/v1/civiccomms/faq` returns source-backed FAQ prompts. -- `POST /api/v1/civiccomms/audience-variant` returns an audience-specific draft variant. - -## Optional Persistence - -Set `CIVICCOMMS_DRAFT_DB_URL` to enable local SQLAlchemy-backed source review and meeting summary records. Without that variable, Townlight Communications remains deterministic and stateless. Retrieval endpoints return actionable `503` responses that name the required configuration. - -## Local Development - -Townlight Communications v0.1.1 is pinned to `civiccore==0.3.0`. - -```bash -python -m pip install -e ".[dev]" -python -m pytest -q -bash scripts/verify-release.sh -``` - -## License - -Code: AGPL-3.0-only, with the TownLight Public Institution Exception for qualifying deployments. See [LICENSE](LICENSE) and [LICENSE-EXCEPTION.md](LICENSE-EXCEPTION.md). -Documentation is CC BY 4.0. +License: code AGPL-3.0-only with the TownLight Public Institution Exception; documentation CC BY 4.0. diff --git a/README.txt b/README.txt index 690e0a0..b890a9d 100644 --- a/README.txt +++ b/README.txt @@ -1,56 +1,23 @@ - Parked foundation — outside the released Windows suite. This repository contains exploratory/support code, not a completed Townlight product. It is not installed or supported by Windows 1.8.1.1. Historical examples, package names and dependency pins below describe this foundation and must not be used as current suite installation instructions. Use the released Windows suite, current modules and acceptance limits. +# Townlight Communications 0.2.0 development candidate -Townlight Communications +Townlight Communications is the development candidate for the Townlight Windows staff Communications screen. It is not included in the released Windows 1.9.3.2 suite. Distribution name: `townlight-comms`; import name: `townlight_comms`; current dependency: Townlight Core 1.3.0.dev2 (`townlight-core 1.3.0.dev2`). -Townlight Communications is the Townlight module for source-backed public explainers, meeting summaries, ordinance summaries, newsletters, FAQs, and audience-specific draft variants. +The canonical application is the Communications workspace in the Townlight Windows staff shell, using existing administrator, city-staff and clerk roles, plus a separate Records permission for archive access. The repository's standalone `main.py` remains a prototype for draft helpers. It is not a secured workflow server, and its commands are not production deployment instructions. -Current state: v0.1.1 public communications foundation plus draft persistence release. This repo ships a FastAPI package, health/root endpoints, documentation gates, deterministic source-readiness review, meeting summary draft outlines, optional database-backed source review and meeting summary draft records, ordinance explainer drafts, newsletter scaffolds, FAQ prompts, audience-variant drafts, and accessible public sample UI at /civiccomms. It does not ship autonomous publication, campaign or advocacy content, legal advice, certified translation, live LLM calls, social media posting, or communications system-of-record integrations. +## Workflow -What Townlight Communications Does +- Draft and save content from selected Meetings, Code, Notice or 311 sources. The Parks adapter remains pending until the Parks phase. +- Run an Access check, review and approve one exact revision, then schedule website and email publication. +- Archive the published revision to Records BEFORE editing, correcting, or withdrawing it; Records access requires the separate Records permission. +- Correct or withdraw published content without reviving stale revisions. +- Capture approved source snapshots and public attachments. Private source content cannot be published. -- Check that draft work starts from named source material and citations. -- Create deterministic meeting summary draft outlines. -- Persist source review and meeting summary draft records when CIVICCOMMS_DRAFT_DB_URL is configured. -- Create plain-language ordinance explainer draft scaffolds. -- Build newsletter and FAQ draft structures from source items. -- Produce audience-specific variants without changing source facts. -- Demonstrate a public communications-support UI at /civiccomms. +Publication is transactional: approved revision snapshots, website and email tasks, and status are durable in PostgreSQL. A host service claims due work with leases, so the native app need not stay open. The website path uses the existing authenticated portal receiver. -What Townlight Communications Does Not Do +Website publication uses the host-configured portal credential and origin. Normal operation uses an unattended host service, not an operator's open window. Email uses city settings shared with 311 SMTP. Subscribers must confirm email and can manage preferences or unsubscribe. Queued means pending, not SMTP accepted. Only sent means SMTP accepted the message, not human receipt; failed and uncertain sends are shown separately, and uncertain sends are never retried automatically. -- It does not publish or post autonomously. -- It does not produce campaign, advocacy, or partisan content. -- It does not provide legal advice. -- It does not certify translations or accessibility compliance. -- It does not call live LLMs in v0.1.1. -- It does not replace a communications system of record. +The Records archive stores actual published bytes and receipts and returns a real identifier. It requires the separate Records role permission. -API Surface +Status: source-level checks passed for this development candidate, but installed Windows candidate acceptance is still pending. Do not describe this module as completed or released. The existing download at https://github.com/townlight/townlight/releases/latest explicitly does not include Communications. -- GET / returns the shipped/planned boundary. -- GET /health returns package and Townlight Core versions. -- GET /civiccomms returns the accessible public sample UI. -- POST /api/v1/civiccomms/source-review returns source-readiness checks. -- GET /api/v1/civiccomms/source-review/{review_id} retrieves a persisted source review when CIVICCOMMS_DRAFT_DB_URL is configured. -- POST /api/v1/civiccomms/meeting-summary returns a meeting summary draft outline and a summary_id when persistence is configured. -- GET /api/v1/civiccomms/meeting-summary/{summary_id} retrieves a persisted meeting summary when CIVICCOMMS_DRAFT_DB_URL is configured. -- POST /api/v1/civiccomms/ordinance-summary returns a plain-language explainer draft. -- POST /api/v1/civiccomms/newsletter returns a newsletter draft outline. -- POST /api/v1/civiccomms/faq returns source-backed FAQ prompts. -- POST /api/v1/civiccomms/audience-variant returns an audience-specific draft variant. - -Optional Persistence - -Set CIVICCOMMS_DRAFT_DB_URL to enable local SQLAlchemy-backed source review and meeting summary records. Without that variable, Townlight Communications remains deterministic and stateless. Retrieval endpoints return actionable 503 responses that name the required configuration. - -Local Development - -Townlight Communications v0.1.1 is pinned to civiccore==0.3.0. - - python -m pip install -e ".[dev]" - python -m pytest -q - bash scripts/verify-release.sh - -License - -Code: AGPL-3.0-only, with the TownLight Public Institution Exception for qualifying deployments. See LICENSE and LICENSE-EXCEPTION.md. Documentation is CC BY 4.0. +License: code AGPL-3.0-only with the TownLight Public Institution Exception; documentation CC BY 4.0. diff --git a/USER-MANUAL.md b/USER-MANUAL.md index 1cc31ba..e0be4ee 100644 --- a/USER-MANUAL.md +++ b/USER-MANUAL.md @@ -1,49 +1,51 @@ - +# Townlight Communications 0.2.0 User Manual -# Townlight Communications User Manual +## Status and scope -## For Non-Technical Users +Townlight Communications 0.2.0 is a development candidate for the Townlight Windows staff Communications screen. It is not part of the released Windows 1.9.3.2 suite. Distribution name: `townlight-comms`; import name: `townlight_comms`; current dependency: Townlight Core 1.3.0.dev2 (`townlight-core 1.3.0.dev2`). -Townlight Communications helps staff turn city source material into public-facing draft communications. It can review whether sources and citations are present, outline meeting summaries, draft ordinance explainers, structure newsletters, suggest FAQ prompts, and create audience-specific variants. +The canonical application is the Communications workspace in the Townlight Windows staff shell with existing administrator, city-staff and clerk roles. A separate Records permission controls archive retrieval. The standalone `main.py` in this repository remains a prototype for draft helpers; it is not a secured workflow server or production deployment procedure. -Current state: `0.1.1` public communications foundation plus draft persistence release. Townlight Communications can optionally save source review and meeting summary draft records when IT configures `CIVICCOMMS_DRAFT_DB_URL`. Townlight Communications does not publish or post autonomously, create campaign or advocacy content, provide legal advice, certify translations, call live LLMs, post to social media, or replace a communications system of record. Staff own every draft, citation, approval, and publication decision. +## Staff workflow -## For IT and Technical Staff +1. Create or reopen a draft. Select sources from Meetings, Code, Notice or 311. The Parks adapter stays pending until the Parks phase. +2. Save the draft and run an Access check. Review and approve one exact revision. Approval applies to that revision only; later edits clear it. +3. Schedule publication to the website and email for the approved revision. +4. Publish, then archive the published revision to Records BEFORE editing, correcting, or withdrawing it; Records access requires the separate Records permission. Corrections preserve prior revisions, and withdrawal prevents stale content from being restored. -Townlight Communications is a FastAPI Python package pinned to `civiccore==0.3.0`. The current runtime exposes: +Captured approved source snapshots, public URLs, digests and revision provenance remain with the article. Public attachments require review. Private source content cannot be published, and missing, private or stale sources block approval. -- `GET /` -- `GET /health` -- `GET /civiccomms` -- `POST /api/v1/civiccomms/source-review` -- `GET /api/v1/civiccomms/source-review/{review_id}` -- `POST /api/v1/civiccomms/meeting-summary` -- `GET /api/v1/civiccomms/meeting-summary/{summary_id}` -- `POST /api/v1/civiccomms/ordinance-summary` -- `POST /api/v1/civiccomms/newsletter` -- `POST /api/v1/civiccomms/faq` -- `POST /api/v1/civiccomms/audience-variant` +## Portal, email and delivery -Run: +The host configuration supplies the portal credential and origin. Normal operation uses an unattended host service, not an operator window, so scheduled work can complete after the staff app closes. Website tasks travel through the existing authenticated portal receiver, with receipt URL and hash retained. -```bash -python -m pip install -e ".[dev]" -python -m pytest -q -bash scripts/verify-release.sh -``` +Email uses the city email settings shared with 311 SMTP. Subscribers must confirm their email address and can manage preferences or unsubscribe. Queued means pending, not SMTP accepted. Only sent means SMTP accepted the message, not human receipt. Failed and uncertain results are shown separately, and an uncertain send is never retried automatically. Deterministic message identifiers and durable records support safe retries only when non-delivery is known. + +## Records and roles + +The Records archive stores the actual published bytes, source references, attachments and receipts, and returns a real identifier. It requires the separate Records role permission. Existing staff roles continue to control drafting, review and approval; no resident account can see staff drafts or private source data. Publication metrics are limited to explicit approved aggregate reporting, not subscriber lists. + +## Acceptance status -Set `CIVICCOMMS_DRAFT_DB_URL` to enable local SQLAlchemy-backed source review and meeting summary draft records. If the variable is not set, Townlight Communications keeps deterministic stateless behavior and retrieval endpoints return actionable configuration guidance. +Source-level checks passed for this development candidate, but installed Windows candidate acceptance remains pending. Acceptance must prove staff two-PC authoring, exact-revision approval, scheduling, app-closed host publication to the portal and controlled SMTP, correction and withdrawal, restart survival, and Records retrieval. Source tests are not installed acceptance. Do not describe this module as completed or released. The existing download at https://github.com/townlight/townlight/releases/latest explicitly does not include Communications. -## Architecture +## Technical architecture ```mermaid flowchart LR - Clerk["Clerk / communications staff"] --> CivicComms["CivicComms"] - CivicClerk["CivicClerk sources"] -. future connector .-> CivicComms - CivicCode["CivicCode sources"] -. future connector .-> CivicComms - CivicAccess["CivicAccess review"] -. future handoff .-> CivicComms - CivicComms --> CivicCore["CivicCore v0.3.0"] - CivicComms --> Drafts["Human-approved draft artifacts"] + UI["TypeScript staff UI"] --> Native["Fixed native command"] + Native --> API["Loopback staff API"] + API --> DB[("PostgreSQL durable records")] + DB --> Queue["Durable queue"] + Queue --> Worker["Host worker with task leases"] + Worker --> Portal["Authenticated portal receiver"] + Worker --> SMTP["City SMTP shared with 311"] ``` -Townlight Communications depends on Townlight Core. Townlight Core does not depend on Townlight Communications. Townlight Communications v0.1.1 uses deterministic sample source-backed drafting plus optional local draft persistence; autonomous publication, campaign or advocacy content, legal advice, certified translation, live LLM calls, social media posting, and production communications-system integrations are future work. +The desktop runtime is `/desktop/v1/communications`, protected by native staff authentication. Browser requests use a fixed native command allowlist and cannot choose arbitrary URLs. Portal inbound operations use encrypted authenticated inbox and pump patterns; the desktop service remains private. Production uses a real PostgreSQL schema with explicit migration; SQLite translation is for tests, and production bootstrap is false. Revisions are immutable and approval binds the exact public-content hash. Optimistic revisions and database transactions prevent two-PC lost updates. Plain text is stored and escaped paragraphs are rendered; HTML is not trusted. + +Source eligibility is checked at runtime against the owning module; user-supplied flags cannot authorize publication. The email outbox has durable state separate from 311, and subscriber tokens are hashed and private. The host service owns portal credentials and origin configuration. + +Back up database data, profile keys, durable queue work and Records files as one unit. The product does not provide Mac or Linux installation instructions. + +Documentation authoring and translation provenance are recorded separately from product implementation. diff --git a/USER-MANUAL.txt b/USER-MANUAL.txt index 1d99b9e..e0be4ee 100644 --- a/USER-MANUAL.txt +++ b/USER-MANUAL.txt @@ -1,39 +1,51 @@ -Townlight Communications User Manual -====================== +# Townlight Communications 0.2.0 User Manual -For Non-Technical Users ------------------------ +## Status and scope -Townlight Communications helps staff turn city source material into public-facing draft communications. It can review whether sources and citations are present, outline meeting summaries, draft ordinance explainers, structure newsletters, suggest FAQ prompts, and create audience-specific variants. +Townlight Communications 0.2.0 is a development candidate for the Townlight Windows staff Communications screen. It is not part of the released Windows 1.9.3.2 suite. Distribution name: `townlight-comms`; import name: `townlight_comms`; current dependency: Townlight Core 1.3.0.dev2 (`townlight-core 1.3.0.dev2`). -Current state: 0.1.1 public communications foundation plus draft persistence release. Townlight Communications can optionally save source review and meeting summary draft records when IT configures CIVICCOMMS_DRAFT_DB_URL. Townlight Communications does not publish or post autonomously, create campaign or advocacy content, provide legal advice, certify translations, call live LLMs, post to social media, or replace a communications system of record. Staff own every draft, citation, approval, and publication decision. +The canonical application is the Communications workspace in the Townlight Windows staff shell with existing administrator, city-staff and clerk roles. A separate Records permission controls archive retrieval. The standalone `main.py` in this repository remains a prototype for draft helpers; it is not a secured workflow server or production deployment procedure. -For IT and Technical Staff --------------------------- +## Staff workflow -Townlight Communications is a FastAPI Python package pinned to civiccore==0.3.0. The current runtime exposes: +1. Create or reopen a draft. Select sources from Meetings, Code, Notice or 311. The Parks adapter stays pending until the Parks phase. +2. Save the draft and run an Access check. Review and approve one exact revision. Approval applies to that revision only; later edits clear it. +3. Schedule publication to the website and email for the approved revision. +4. Publish, then archive the published revision to Records BEFORE editing, correcting, or withdrawing it; Records access requires the separate Records permission. Corrections preserve prior revisions, and withdrawal prevents stale content from being restored. -- GET / -- GET /health -- GET /civiccomms -- POST /api/v1/civiccomms/source-review -- GET /api/v1/civiccomms/source-review/{review_id} -- POST /api/v1/civiccomms/meeting-summary -- GET /api/v1/civiccomms/meeting-summary/{summary_id} -- POST /api/v1/civiccomms/ordinance-summary -- POST /api/v1/civiccomms/newsletter -- POST /api/v1/civiccomms/faq -- POST /api/v1/civiccomms/audience-variant +Captured approved source snapshots, public URLs, digests and revision provenance remain with the article. Public attachments require review. Private source content cannot be published, and missing, private or stale sources block approval. -Run: +## Portal, email and delivery -python -m pip install -e ".[dev]" -python -m pytest -q -bash scripts/verify-release.sh +The host configuration supplies the portal credential and origin. Normal operation uses an unattended host service, not an operator window, so scheduled work can complete after the staff app closes. Website tasks travel through the existing authenticated portal receiver, with receipt URL and hash retained. -Set CIVICCOMMS_DRAFT_DB_URL to enable local SQLAlchemy-backed source review and meeting summary draft records. If the variable is not set, Townlight Communications keeps deterministic stateless behavior and retrieval endpoints return actionable configuration guidance. +Email uses the city email settings shared with 311 SMTP. Subscribers must confirm their email address and can manage preferences or unsubscribe. Queued means pending, not SMTP accepted. Only sent means SMTP accepted the message, not human receipt. Failed and uncertain results are shown separately, and an uncertain send is never retried automatically. Deterministic message identifiers and durable records support safe retries only when non-delivery is known. -Architecture ------------- +## Records and roles -Townlight Communications depends on Townlight Core. Townlight Core does not depend on Townlight Communications. Townlight Communications v0.1.1 uses deterministic sample source-backed drafting plus optional local draft persistence; autonomous publication, campaign or advocacy content, legal advice, certified translation, live LLM calls, social media posting, and production communications-system integrations are future work. +The Records archive stores the actual published bytes, source references, attachments and receipts, and returns a real identifier. It requires the separate Records role permission. Existing staff roles continue to control drafting, review and approval; no resident account can see staff drafts or private source data. Publication metrics are limited to explicit approved aggregate reporting, not subscriber lists. + +## Acceptance status + +Source-level checks passed for this development candidate, but installed Windows candidate acceptance remains pending. Acceptance must prove staff two-PC authoring, exact-revision approval, scheduling, app-closed host publication to the portal and controlled SMTP, correction and withdrawal, restart survival, and Records retrieval. Source tests are not installed acceptance. Do not describe this module as completed or released. The existing download at https://github.com/townlight/townlight/releases/latest explicitly does not include Communications. + +## Technical architecture + +```mermaid +flowchart LR + UI["TypeScript staff UI"] --> Native["Fixed native command"] + Native --> API["Loopback staff API"] + API --> DB[("PostgreSQL durable records")] + DB --> Queue["Durable queue"] + Queue --> Worker["Host worker with task leases"] + Worker --> Portal["Authenticated portal receiver"] + Worker --> SMTP["City SMTP shared with 311"] +``` + +The desktop runtime is `/desktop/v1/communications`, protected by native staff authentication. Browser requests use a fixed native command allowlist and cannot choose arbitrary URLs. Portal inbound operations use encrypted authenticated inbox and pump patterns; the desktop service remains private. Production uses a real PostgreSQL schema with explicit migration; SQLite translation is for tests, and production bootstrap is false. Revisions are immutable and approval binds the exact public-content hash. Optimistic revisions and database transactions prevent two-PC lost updates. Plain text is stored and escaped paragraphs are rendered; HTML is not trusted. + +Source eligibility is checked at runtime against the owning module; user-supplied flags cannot authorize publication. The email outbox has durable state separate from 311, and subscriber tokens are hashed and private. The host service owns portal credentials and origin configuration. + +Back up database data, profile keys, durable queue work and Records files as one unit. The product does not provide Mac or Linux installation instructions. + +Documentation authoring and translation provenance are recorded separately from product implementation. diff --git a/docs/index.html b/docs/index.html index af73df0..d918c68 100644 --- a/docs/index.html +++ b/docs/index.html @@ -3,26 +3,216 @@ -Townlight Communications - source-backed public communications support +Townlight Communications 0.2.0 — development candidate + + +

Townlight / Townlight Communications

-

Explain city work without losing the source trail.

-

Townlight Communications v0.1.1 ships a foundation for source-readiness review, meeting summary outlines, optional database-backed draft records, ordinance explainers, newsletters, FAQ prompts, and audience-specific draft variants.

-

Shipping v0.1.1

+

Source-backed public communications.

+

Townlight Communications is a Windows suite integration for drafting, reviewing, approving, scheduling, correcting, and archiving city communications while keeping the source trail attached.

+

Development candidate 0.2.0

+
+

Not the current release. This is a Townlight Communications 0.2.0 development candidate. The current Townlight suite release is 1.9.3.2, and that released suite does not yet include Communications.

+
+
-
-
-

What ships

  • Source-readiness checks.
  • Meeting summary draft outlines.
  • Optional draft persistence with CIVICCOMMS_DRAFT_DB_URL.
  • Ordinance explainer drafts.
  • Newsletter and FAQ scaffolds.
  • Audience variant drafts.
  • Public sample UI at /civiccomms.
-

What does not ship

Townlight Communications does not publish autonomously, create campaign or advocacy content, provide legal advice, certify translations, call live LLMs, post to social media, or replace a communications system of record.

- -

Dependency

Pinned to civiccore==0.3.0. Townlight Core remains dependency-only; it never imports from Townlight Communications.

+ +
+
+
+

Workflow

+

How it works

+

Each public item follows an explicit path from source selection to a durable public record. Staff approval stays human and tied to the exact revision reviewed.

+
+
    +
  1. Source
    Select a supported source and verify that it is public, current, and eligible for publication.
  2. +
  3. Draft
    Draft in plain text with source references attached. Editing clears prior approval.
  4. +
  5. Review
    Preview the exact revision, access report, and source snapshots before sign-off.
  6. +
  7. Approve and schedule
    Record the approval hash, actor, and time; schedule portal or email delivery.
  8. +
  9. Publish and preserve
    Capture receipts, corrections, withdrawals, source snapshots, and a Records archive entry.
  10. +
+
+ +
+
+

Planned product surface

+

Capabilities in the 0.2.0 candidate

+

These are source-under-development capabilities, not a claim that the current 1.9.3.2 suite release contains them.

+
+
+
+

Drafting and review

+
    +
  • Source-backed draft review with public eligibility checked at runtime.
  • +
  • Exact-revision previews and explicit human approvals.
  • +
  • Edit invalidation, stale-review prevention, and optimistic revision checks across two-PC work.
  • +
+
+
+

Publishing and history

+
    +
  • Scheduled publication to the resident portal and email.
  • +
  • Correction and withdrawal with ordered publication history.
  • +
  • Source snapshots and a Records archive containing published revisions and receipts.
  • +
+
+
+

Resident experience

+
    +
  • Approved article list and detail in the resident portal.
  • +
  • Subscriber confirmation, preferences, and unsubscribe.
  • +
  • No resident access to staff drafts or private source data.
  • +
+
+
+

Evidence and controls

+
    +
  • Source references retain kind, identifier, revision, digest, and public URL.
  • +
  • Approval hashes and content digests support exact-revision accountability.
  • +
  • Visible queued, delivered, and failed states; destructive actions require confirmation.
  • +
+
+
+
+ +
+
+

Interface outline

+

Screens, without mock screenshots

+

A textual inventory is used here. No screenshots or usage metrics are presented because installed acceptance is not complete.

+
+
+
+

Staff Communications workspace

+

Saved draft list and filters, source picker, plain-text editor, exact-revision preview, Access review, approval, scheduling, delivery status, correction and withdrawal, and Records archive.

+
+
+

Resident portal

+

Approved article list and article detail, plus subscription confirmation, preferences, and unsubscribe. Staff drafts and private source data are not exposed.

+
+
+
+ +
+
+

Responsibility

+

Roles and handoffs

+

The design reuses the existing staff shell and existing administrator, city-staff, and clerk grants. No new authentication provider is introduced.

+
+
+

Author or editor

Selects sources, prepares plain text, and resolves source or access issues beside the relevant field.

+

Reviewer or clerk

Reviews the exact revision and access report, records explicit approval, and schedules the approved item.

+

IT or city operator

Uses the Windows suite and existing city configuration, including encrypted SMTP settings. There is no package or pip installation path for the city operator.

+

Resident subscriber

Confirms opt-in, manages preferences or unsubscribes, and reads only approved public articles.

+
+
+ +
+
+

Deployment

+

IT configuration

+
+
+
+
    +
  • Platform: Windows suite integration; the Communications source is under development.
  • +
  • Identity: native staff authentication and existing administrator, city-staff, and clerk grants.
  • +
  • Runtime boundary: native staff gateway under /desktop/v1/communications; fixed allowlisted browser commands, with no arbitrary URL access.
  • +
  • Data: durable Communications domain with immutable revisions, source snapshots, approvals, schedules, delivery state, and Records archive.
  • +
  • Email: existing city SMTP transport and encrypted settings, with a separate Communications outbox and visible uncertain-send state.
  • +
  • Installation: delivered through the signed Windows suite candidate. This page does not provide package installation instructions.
  • +
+
+
+
+ +
+
+

Scope boundaries

+

Limits and non-claims

+
+
+
+

Not included

+
    +
  • No social channels.
  • +
  • No AI automation.
  • +
  • No autonomous publication.
  • +
  • No campaign or advocacy content.
  • +
  • No legal advice or certified translations.
  • +
+
+
+

Human control

+

Staff approval remains explicit. Missing, private, or stale sources block approval. Manual source-backed content does not require AI. Subscriptions are opt-in, and future mail excludes unsubscribed recipients.

+
+
+

Parks integration

+

Parks source integration is pending.

+
+
+
+ +
+
+

Status

+

Source versus installed evidence

+

Source design and source tests are not installed acceptance. The final evidence must come from the combined signed Windows candidate.

+
+
+ + + + + + + + + +
Current evidence status
ItemStatusWhat it proves
Townlight Communications 0.2.0Development candidateSource and design work for Windows suite integration; not a released product.
Townlight suite 1.9.3.2Current suite releaseExisting released suite does not yet include Communications.
Installed Windows acceptancePendingMust prove staff authoring, approval, scheduling, portal and SMTP delivery, correction, history, Records retrieval, and restart survival.
Parks source connectorPendingParks source integration is not complete.
+
+
+ +
+
+

Repository

+ +

Repository documentation is the source of record. This landing page does not publish a release or replace the project manual.

+
+
-

AGPL-3.0 code. CC BY 4.0 docs. Run locally by the city.

+ +
+

Townlight Communications 0.2.0 development candidate. Current Townlight suite release: 1.9.3.2, which does not include Communications. AGPL-3.0 code; CC BY 4.0 documentation.

+
diff --git a/pyproject.toml b/pyproject.toml index e8259c9..7e79a6f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -3,20 +3,21 @@ requires = ["hatchling>=1.27.0"] build-backend = "hatchling.build" [project] -name = "civiccomms" -version = "0.1.1" +name = "townlight-comms" +version = "0.2.0" description = "Townlight Communications runtime foundation for source-backed public explainers, meeting summaries, newsletters, FAQs, and audience variants." readme = "README.md" requires-python = ">=3.11" license = { text = "AGPL-3.0-only" } authors = [ - { name = "CivicSuite contributors" } + { name = "Townlight contributors" } ] dependencies = [ - "civiccore==0.3.0", + "townlight-core==1.3.0.dev2", "fastapi>=0.115.0,<1.0.0", "sqlalchemy>=2.0.0,<3.0.0", "uvicorn[standard]>=0.30.0,<1.0.0", + "cryptography>=44,<47", ] [project.optional-dependencies] @@ -32,11 +33,11 @@ dev = [ testpaths = ["tests"] [tool.hatch.build.targets.wheel] -packages = ["civiccomms"] +packages = ["townlight_comms"] [tool.hatch.build.targets.sdist] include = [ - "civiccomms", + "townlight_comms", "scripts", "tests", "README.md", diff --git a/scripts/check-civiccore-placeholder-imports.py b/scripts/check-civiccore-placeholder-imports.py index ba6fb35..4d5e38b 100644 --- a/scripts/check-civiccore-placeholder-imports.py +++ b/scripts/check-civiccore-placeholder-imports.py @@ -1,4 +1,4 @@ -"""Fail if CivicComms imports CivicCore placeholder packages.""" +"""Fail if Townlight Communications imports CivicCore placeholder packages.""" from __future__ import annotations @@ -20,8 +20,8 @@ "verification", } -SOURCE_ROOT = Path("civiccomms") -PATTERN = re.compile(r"^\s*(?:from|import)\s+civiccore\.([a-zA-Z_][a-zA-Z0-9_]*)", re.M) +SOURCE_ROOT = Path("townlight_comms") +PATTERN = re.compile(r"^\s*(?:from|import)\s+townlight_core\.([a-zA-Z_][a-zA-Z0-9_]*)", re.MULTILINE) def main() -> int: @@ -34,7 +34,7 @@ def main() -> int: package = match.group(1) if package in PLACEHOLDERS: failures.append( - f"{path}: civiccore.{package} is a placeholder package in v0.3.0. " + f"{path}: townlight_core.{package} is a placeholder package in v1.3.0.dev2. " "See AGENTS.md section 3.1." ) if failures: diff --git a/scripts/verify-docs.sh b/scripts/verify-docs.sh index bdf8cf8..81cfddb 100644 --- a/scripts/verify-docs.sh +++ b/scripts/verify-docs.sh @@ -30,12 +30,12 @@ for file in "${required[@]}"; do done echo "==> Current-facing shipped/planned truth check" -if grep -RInE 'Civic311|civic311|Open311|system-of-record integrations are online|autonomous publication is implemented|campaign content is supported|legal advice is implemented|live LLM calls are online' README.md README.txt USER-MANUAL.md USER-MANUAL.txt docs/index.html CHANGELOG.md; then - echo "FAIL: stale or overstated CivicComms copy found" >&2 +if grep -RInE 'system-of-record integrations are online|autonomous publication is implemented|campaign content is supported|legal advice is implemented|live LLM calls are online' README.md README.txt USER-MANUAL.md USER-MANUAL.txt docs/index.html; then + echo "FAIL: stale or overstated Townlight Communications copy found" >&2 exit 1 fi -for token in "Townlight Communications" civiccomms "v0.1.1" "civiccore==0.3.0"; do +for token in "Townlight Communications" "candidate" "Windows" "0.2.0" "townlight-comms" "townlight_comms" "Core" "1.3.0.dev2"; do if ! grep -RIn "$token" README.md USER-MANUAL.md docs/index.html CHANGELOG.md >/dev/null; then echo "FAIL: expected token missing from current-facing docs: $token" >&2 exit 1 diff --git a/scripts/verify-release.sh b/scripts/verify-release.sh index 6d5d198..5d2fc72 100644 --- a/scripts/verify-release.sh +++ b/scripts/verify-release.sh @@ -1,14 +1,13 @@ #!/usr/bin/env bash set -euo pipefail -VERSION="0.1.1" +VERSION="0.2.0" python_cmd() { local candidates=() - if [[ -n "${CIVICCOMMS_RELEASE_PYTHON:-}" ]]; then - candidates+=("${CIVICCOMMS_RELEASE_PYTHON}") + if [[ -n "${TOWNLIGHT_COMMS_RELEASE_PYTHON:-}" ]]; then + candidates+=("${TOWNLIGHT_COMMS_RELEASE_PYTHON}") fi - candidates+=("/mnt/c/Users/scott/AppData/Local/Microsoft/WindowsApps/python.exe") candidates+=(python python3 "py -3") for candidate in "${candidates[@]}"; do @@ -33,14 +32,15 @@ import tomllib root = Path.cwd() pyproject = tomllib.loads((root / "pyproject.toml").read_text(encoding="utf-8")) version = pyproject["project"]["version"] -init = (root / "civiccomms" / "__init__.py").read_text(encoding="utf-8") +init = (root / "townlight_comms" / "__init__.py").read_text(encoding="utf-8") readme = (root / "README.md").read_text(encoding="utf-8") changelog = (root / "CHANGELOG.md").read_text(encoding="utf-8") -assert version == "0.1.1", version -assert '__version__ = "0.1.1"' in init -assert "v0.1.1" in readme -assert "## [0.1.1] - 2026-04-28" in changelog -assert "civiccore==0.3.0" in readme +assert version == "0.2.0", version +assert '__version__ = "0.2.0"' in init +assert "Townlight Communications 0.2.0 development candidate" in readme +assert "## [Unreleased]" in changelog +assert "### 0.2.0 candidate" in changelog +assert "townlight-core 1.3.0.dev2" in readme print("PASS: version surfaces synchronized") PY @@ -57,15 +57,15 @@ echo "==> Ruff" "$PYTHON" -m ruff check . echo "==> Build artifacts" -rm -rf dist -"$PYTHON" -m build +mkdir -p "dist/${VERSION}" +"$PYTHON" -m build --outdir "dist/${VERSION}" ( - cd dist - sha256sum civiccomms-0.1.1-py3-none-any.whl civiccomms-0.1.1.tar.gz > SHA256SUMS.txt + cd "dist/${VERSION}" + sha256sum "townlight_comms-${VERSION}-py3-none-any.whl" "townlight_comms-${VERSION}.tar.gz" > SHA256SUMS.txt ) -test -f dist/civiccomms-0.1.1-py3-none-any.whl -test -f dist/civiccomms-0.1.1.tar.gz -test -s dist/SHA256SUMS.txt +test -f "dist/${VERSION}/townlight_comms-${VERSION}-py3-none-any.whl" +test -f "dist/${VERSION}/townlight_comms-${VERSION}.tar.gz" +test -s "dist/${VERSION}/SHA256SUMS.txt" echo "PASS: build artifacts and SHA256SUMS.txt created" echo "VERIFY-RELEASE: PASSED" diff --git a/tests/test_article_attachments.py b/tests/test_article_attachments.py new file mode 100644 index 0000000..6218030 --- /dev/null +++ b/tests/test_article_attachments.py @@ -0,0 +1,158 @@ +"""Real attachment workflow tests against SQLite-backed repository state.""" +import hashlib +import os +import tempfile +import unittest + +from sqlalchemy import create_engine, func, select, update + +from townlight_comms import migrations +from townlight_comms.models import approvals, attachments, revisions +from townlight_comms.store import Conflict, InvalidInput, NotFound +from townlight_comms.workflow import CommunicationsRepository + + +class ArticleAttachmentTests(unittest.TestCase): + def setUp(self): + fd, self.path = tempfile.mkstemp(suffix=".db") + os.close(fd) + self.engine = create_engine("sqlite:///" + self.path) + migrations.upgrade(self.engine) + self.repo = CommunicationsRepository(self.engine) + self.sources = [{ + "kind": "meetings", "id": "m1", "revision": "1", + "title": "Council", "url": "/public/meetings/m1", + "sha256": "a" * 64, "eligible": True, + }] + self.access = {"reviewed": True, "findings": []} + + def tearDown(self): + self.engine.dispose() + os.unlink(self.path) + + def _sha(self, article_id, revision): + with self.repo.engine.connect() as conn: + return conn.execute(select(revisions.c.sha256).where( + revisions.c.article_id == article_id, + revisions.c.revision == revision)).scalar_one() + + def _refs(self, article_id, revision): + with self.repo.engine.connect() as conn: + return conn.execute(select(revisions.c.attachment_refs).where( + revisions.c.article_id == article_id, + revisions.c.revision == revision)).scalar_one() + + def _count_revisions(self, article_id): + with self.repo.engine.connect() as conn: + return conn.execute(select(func.count()).select_from(revisions).where( + revisions.c.article_id == article_id)).scalar_one() + + def _create(self): + return self.repo.create( + "clerk", "announcement", "Old", "Old body", "en", self.sources, + access_review=self.access)["id"] + + def test_public_attachment_revisions_and_exact_reads(self): + article_id = self._create() + first_sha = self._sha(article_id, 1) + actual = b"public minutes\n\x00\xff" + digest = hashlib.sha256(actual).hexdigest() + self.repo.add_attachment( + article_id, 1, "clerk", "minutes.bin", "application/octet-stream", + actual, public=True) + self.assertNotEqual(self._sha(article_id, 2), first_sha) + refs = self._refs(article_id, 2) + self.assertEqual(len(refs), 1) + self.assertEqual(refs[0]["sha256"], digest) + self.assertEqual(refs[0]["size"], len(actual)) + attachment_id = refs[0]["id"] + + self.repo.edit( + article_id, "clerk", 2, "New title", "New body", "en", + self.sources, access_review=self.access) + self.assertEqual(self._refs(article_id, 3), refs) + stored = self.repo.read_attachment(article_id, attachment_id) + self.assertEqual(stored["content"], actual) + self.assertEqual(stored["sha256"], digest) + self.assertEqual(stored["size"], len(actual)) + self.assertEqual(stored["name"], "minutes.bin") + self.assertEqual(stored["media_type"], "application/octet-stream") + + self.repo.remove_attachment(article_id, 3, "clerk", attachment_id) + self.assertTrue(self._sha(article_id, 4)) + with self.assertRaises(NotFound): + self.repo.read_attachment(article_id, attachment_id) + old = self.repo.read_attachment(article_id, attachment_id, revision=2) + self.assertEqual(old["content"], actual) + self.assertEqual(old["sha256"], digest) + + def test_private_attachment_blocks_approval_and_old_approval_survives(self): + article_id = self._create() + self.repo.add_attachment( + article_id, 1, "clerk", "secret.txt", "text/plain", + b"private", public=False) + with self.repo.engine.connect() as conn: + private_id = conn.execute(select(attachments.c.id).where( + attachments.c.article_id == article_id, + attachments.c.revision == 2)).scalar_one() + self.repo.review(article_id, "clerk", 2, "checked") + with self.assertRaises(Conflict): + self.repo.approve( + article_id, 2, self._sha(article_id, 2), "clerk", self.sources) + + self.repo.remove_attachment(article_id, 2, "clerk", private_id) + self.repo.review(article_id, "clerk", 3, "checked") + approved_sha = self._sha(article_id, 3) + self.repo.approve(article_id, 3, approved_sha, "clerk", self.sources) + with self.repo.engine.connect() as conn: + self.assertEqual(conn.execute(select(approvals.c.sha256).where( + approvals.c.article_id == article_id, + approvals.c.revision == 3)).scalar_one(), approved_sha) + + self.repo.add_attachment( + article_id, 3, "clerk", "public.txt", "text/plain", + b"public", public=True) + with self.repo.engine.connect() as conn: + preserved = conn.execute(select(approvals.c.sha256).where( + approvals.c.article_id == article_id, + approvals.c.revision == 3)).scalar_one() + self.assertEqual(preserved, approved_sha) + with self.assertRaises(Conflict): + self.repo.approve( + article_id, 4, self._sha(article_id, 4), "clerk", self.sources) + + def test_invalid_attachment_input_and_tamper_detection(self): + article_id = self._create() + first_sha = self._sha(article_id, 1) + with self.assertRaises(InvalidInput): + self.repo.add_attachment( + article_id, 1, "clerk", "../x.txt", "text/plain", + b"x", public=True) + with self.assertRaises(InvalidInput): + self.repo.add_attachment( + article_id, 1, "clerk", "large.bin", "application/octet-stream", + b"x" * (10 * 1024 * 1024 + 1), public=True) + self.assertEqual(self._count_revisions(article_id), 1) + self.assertEqual(self._sha(article_id, 1), first_sha) + + actual = b"tamper target" + self.repo.add_attachment( + article_id, 1, "clerk", "target.bin", "application/octet-stream", + actual, public=True) + with self.repo.engine.connect() as conn: + attachment_id = conn.execute(select(attachments.c.id).where( + attachments.c.article_id == article_id, + attachments.c.revision == 2)).scalar_one() + with self.repo.engine.begin() as conn: + conn.execute(update(attachments).where( + attachments.c.id == attachment_id).values(content=b"tampered")) + with self.assertRaises(Conflict): + self.repo.read_attachment(article_id, attachment_id) + self.repo.review(article_id, "clerk", 2, "checked") + with self.assertRaises(Conflict): + self.repo.approve( + article_id, 2, self._sha(article_id, 2), "clerk", self.sources) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_editorial_workflow.py b/tests/test_editorial_workflow.py new file mode 100644 index 0000000..9ac12bb --- /dev/null +++ b/tests/test_editorial_workflow.py @@ -0,0 +1,105 @@ +"""Real workflow tests for editorial, approval and scheduling.""" +import os +import tempfile +import unittest +from datetime import UTC, datetime, timedelta + +from sqlalchemy import create_engine, select + +from townlight_comms import migrations +from townlight_comms.models import approvals, events, publications, revisions +from townlight_comms.store import Conflict +from townlight_comms.workflow import CommunicationsRepository + + +class WorkflowTests(unittest.TestCase): + def setUp(self): + fd, self.path = tempfile.mkstemp(suffix=".db") + os.close(fd) + self.engine = create_engine("sqlite:///" + self.path) + migrations.upgrade(self.engine) + self.repo = CommunicationsRepository(self.engine) + self.sources = [{ + "kind": "meetings", "id": "m1", "revision": "1", + "title": "Council", "url": "/public/meetings/m1", + "sha256": "a" * 64, "eligible": True, + }] + self.access = {"reviewed": True, "findings": []} + + def tearDown(self): + self.engine.dispose() + os.unlink(self.path) + + def _sha(self, article_id, revision): + with self.repo.engine.connect() as conn: + return conn.execute(select(revisions.c.sha256).where( + revisions.c.article_id == article_id, + revisions.c.revision == revision)).scalar_one() + + def _create(self, title="Old", body="Old body"): + return self.repo.create( + "clerk", "announcement", title, body, "en", self.sources, + access_review=self.access)["id"] + + def test_restart_edit_keeps_old_revision_and_stale_edit_conflicts(self): + article_id = self._create() + restarted = CommunicationsRepository(self.engine) + restarted.edit(article_id, "clerk", 1, "New", "New body", "en", self.sources, + access_review=self.access) + with self.repo.engine.connect() as conn: + old = conn.execute(select(revisions.c.title, revisions.c.body).where( + revisions.c.article_id == article_id, + revisions.c.revision == 1)).one() + self.assertEqual(old.title, "Old") + self.assertEqual(old.body, "Old body") + with self.assertRaises(Conflict): + restarted.edit(article_id, "clerk", 1, "Again", "Again", "en", self.sources, + access_review=self.access) + + def test_changed_source_conflicts_before_exact_approval_succeeds(self): + article_id = self._create() + self.repo.review(article_id, "clerk", 1, "checked") + approved_sha = self._sha(article_id, 1) + changed = [dict(self.sources[0], url="/public/meetings/m2")] + with self.assertRaises(Conflict): + self.repo.approve(article_id, 1, approved_sha, "clerk", changed) + self.repo.approve(article_id, 1, approved_sha, "clerk", self.sources) + self.assertEqual(self.repo.get(article_id)["state"], "approved") + + def test_schedule_duplicate_edit_cancels_pending_and_blocks_unreviewed(self): + article_id = self._create() + self.repo.review(article_id, "clerk", 1, "checked") + approved_sha = self._sha(article_id, 1) + self.repo.approve(article_id, 1, approved_sha, "clerk", self.sources) + due = datetime.now(UTC) + timedelta(minutes=5) + self.repo.schedule(article_id, 1, approved_sha, "clerk", due, ["website"]) + self.repo.schedule(article_id, 1, approved_sha, "clerk", due, ["website"]) + with self.repo.engine.connect() as conn: + pub_count = conn.execute(select(publications.c.id).where( + publications.c.article_id == article_id, + publications.c.action == "publish")).all() + event_count = conn.execute(select(events.c.id).where( + events.c.article_id == article_id, + events.c.kind == "scheduled")).all() + self.assertEqual(len(pub_count), 1) + self.assertEqual(len(event_count), 1) + + self.repo.edit(article_id, "clerk", 1, "Draft", "Draft body", "en", + self.sources, access_review=self.access) + with self.repo.engine.connect() as conn: + pub_state = conn.execute(select(publications.c.state).where( + publications.c.article_id == article_id, + publications.c.revision == 1, + publications.c.action == "publish")).scalar_one() + old_approval = conn.execute(select(approvals.c.sha256).where( + approvals.c.article_id == article_id, + approvals.c.revision == 1)).scalar_one() + self.assertEqual(pub_state, "failed") + self.assertEqual(old_approval, approved_sha) + new_sha = self._sha(article_id, 2) + with self.assertRaises(Conflict): + self.repo.approve(article_id, 2, new_sha, "clerk", self.sources) + + +if __name__ == "__main__": + unittest.main() \ No newline at end of file diff --git a/tests/test_email_outbox.py b/tests/test_email_outbox.py new file mode 100644 index 0000000..579ef7b --- /dev/null +++ b/tests/test_email_outbox.py @@ -0,0 +1,218 @@ +"""Workflow-level tests for publication email outbox delivery. + +These tests exercise the real CommunicationsRepository against an in-memory +SQLite database migrated through townlight_comms.migrations. No SMTP or other +network calls are made. +""" + +import hashlib +import os +import tempfile +import unittest +from datetime import UTC, datetime, timedelta + +from sqlalchemy import create_engine, select + +from townlight_comms import migrations +from townlight_comms.models import email_outbox, revisions +from townlight_comms.workflow import CommunicationsRepository + + +class EmailOutboxWorkflowTests(unittest.TestCase): + def setUp(self): + fd, self.path = tempfile.mkstemp(suffix=".db") + os.close(fd) + self.engine = create_engine("sqlite:///" + self.path) + migrations.upgrade(self.engine) + self.repo = CommunicationsRepository(self.engine) + self.sources = [{ + "kind": "meetings", "id": "m1", "revision": "1", + "title": "Council", "url": "/public/meetings/m1", + "sha256": "a" * 64, "eligible": True, + }] + self.access = {"reviewed": True, "findings": []} + + def tearDown(self): + self.engine.dispose() + os.unlink(self.path) + + def _sha(self, article_id, revision): + with self.repo.engine.connect() as conn: + return conn.execute(select(revisions.c.sha256).where( + revisions.c.article_id == article_id, + revisions.c.revision == revision)).scalar_one() + + def _subscribe(self, email, topics, language="en"): + requested = self.repo.request_subscription(email, topics, language) + self.assertIn("management_token", requested) + self.assertIn("confirmation_token", requested) + self.assertEqual( + self.repo.confirm_subscription(requested["confirmation_token"]), + {"confirmed": True}) + return requested + + def _claimed_publication(self): + article_id = self.repo.create( + "clerk", "announcement", "Notice", "Body", "en", self.sources, + access_review=self.access)["id"] + self.repo.review(article_id, "clerk", 1, "checked") + sha = self._sha(article_id, 1) + self.repo.approve(article_id, 1, sha, "clerk", self.sources) + due = datetime.now(UTC) - timedelta(seconds=1) + self.repo.schedule( + article_id, 1, sha, "clerk", due, ["email", "website"]) + job = self.repo.claim_due() + self.assertIsNotNone(job) + self.assertIn("id", job) + self.assertIn("claim_token", job) + return job + + @staticmethod + def _public_url(): + return "https://townlight.example/public/notice" + + def test_enqueue_eligibility_is_idempotent_and_claim_delivers(self): + eligible = self._subscribe("eligible@example.com", ["all"], "en") + self._subscribe("parks@example.com", ["parks"], "en") + self._subscribe("french@example.com", ["all"], "fr") + + job = self._claimed_publication() + url = self._public_url() + + counts = self.repo.enqueue_publication_email( + job["id"], job["claim_token"], url) + self.assertEqual(counts, { + "pending": 1, "sent": 0, "failed": 0, + "uncertain": 0, "skipped": 0, + }) + + duplicate = self.repo.enqueue_publication_email( + job["id"], job["claim_token"], url) + self.assertEqual(duplicate, { + "pending": 1, "sent": 0, "failed": 0, + "uncertain": 0, "skipped": 0, + }) + + claimed = self.repo.claim_email(now=datetime.now(UTC)) + self.assertIsNotNone(claimed) + expected_message_id = "<{}@townlight.local>".format( + hashlib.sha256( + "{}:{}".format(job["id"], eligible["id"]).encode("utf-8") + ).hexdigest() + ) + self.assertEqual(claimed["message_id"], expected_message_id) + self.assertEqual(claimed["subject"], "Notice") + self.assertEqual(claimed["recipient"], "eligible@example.com") + + with self.repo.engine.connect() as conn: + row = conn.execute(select( + email_outbox.c.subject, + email_outbox.c.body, + email_outbox.c.message_id, + ).where(email_outbox.c.id == claimed["id"])).mappings().one() + self.assertEqual(row["subject"], "Notice") + self.assertEqual(row["message_id"], expected_message_id) + self.assertTrue(row["body"].endswith(url)) + + self.assertTrue(self.repo.finish_email( + claimed["id"], claimed["claim_token"], "sent")) + summary = self.repo.email_summary(job["id"]) + self.assertEqual(summary["sent"], 1) + self.assertEqual(summary["remaining"], 0) + + def test_unsubscribe_after_enqueue_skips_delivery(self): + subscriber = self._subscribe("unsubscribe@example.com", ["all"], "en") + job = self._claimed_publication() + counts = self.repo.enqueue_publication_email( + job["id"], job["claim_token"], self._public_url()) + self.assertEqual(counts["pending"], 1) + + preferences = self.repo.preferences( + subscriber["management_token"], active=False) + self.assertFalse(preferences["active"]) + + self.assertIsNone(self.repo.claim_email( + now=datetime.now(UTC))) + summary = self.repo.email_summary(job["id"]) + self.assertEqual(summary["remaining"], 0) + self.assertEqual(summary["sent"], 0) + self.assertEqual(summary["skipped"], 1) + self.assertEqual(summary["failed"], 0) + + with self.repo.engine.connect() as conn: + row = conn.execute(select( + email_outbox.c.state, + email_outbox.c.attempts, + email_outbox.c.claim_token, + ).where(email_outbox.c.publication_id == job["id"])).mappings().one() + self.assertEqual(row["state"], "failed") + self.assertEqual(row["attempts"], 0) + self.assertIsNone(row["claim_token"]) + + def test_expired_claim_is_uncertain_and_retry_keeps_pending(self): + expire_subscriber = self._subscribe("expire@example.com", ["all"], "en") + job = self._claimed_publication() + self.repo.enqueue_publication_email( + job["id"], job["claim_token"], self._public_url()) + + first_now = datetime.now(UTC) + claimed = self.repo.claim_email(now=first_now, lease_seconds=30) + self.assertIsNotNone(claimed) + + expired_now = first_now + timedelta(seconds=31) + self.assertIsNone(self.repo.claim_email(now=expired_now)) + self.assertIsNone(self.repo.claim_email(now=expired_now)) + + with self.repo.engine.connect() as conn: + expired = conn.execute(select( + email_outbox.c.state, + email_outbox.c.attempts, + email_outbox.c.claim_token, + ).where(email_outbox.c.id == claimed["id"])).mappings().one() + self.assertEqual(expired["state"], "uncertain") + self.assertEqual(expired["attempts"], 1) + self.assertIsNone(expired["claim_token"]) + + # Deactivate the expired subscriber so only the retry recipient is + # eligible for the separate retry publication. + preferences = self.repo.preferences( + expire_subscriber["management_token"], active=False) + self.assertFalse(preferences["active"]) + + # A separate publication/subscriber fixture exercises safe retry. + self._subscribe("retry@example.com", ["all"], "en") + retry_job = self._claimed_publication() + retry_counts = self.repo.enqueue_publication_email( + retry_job["id"], retry_job["claim_token"], self._public_url()) + self.assertEqual(retry_counts["pending"], 1) + + retry_now = datetime.now(UTC) + retry_claim = self.repo.claim_email(now=retry_now) + self.assertIsNotNone(retry_claim) + self.assertFalse(self.repo.finish_email( + retry_claim["id"], "wrong-token", "retry")) + self.assertTrue(self.repo.finish_email( + retry_claim["id"], retry_claim["claim_token"], "retry")) + + with self.repo.engine.connect() as conn: + retried = conn.execute(select( + email_outbox.c.state, + email_outbox.c.attempts, + email_outbox.c.next_attempt_at, + email_outbox.c.claim_token, + ).where(email_outbox.c.id == retry_claim["id"])).mappings().one() + self.assertEqual(retried["state"], "pending") + self.assertEqual(retried["attempts"], 1) + self.assertIsNotNone(retried["next_attempt_at"]) + self.assertIsNone(retried["claim_token"]) + + # next_attempt_at is in the future, so the pending row is not + # re-claimed immediately. + self.assertIsNone(self.repo.claim_email(now=retry_now)) + summary = self.repo.email_summary(retry_job["id"]) + self.assertEqual(summary["remaining"], 1) + self.assertEqual(summary["sent"], 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_postgres_editorial.py b/tests/test_postgres_editorial.py new file mode 100644 index 0000000..4c529df --- /dev/null +++ b/tests/test_postgres_editorial.py @@ -0,0 +1,88 @@ +"""Real PostgreSQL integration test for the editorial delivery workflow.""" + +import os +import unittest +from datetime import UTC, datetime +from uuid import uuid4 + +from sqlalchemy import create_engine, select +from sqlalchemy.engine import make_url + +from townlight_comms import migrations +from townlight_comms.models import publications, revisions +from townlight_comms.workflow import CommunicationsRepository + + +class PostgresEditorialIntegrationTests(unittest.TestCase): + def test_editorial_claim_finish_and_reopen(self): + raw_url = os.environ.get("TOWNLIGHT_COMMS_TEST_DATABASE_URL") + if not raw_url: + self.skipTest("TOWNLIGHT_COMMS_TEST_DATABASE_URL is not set") + url = make_url(raw_url) + if url.get_backend_name() != "postgresql": + self.fail("test database URL must use PostgreSQL") + if url.host not in {"127.0.0.1", "localhost"}: + self.fail("test database host must be 127.0.0.1 or localhost") + if url.port != 25483: + self.fail("test database port must be 25483") + if not (url.database or "").startswith("townlight_comms_test"): + self.fail("test database name must start with townlight_comms_test") + + engine = create_engine(raw_url) + try: + migrations.upgrade(engine) + migrations.upgrade(engine) + self.assertTrue(migrations.ready(engine)) + + repo = CommunicationsRepository(engine) + unique = uuid4().hex + sources = [{ + "kind": "meetings", "id": "meeting-" + unique, "revision": "1", + "title": "Integration meeting", "url": "/public/meetings/" + unique, + "sha256": "b" * 64, "eligible": True, + }] + access = {"reviewed": True, "findings": []} + article_id = repo.create( + "clerk", "announcement", "Postgres notice " + unique, + "Body", "en", sources, access_review=access)["id"] + repo.review(article_id, "clerk", 1, "checked") + with engine.connect() as conn: + sha = conn.execute(select(revisions.c.sha256).where( + revisions.c.article_id == article_id, + revisions.c.revision == 1)).scalar_one() + repo.approve(article_id, 1, sha, "clerk", sources) + repo.schedule( + article_id, 1, sha, "clerk", datetime.now(UTC), + ["website"]) + + job = repo.claim_due() + self.assertIsNotNone(job) + self.assertEqual(job["article_id"], article_id) + receipt = {"status": "queued", "job": job["id"]} + repo.finish_publication( + job["id"], job["claim_token"], state="queued", + website_receipt=receipt) + + engine.dispose() + engine = create_engine(raw_url) + reopened = CommunicationsRepository(engine) + record = reopened.get(article_id) + self.assertEqual(record["id"], article_id) + with engine.connect() as conn: + current_revision = conn.execute( + select(revisions.c.revision).where( + revisions.c.article_id == article_id + ).order_by(revisions.c.revision.desc()) + ).scalars().first() + history_state = conn.execute( + select(publications.c.state).where( + publications.c.id == job["id"]) + ).scalar_one() + self.assertEqual(current_revision, 1) + self.assertEqual(history_state, "queued") + finally: + engine.dispose() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_production_depth_draft_persistence.py b/tests/test_production_depth_draft_persistence.py index d236af3..02bca0b 100644 --- a/tests/test_production_depth_draft_persistence.py +++ b/tests/test_production_depth_draft_persistence.py @@ -4,15 +4,14 @@ from fastapi.testclient import TestClient -from civiccomms.main import app, _dispose_draft_repository -from civiccomms.persistence import CommunicationsDraftRepository - +from townlight_comms.main import _dispose_draft_repository, app +from townlight_comms.persistence import CommunicationsDraftRepository client = TestClient(app) def test_repository_persists_source_review_and_meeting_summary(tmp_path: Path) -> None: - db_path = tmp_path / "civiccomms.db" + db_path = tmp_path / "townlight_comms.db" db_url = f"sqlite+pysqlite:///{db_path.as_posix()}" repository = CommunicationsDraftRepository(db_url=db_url) @@ -42,25 +41,25 @@ def test_repository_persists_source_review_and_meeting_summary(tmp_path: Path) - def test_draft_persistence_api_round_trip(monkeypatch, tmp_path: Path) -> None: - db_path = tmp_path / "civiccomms-api.db" - monkeypatch.setenv("CIVICCOMMS_DRAFT_DB_URL", f"sqlite+pysqlite:///{db_path.as_posix()}") + db_path = tmp_path / "townlight_comms-api.db" + monkeypatch.setenv("TOWNLIGHT_COMMS_DRAFT_DB_URL", f"sqlite+pysqlite:///{db_path.as_posix()}") _dispose_draft_repository() created_review = client.post( - "/api/v1/civiccomms/source-review", + "/api/v1/townlight_comms/source-review", json={"source_titles": ["Council packet"], "citations": ["packet p. 2"]}, ) review_id = created_review.json()["review_id"] - fetched_review = client.get(f"/api/v1/civiccomms/source-review/{review_id}") + fetched_review = client.get(f"/api/v1/townlight_comms/source-review/{review_id}") created_summary = client.post( - "/api/v1/civiccomms/meeting-summary", + "/api/v1/townlight_comms/meeting-summary", json={"meeting_title": "Council", "actions": ["approved item 4"], "citations": ["minutes p. 3"]}, ) summary_id = created_summary.json()["summary_id"] - fetched_summary = client.get(f"/api/v1/civiccomms/meeting-summary/{summary_id}") + fetched_summary = client.get(f"/api/v1/townlight_comms/meeting-summary/{summary_id}") _dispose_draft_repository() - monkeypatch.delenv("CIVICCOMMS_DRAFT_DB_URL") + monkeypatch.delenv("TOWNLIGHT_COMMS_DRAFT_DB_URL") assert created_review.status_code == 200 assert review_id @@ -74,29 +73,29 @@ def test_draft_persistence_api_round_trip(monkeypatch, tmp_path: Path) -> None: def test_get_source_review_without_persistence_returns_actionable_503(monkeypatch) -> None: - monkeypatch.delenv("CIVICCOMMS_DRAFT_DB_URL", raising=False) + monkeypatch.delenv("TOWNLIGHT_COMMS_DRAFT_DB_URL", raising=False) _dispose_draft_repository() - response = client.get("/api/v1/civiccomms/source-review/example") + response = client.get("/api/v1/townlight_comms/source-review/example") assert response.status_code == 503 detail = response.json()["detail"] assert detail["message"] == "Townlight Communications draft persistence is not configured." - assert "Set CIVICCOMMS_DRAFT_DB_URL" in detail["fix"] + assert "Set TOWNLIGHT_COMMS_DRAFT_DB_URL" in detail["fix"] def test_get_meeting_summary_missing_id_returns_actionable_404(monkeypatch, tmp_path: Path) -> None: - db_path = tmp_path / "civiccomms-missing.db" - monkeypatch.setenv("CIVICCOMMS_DRAFT_DB_URL", f"sqlite+pysqlite:///{db_path.as_posix()}") + db_path = tmp_path / "townlight_comms-missing.db" + monkeypatch.setenv("TOWNLIGHT_COMMS_DRAFT_DB_URL", f"sqlite+pysqlite:///{db_path.as_posix()}") _dispose_draft_repository() - response = client.get("/api/v1/civiccomms/meeting-summary/missing") + response = client.get("/api/v1/townlight_comms/meeting-summary/missing") _dispose_draft_repository() - monkeypatch.delenv("CIVICCOMMS_DRAFT_DB_URL") + monkeypatch.delenv("TOWNLIGHT_COMMS_DRAFT_DB_URL") assert response.status_code == 404 detail = response.json()["detail"] assert detail["message"] == "Meeting summary record not found." - assert "POST /api/v1/civiccomms/meeting-summary" in detail["fix"] + assert "POST /api/v1/townlight_comms/meeting-summary" in detail["fix"] db_path.unlink() diff --git a/tests/test_publication_delivery_state.py b/tests/test_publication_delivery_state.py new file mode 100644 index 0000000..db8d0af --- /dev/null +++ b/tests/test_publication_delivery_state.py @@ -0,0 +1,105 @@ +"""Real tests for publication claim delivery and subscription state.""" + +import hashlib +import os +import tempfile +import unittest +from datetime import UTC, datetime, timedelta + +from sqlalchemy import create_engine, select + +from townlight_comms import migrations +from townlight_comms.models import publications, revisions, subscribers +from townlight_comms.store import Conflict, InvalidInput, Unauthorized +from townlight_comms.workflow import CommunicationsRepository + + +class PublicationDeliveryStateTests(unittest.TestCase): + def setUp(self): + fd, self.path = tempfile.mkstemp(suffix=".db") + os.close(fd) + self.engine = create_engine("sqlite:///" + self.path) + migrations.upgrade(self.engine) + self.repo = CommunicationsRepository(self.engine) + self.sources = [{ + "kind": "meetings", "id": "m1", "revision": "1", + "title": "Council", "url": "/public/meetings/m1", + "sha256": "a" * 64, "eligible": True, + }] + self.access = {"reviewed": True, "findings": []} + + def tearDown(self): + self.engine.dispose() + os.unlink(self.path) + + def _sha(self, article_id, revision): + with self.repo.engine.connect() as conn: + return conn.execute(select(revisions.c.sha256).where( + revisions.c.article_id == article_id, + revisions.c.revision == revision)).scalar_one() + + def _approved_due(self): + article_id = self.repo.create( + "clerk", "announcement", "Notice", "Body", "en", self.sources, + access_review=self.access)["id"] + self.repo.review(article_id, "clerk", 1, "checked") + sha = self._sha(article_id, 1) + self.repo.approve(article_id, 1, sha, "clerk", self.sources) + due = datetime.now(UTC) - timedelta(seconds=1) + self.repo.schedule(article_id, 1, sha, "clerk", due, ["website"]) + return article_id + + def test_claim_and_finish_guard_delivery_state(self): + article_id = self._approved_due() + job = self.repo.claim_due() + self.assertIsNotNone(job) + self.assertIsNone(CommunicationsRepository(self.engine).claim_due()) + with self.assertRaises(Conflict): + self.repo.finish_publication(job["id"], "wrong-token", state="published") + with self.assertRaises(InvalidInput): + self.repo.finish_publication(job["id"], job["claim_token"], state="published") + self.repo.finish_publication(job["id"], job["claim_token"], state="queued") + self.assertEqual(self.repo.get(article_id)["state"], "scheduled") + + def test_expired_claim_becomes_uncertain_without_resend(self): + self._approved_due() + job = self.repo.claim_due() + expired_now = job["lease_until"] + timedelta(seconds=1) + self.assertIsNone(self.repo.claim_due(now=expired_now)) + with self.repo.engine.connect() as conn: + state = conn.execute(select(publications.c.state).where( + publications.c.id == job["id"])).scalar_one() + self.assertEqual(state, "uncertain") + self.assertIsNone(self.repo.claim_due(now=expired_now)) + + def test_subscription_confirmation_preferences_and_hashed_tokens(self): + requested = self.repo.request_subscription("user@example.com", ["meetings", "code"]) + management = requested["management_token"] + confirmation = requested["confirmation_token"] + with self.assertRaises(Unauthorized): + self.repo.preferences(management) + + duplicate = self.repo.request_subscription("USER@Example.com", ["parks"]) + self.assertEqual(duplicate, {"accepted": True}) + + with self.repo.engine.connect() as conn: + row = conn.execute(select(subscribers).where( + subscribers.c.id == requested["id"])).mappings().one() + self.assertEqual(row["token_hash"], + hashlib.sha256(management.encode("utf-8")).hexdigest()) + self.assertEqual(row["confirmation_hash"], + hashlib.sha256(confirmation.encode("utf-8")).hexdigest()) + self.assertNotIn(management, row.values()) + self.assertNotIn(confirmation, row.values()) + + self.assertEqual(self.repo.confirm_subscription(confirmation), {"confirmed": True}) + response = self.repo.preferences(management, active=False) + self.assertEqual(set(response), {"id", "topics", "language", "active"}) + self.assertEqual(response["id"], requested["id"]) + self.assertEqual(response["topics"], ["meetings", "code"]) + self.assertEqual(response["language"], "en") + self.assertFalse(response["active"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_records_guard.py b/tests/test_records_guard.py new file mode 100644 index 0000000..c1c3138 --- /dev/null +++ b/tests/test_records_guard.py @@ -0,0 +1,141 @@ +"""Real SQLite tests for the Records guard around published revisions.""" + +import os +import tempfile +import unittest +from datetime import UTC, datetime, timedelta +from uuid import uuid4 + +from sqlalchemy import create_engine, select, update + +from townlight_comms import migrations +from townlight_comms.models import articles, publications, records_receipts, revisions +from townlight_comms.store import Conflict +from townlight_comms.workflow import CommunicationsRepository + + +class RecordsGuardTests(unittest.TestCase): + def setUp(self): + fd, self.path = tempfile.mkstemp(suffix=".db") + os.close(fd) + self.base_engine = create_engine("sqlite:///" + self.path) + migrations.upgrade(self.base_engine) + self.repo = CommunicationsRepository(self.base_engine) + self.engine = self.repo.engine + self.sources = [{ + "kind": "meetings", "id": "m1", "revision": "1", + "title": "Council", "url": "/public/meetings/m1", + "sha256": "a" * 64, "eligible": True, + }] + self.access = {"reviewed": True, "findings": []} + + def tearDown(self): + self.base_engine.dispose() + os.unlink(self.path) + + def _sha(self, article_id, revision): + with self.engine.connect() as conn: + return conn.execute(select(revisions.c.sha256).where( + revisions.c.article_id == article_id, + revisions.c.revision == revision)).scalar_one() + + def _approved_due(self): + article_id = self.repo.create( + "clerk", "announcement", "Notice", "Body", "en", self.sources, + access_review=self.access)["id"] + self.repo.review(article_id, "clerk", 1, "checked") + sha = self._sha(article_id, 1) + self.repo.approve(article_id, 1, sha, "clerk", self.sources) + due = datetime.now(UTC) - timedelta(seconds=1) + self.repo.schedule(article_id, 1, sha, "clerk", due, ["website"]) + return article_id + + def _publish_ack(self, article_id, revision): + # Delivery acknowledgement fixture: direct DB state only, no network. + now = datetime.now(UTC) + with self.engine.begin() as conn: + result = conn.execute(update(publications).where( + publications.c.article_id == article_id, + publications.c.revision == revision, + publications.c.action == "publish", + ).values(state="published", website_receipt={"acknowledged": True}, + updated_at=now)) + self.assertEqual(result.rowcount, 1) + result = conn.execute(update(articles).where( + articles.c.id == article_id, + ).values(state="published", updated_at=now)) + self.assertEqual(result.rowcount, 1) + + def test_receipt_unblocks_edit_and_withdraw_schedule(self): + article_id = self._approved_due() + self._publish_ack(article_id, 1) + sha1 = self._sha(article_id, 1) + due = datetime.now(UTC) + timedelta(minutes=5) + + with self.assertRaises(Conflict): + self.repo.edit(article_id, "clerk", 1, "Notice", "Edited", "en", + self.sources, access_review=self.access) + with self.assertRaises(Conflict): + self.repo.add_attachment(article_id, 1, "clerk", "file.txt", + "text/plain", b"data") + with self.assertRaises(Conflict): + self.repo.schedule(article_id, 1, sha1, "clerk", due, + ["website"], action="withdraw") + + archive_sha = "b" * 64 + records_id = "records-" + str(uuid4()) + file_id = str(uuid4()) + first = self.repo.record_records_receipt( + article_id, 1, archive_sha, records_id, file_id) + self.assertEqual(first["file_id"], file_id) + second = self.repo.record_records_receipt( + article_id, 1, archive_sha, records_id, file_id) + self.assertEqual(second["archive_sha256"], archive_sha) + self.assertEqual(second["records_id"], records_id) + self.assertEqual(second["file_id"], file_id) + with self.engine.connect() as conn: + rows = conn.execute(select(records_receipts.c.article_id).where( + records_receipts.c.article_id == article_id, + records_receipts.c.revision == 1)).all() + self.assertEqual(len(rows), 1) + + edited = self.repo.edit( + article_id, "clerk", 1, "Notice", "Edited Body", "en", + self.sources, access_review=self.access) + self.assertEqual(edited["current_revision"], 2) + self.assertEqual(edited["state"], "draft") + with self.engine.connect() as conn: + original_body = conn.execute(select(revisions.c.body).where( + revisions.c.article_id == article_id, + revisions.c.revision == 1)).scalar_one() + self.assertEqual(original_body, "Body") + + with self.assertRaises(Conflict): + self.repo.record_records_receipt( + article_id, 2, "c" * 64, "records-2", str(uuid4())) + + sha2 = self._sha(article_id, 2) + self.repo.review(article_id, "clerk", 2, "withdraw review") + self.repo.approve(article_id, 2, sha2, "clerk", self.sources) + scheduled = self.repo.schedule( + article_id, 2, sha2, "clerk", due, ["website"], action="withdraw") + self.assertEqual(scheduled["state"], "scheduled") + + def test_correction_rejects_queued_only_prior(self): + article_id = self._approved_due() + now = datetime.now(UTC) + with self.engine.begin() as conn: + result = conn.execute(update(publications).where( + publications.c.article_id == article_id, + publications.c.revision == 1, + publications.c.action == "publish", + ).values(state="queued", updated_at=now)) + self.assertEqual(result.rowcount, 1) + with self.assertRaises(Conflict): + self.repo.schedule( + article_id, 1, self._sha(article_id, 1), "clerk", + now + timedelta(minutes=5), ["website"], action="correct") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_runtime_foundation.py b/tests/test_runtime_foundation.py index e5ee670..cde0207 100644 --- a/tests/test_runtime_foundation.py +++ b/tests/test_runtime_foundation.py @@ -1,31 +1,33 @@ from fastapi.testclient import TestClient -import civiccomms -from civiccomms.main import app - +import townlight_comms +from townlight_comms.main import app client = TestClient(app) def test_package_version_is_010() -> None: - assert civiccomms.__version__ == "0.1.1" + assert townlight_comms.__version__ == "0.2.0" def test_root_endpoint_states_runtime_boundary() -> None: payload = client.get("/").json() - assert payload["name"] == "CivicComms" - assert payload["version"] == "0.1.1" - assert payload["status"] == "public communications foundation plus draft persistence" - assert "database-backed source review and meeting summary draft records" in payload["message"] - assert "autonomous publication" in payload["message"] - assert "Post-v0.1.1 roadmap" in payload["next_step"] + assert payload["name"] == "Townlight Communications" + assert payload["version"] == "0.2.0" + assert payload["status"] == "standalone draft-helper prototype" + assert "legacy draft-helper prototype" in payload["message"] + assert "not a secured production" in payload["message"] + assert "/desktop/v1/communications" in payload["message"] + assert "installed Windows candidate acceptance remains pending" in payload["message"] + assert "authenticated Windows Suite" in payload["next_step"] + assert "/desktop/v1/communications" in payload["next_step"] def test_health_endpoint_reports_versions() -> None: payload = client.get("/health").json() assert payload["status"] == "ok" - assert payload["service"] == "civiccomms" - assert payload["version"] == "0.1.1" - assert payload["civiccore_version"] == "0.3.0" + assert payload["service"] == "townlight_comms" + assert payload["version"] == "0.2.0" + assert payload["townlight_core_version"] == "1.3.0.dev2" diff --git a/tests/test_subscription_commands.py b/tests/test_subscription_commands.py new file mode 100644 index 0000000..9d6b412 --- /dev/null +++ b/tests/test_subscription_commands.py @@ -0,0 +1,363 @@ +"""SQLite workflow tests for encrypted subscription commands and mail delivery. + +These tests exercise the real migrations and CommunicationsRepository against a +temporary SQLite database. They do not use SMTP or any network calls. +""" + +import json +import os +import re +import tempfile +import unittest +import uuid +from datetime import UTC, datetime, timedelta +from urllib.parse import parse_qs, urlsplit + +from cryptography.fernet import Fernet +from sqlalchemy import create_engine, func, select + +from townlight_comms import migrations +from townlight_comms.models import subscribers +from townlight_comms.store import Conflict, InvalidInput, Unauthorized +from townlight_comms.subscription_models import ( + subscription_commands, + subscription_mail, +) +from townlight_comms.workflow import CommunicationsRepository + + +class SubscriptionCommandRepositoryTests(unittest.TestCase): + public_origin = "https://townlight.example" + + def setUp(self): + fd, self.path = tempfile.mkstemp(suffix=".db") + os.close(fd) + self.engine = create_engine("sqlite:///" + self.path) + migrations.upgrade(self.engine) + self.repo = CommunicationsRepository(self.engine) + self.engine = self.repo.engine + self.key = Fernet.generate_key() + + def tearDown(self): + self.engine.dispose() + os.unlink(self.path) + + def _execute(self, command_id, operation, payload): + return self.repo.execute_subscription_command( + command_id, + operation, + payload, + key=self.key, + public_origin=self.public_origin, + ) + + def _count(self, table): + with self.engine.connect() as conn: + return conn.execute( + select(func.count()).select_from(table) + ).scalar_one() + + def _command_exists(self, command_id): + with self.engine.connect() as conn: + return conn.execute( + select(subscription_commands.c.command_id).where( + subscription_commands.c.command_id == command_id + ) + ).first() is not None + + def _subscriber(self, email): + with self.engine.connect() as conn: + return conn.execute( + select(subscribers).where(subscribers.c.email == email) + ).mappings().one() + + def _mail_for(self, recipient): + with self.engine.connect() as conn: + return dict(conn.execute( + select(subscription_mail).where( + subscription_mail.c.recipient == recipient + ) + ).mappings().one()) + + def _mail_by_id(self, mail_id): + with self.engine.connect() as conn: + return dict(conn.execute( + select(subscription_mail).where( + subscription_mail.c.id == mail_id + ) + ).mappings().one()) + + def _mail_payload_and_tokens(self, recipient): + row = self._mail_for(recipient) + payload = json.loads( + Fernet(self.key) + .decrypt(row["encrypted_body"].encode("utf-8")) + .decode("utf-8") + ) + tokens = {} + for url in re.findall(r"https?://\S+", payload["body"]): + parts = urlsplit(url) + query = parse_qs(parts.query) + if parts.path.endswith("/confirm/"): + tokens["confirm"] = query["token"][0] + elif parts.path.endswith("/preferences/"): + tokens["preferences"] = query["token"][0] + self.assertEqual(set(tokens), {"confirm", "preferences"}) + return row, payload, tokens + + def _subscribe(self, email): + return self._execute( + str(uuid.uuid4()), + "comms_subscribe", + {"email": email, "topics": ["all"], "language": "en"}, + ) + + def test_subscribe_is_generic_idempotent_and_tokens_stay_encrypted(self): + email = "person@example.com" + command_id = str(uuid.uuid4()) + payload = {"email": email, "topics": ["all"], "language": "en"} + + result = self._execute(command_id, "comms_subscribe", payload) + self.assertEqual(result, {"accepted": True}) + + subscriber = self._subscriber(email) + self.assertFalse(subscriber["active"]) + self.assertFalse(subscriber["confirmed"]) + self.assertIsNotNone(subscriber["confirmation_hash"]) + self.assertIsNotNone(subscriber["token_hash"]) + + mail, message, tokens = self._mail_payload_and_tokens(email) + self.assertEqual(mail["state"], "pending") + self.assertEqual(mail["recipient"], email) + self.assertEqual(mail["attempts"], 0) + self.assertIsNone(mail["claim_token"]) + self.assertIsNone(mail["lease_until"]) + self.assertIsNotNone(mail["next_attempt_at"]) + self.assertTrue(mail["message_id"].endswith("@townlight.local")) + self.assertNotIn(email, mail["encrypted_body"]) + self.assertNotIn(tokens["confirm"], mail["encrypted_body"]) + self.assertNotIn(tokens["preferences"], mail["encrypted_body"]) + self.assertEqual(message["subject"], "Confirm your subscription") + self.assertIn("/communications/confirm/?token=", message["body"]) + self.assertIn("/communications/preferences/?token=", message["body"]) + + self.assertEqual(self._count(subscription_commands), 1) + self.assertEqual(self._count(subscription_mail), 1) + + replay = self._execute(command_id, "comms_subscribe", payload) + self.assertEqual(replay, {"accepted": True}) + self.assertEqual(self._count(subscription_commands), 1) + self.assertEqual(self._count(subscription_mail), 1) + + with self.assertRaises(Conflict): + self._execute( + command_id, + "comms_subscribe", + {"email": email, "topics": ["parks"], "language": "en"}, + ) + self.assertEqual(self._count(subscription_commands), 1) + self.assertEqual(self._count(subscription_mail), 1) + + confirmed = self._execute( + str(uuid.uuid4()), + "comms_confirm", + {"token": tokens["confirm"]}, + ) + self.assertEqual(confirmed, {"confirmed": True}) + subscriber = self._subscriber(email) + self.assertTrue(subscriber["active"]) + self.assertTrue(subscriber["confirmed"]) + self.assertIsNone(subscriber["confirmation_hash"]) + + preferences = self._execute( + str(uuid.uuid4()), + "comms_preferences", + {"token": tokens["preferences"], "active": False}, + ) + self.assertEqual(set(preferences), {"topics", "language", "active"}) + self.assertFalse(preferences["active"]) + dumped = json.dumps(preferences, sort_keys=True) + self.assertNotIn(tokens["confirm"], dumped) + self.assertNotIn(tokens["preferences"], dumped) + self.assertNotIn("token", dumped) + self.assertFalse(self._subscriber(email)["active"]) + + def test_invalid_commands_leave_no_receipt_and_do_not_reset_confirmation(self): + email = "person@example.com" + self._subscribe(email) + _, _, tokens = self._mail_payload_and_tokens(email) + original = self._subscriber(email) + + command_count = self._count(subscription_commands) + subscriber_count = self._count(subscribers) + mail_count = self._count(subscription_mail) + + cases = [ + ( + str(uuid.uuid4()), + "comms_confirm", + {"token": "x" * 32}, + Unauthorized, + ), + ( + str(uuid.uuid4()), + "comms_subscribe", + { + "email": "second@example.com", + "topics": ["all"], + "extra": True, + }, + InvalidInput, + ), + ( + str(uuid.uuid4()), + "comms_preferences", + {"token": tokens["preferences"], "active": 1}, + Unauthorized, + ), + ( + str(uuid.uuid4()), + "comms_subscribe", + {"email": "not-an-email", "topics": ["all"]}, + InvalidInput, + ), + ] + for command_id, operation, payload, exception in cases: + with self.subTest(operation=operation, payload=payload): + with self.assertRaises(exception): + self._execute(command_id, operation, payload) + self.assertFalse(self._command_exists(command_id)) + self.assertEqual(self._count(subscription_commands), command_count) + self.assertEqual(self._count(subscribers), subscriber_count) + self.assertEqual(self._count(subscription_mail), mail_count) + + same_email_command = str(uuid.uuid4()) + repeated = self._execute( + same_email_command, + "comms_subscribe", + {"email": email, "topics": ["parks"], "language": "fr"}, + ) + self.assertEqual(repeated, {"accepted": True}) + self.assertEqual(self._count(subscription_commands), command_count + 1) + self.assertEqual(self._count(subscribers), subscriber_count) + self.assertEqual(self._count(subscription_mail), mail_count) + + after = self._subscriber(email) + self.assertEqual( + after["confirmation_hash"], original["confirmation_hash"]) + self.assertEqual(after["token_hash"], original["token_hash"]) + self.assertFalse(after["active"]) + self.assertFalse(after["confirmed"]) + + self.assertEqual( + self._execute( + str(uuid.uuid4()), + "comms_confirm", + {"token": tokens["confirm"]}, + ), + {"confirmed": True}, + ) + + invalid_preferences_command = str(uuid.uuid4()) + with self.assertRaises(InvalidInput): + self._execute( + invalid_preferences_command, + "comms_preferences", + {"token": tokens["preferences"], "active": 1}, + ) + self.assertFalse(self._command_exists(invalid_preferences_command)) + + def test_claim_sent_expiry_and_bounded_explicit_retry(self): + first_email = "first@example.com" + self._subscribe(first_email) + first_mail = self._mail_for(first_email) + + first_now = datetime.now(UTC) + claimed = self.repo.claim_subscription_email( + key=self.key, now=first_now, lease_seconds=30) + self.assertIsNotNone(claimed) + self.assertEqual(claimed["id"], first_mail["id"]) + self.assertEqual(claimed["recipient"], first_email) + self.assertEqual(claimed["subject"], "Confirm your subscription") + self.assertIn("/communications/confirm/?token=", claimed["body"]) + + self.assertFalse(self.repo.finish_subscription_email( + claimed["id"], "wrong-token", "sent", now=first_now)) + still_claimed = self._mail_by_id(claimed["id"]) + self.assertEqual(still_claimed["state"], "claimed") + self.assertEqual(still_claimed["claim_token"], claimed["claim_token"]) + + self.assertTrue(self.repo.finish_subscription_email( + claimed["id"], claimed["claim_token"], "sent", now=first_now)) + sent = self._mail_by_id(claimed["id"]) + self.assertEqual(sent["state"], "sent") + self.assertEqual(sent["attempts"], 1) + self.assertIsNone(sent["claim_token"]) + self.assertIsNone(sent["lease_until"]) + self.assertIsNone(sent["last_error"]) + self.assertIsNone(self.repo.claim_subscription_email( + key=self.key, now=first_now + timedelta(seconds=1))) + + second_email = "second@example.com" + self._subscribe(second_email) + second_mail = self._mail_for(second_email) + second_now = datetime.now(UTC) + second = self.repo.claim_subscription_email( + key=self.key, now=second_now, lease_seconds=30) + self.assertIsNotNone(second) + self.assertEqual(second["id"], second_mail["id"]) + + expired_now = second_now + timedelta(seconds=31) + self.assertIsNone(self.repo.claim_subscription_email( + key=self.key, now=expired_now)) + expired = self._mail_by_id(second["id"]) + self.assertEqual(expired["state"], "uncertain") + self.assertEqual(expired["last_error"], "lease expired") + self.assertEqual(expired["attempts"], 1) + self.assertIsNone(expired["claim_token"]) + self.assertIsNone(expired["lease_until"]) + self.assertFalse(self.repo.finish_subscription_email( + second["id"], second["claim_token"], "retry", now=expired_now)) + + retry_email = "retry@example.com" + self._subscribe(retry_email) + retry_mail = self._mail_for(retry_email) + due = datetime.now(UTC) + claimed = self.repo.claim_subscription_email( + key=self.key, now=due, lease_seconds=30) + self.assertIsNotNone(claimed) + self.assertEqual(claimed["id"], retry_mail["id"]) + + for attempt in range(1, 6): + row = self._mail_by_id(claimed["id"]) + self.assertEqual(row["state"], "claimed") + self.assertEqual(row["attempts"], attempt) + self.assertTrue(self.repo.finish_subscription_email( + claimed["id"], claimed["claim_token"], "retry", now=due)) + row = self._mail_by_id(claimed["id"]) + if attempt < 5: + self.assertEqual(row["state"], "pending") + self.assertEqual(row["last_error"], "delivery retry scheduled") + self.assertEqual(row["attempts"], attempt) + self.assertIsNotNone(row["next_attempt_at"]) + self.assertIsNone(row["claim_token"]) + self.assertIsNone(row["lease_until"]) + self.assertIsNone(self.repo.claim_subscription_email( + key=self.key, now=due)) + due = row["next_attempt_at"] + claimed = self.repo.claim_subscription_email( + key=self.key, now=due, lease_seconds=30) + self.assertIsNotNone(claimed) + self.assertEqual(claimed["id"], retry_mail["id"]) + else: + self.assertEqual(row["state"], "failed") + self.assertEqual(row["last_error"], "delivery failed") + self.assertEqual(row["attempts"], 5) + self.assertIsNone(row["claim_token"]) + self.assertIsNone(row["lease_until"]) + self.assertIsNone(self.repo.claim_subscription_email( + key=self.key, now=due + timedelta(days=1))) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_civiccomms_foundation.py b/tests/test_townlight_comms_foundation.py similarity index 79% rename from tests/test_civiccomms_foundation.py rename to tests/test_townlight_comms_foundation.py index 74d047d..248084b 100644 --- a/tests/test_civiccomms_foundation.py +++ b/tests/test_townlight_comms_foundation.py @@ -1,13 +1,12 @@ from fastapi.testclient import TestClient -from civiccomms.audience_variants import draft_audience_variant -from civiccomms.faq import generate_faq -from civiccomms.main import app -from civiccomms.meeting_summary import draft_meeting_summary -from civiccomms.newsletter import draft_newsletter -from civiccomms.ordinance_summary import draft_ordinance_summary -from civiccomms.source_review import review_sources - +from townlight_comms.audience_variants import draft_audience_variant +from townlight_comms.faq import generate_faq +from townlight_comms.main import app +from townlight_comms.meeting_summary import draft_meeting_summary +from townlight_comms.newsletter import draft_newsletter +from townlight_comms.ordinance_summary import draft_ordinance_summary +from townlight_comms.source_review import review_sources client = TestClient(app) @@ -76,40 +75,40 @@ def test_audience_variant_preserves_review_boundary() -> None: assert "no autonomous posting" in result.boundary -def test_civiccomms_support_apis_success_shape() -> None: +def test_townlight_comms_support_apis_success_shape() -> None: assert client.post( - "/api/v1/civiccomms/source-review", + "/api/v1/townlight_comms/source-review", json={"source_titles": ["Council packet"], "citations": ["packet p. 2"]}, ).json()["ready_for_draft"] is True meeting_response = client.post( - "/api/v1/civiccomms/meeting-summary", + "/api/v1/townlight_comms/meeting-summary", json={"meeting_title": "Council", "actions": ["approved item 4"], "citations": ["minutes p. 3"]}, ) assert meeting_response.status_code == 200 assert meeting_response.json()["summary_id"] is None assert client.post( - "/api/v1/civiccomms/ordinance-summary", + "/api/v1/townlight_comms/ordinance-summary", json={"ordinance_id": "ORD-1", "topic": "trees", "citations": ["code 12.01"]}, ).status_code == 200 assert client.post( - "/api/v1/civiccomms/newsletter", + "/api/v1/townlight_comms/newsletter", json={"week_of": "2026-04-27", "source_items": ["park opening"]}, ).status_code == 200 assert client.post( - "/api/v1/civiccomms/faq", + "/api/v1/townlight_comms/faq", json={"topic": "parks", "source_facts": ["new hours"]}, ).status_code == 200 assert client.post( - "/api/v1/civiccomms/audience-variant", + "/api/v1/townlight_comms/audience-variant", json={"base_message": "New hours begin Monday.", "audience": "families"}, ).status_code == 200 def test_public_ui_route_is_accessible_and_honest() -> None: - response = client.get("/civiccomms") + response = client.get("/townlight_comms") assert response.status_code == 200 - assert "Townlight Communications v0.1.1" in response.text + assert "Townlight Communications v0.2.0" in response.text assert "Human approval required" in response.text assert "no campaign" in response.text.lower() assert "live LLM calls" in response.text diff --git a/civiccomms/__init__.py b/townlight_comms/__init__.py similarity index 73% rename from civiccomms/__init__.py rename to townlight_comms/__init__.py index db5e542..4865eab 100644 --- a/civiccomms/__init__.py +++ b/townlight_comms/__init__.py @@ -1,3 +1,3 @@ """Townlight Communications runtime foundation package.""" -__version__ = "0.1.1" +__version__ = "0.2.0" diff --git a/townlight_comms/approval.py b/townlight_comms/approval.py new file mode 100644 index 0000000..ec3f6a8 --- /dev/null +++ b/townlight_comms/approval.py @@ -0,0 +1,86 @@ +import hashlib + +from sqlalchemy import select + +from .models import approvals, articles, attachments +from .store import Conflict, InvalidInput, canonical_bytes, utcnow + + +class ApprovalMixin: + def approve(self, article_id, expected_revision, expected_sha256, actor, verified_sources): + if not isinstance(actor, str) or not actor or len(actor) > 128: + raise InvalidInput("actor") + if not isinstance(expected_sha256, str) or not expected_sha256: + raise InvalidInput("expected_sha256") + with self.engine.begin() as conn: + art = self._article(conn, article_id, expected_revision, lock=True) + if art["state"] != "review": + raise Conflict("state") + rev = self._revision(conn, article_id, art["current_revision"]) + if rev["sha256"] != expected_sha256: + raise Conflict("sha256") + sources = self._public_sources(verified_sources) + if canonical_bytes(sources) != canonical_bytes(rev["source_refs"]): + raise Conflict("sources") + access = rev["access_review"] + if (not isinstance(access, dict) or access.get("reviewed") is not True + or not isinstance(access.get("findings"), list)): + raise Conflict("access_review") + refs = rev["attachment_refs"] or [] + if not isinstance(refs, list): + raise Conflict("attachments") + for ref in refs: + if not isinstance(ref, dict) or ref.get("public") is not True: + raise Conflict("attachment_public") + attachment_id = ref.get("id") + if attachment_id is None: + attachment_id = ref.get("attachment_id") + if not isinstance(attachment_id, str) or not attachment_id: + raise Conflict("attachment") + row = conn.execute( + select(attachments).where( + attachments.c.id == attachment_id, + attachments.c.article_id == article_id, + ) + ).first() + if row is None: + raise Conflict("attachment") + actual = row._mapping + if (ref.get("name") != actual.get("name") + or ref.get("media_type") != actual.get("media_type")): + raise Conflict("attachment_manifest") + blob = next((actual[k] for k in ("content", "data", "bytes", "blob") + if k in actual), None) + if not isinstance(blob, (bytes, bytearray, memoryview)): + raise Conflict("attachment") + digest = hashlib.sha256(blob).hexdigest() + if len(blob) != ref.get("size") or digest != ref.get("sha256"): + raise Conflict("attachment_manifest") + prior = conn.execute( + select(approvals.c.sha256).where( + approvals.c.article_id == article_id, + approvals.c.revision == expected_revision, + ) + ).scalar_one_or_none() + if prior is None: + conn.execute(approvals.insert().values( + article_id=article_id, + revision=expected_revision, + sha256=expected_sha256, + actor=actor, + created_at=utcnow(), + )) + elif prior != expected_sha256: + raise Conflict("approval") + res = conn.execute( + articles.update().where( + articles.c.id == article_id, + articles.c.current_revision == expected_revision, + articles.c.state == "review", + ).values(state="approved", updated_at=utcnow()) + ) + if res.rowcount != 1: + raise Conflict("cas") + self._event(conn, article_id, expected_revision, "approved", actor, + {"sha256": expected_sha256}) + return self.get(article_id) \ No newline at end of file diff --git a/townlight_comms/attachments.py b/townlight_comms/attachments.py new file mode 100644 index 0000000..4c4826b --- /dev/null +++ b/townlight_comms/attachments.py @@ -0,0 +1,205 @@ +"""Attachment workflows built on immutable article revisions.""" + +from __future__ import annotations + +import hashlib + +from sqlalchemy import select, update + +from .models import articles, attachments, publications +from .store import Conflict, InvalidInput, NotFound, new_id, utcnow + +_MAX_ATTACHMENT_SIZE = 10 * 1024 * 1024 + + +class AttachmentMixin: + """Add/remove attachment references and read verified stored bytes.""" + + def _bump(self, conn, article_id, expected_revision, actor, newrefs): + """Publish a new draft revision carrying ``newrefs`` as its manifest.""" + self._article(conn, article_id, expected_revision, lock=True) + self._require_published_archives(conn, article_id) + old = self._revision(conn, article_id, expected_revision) + content = self._content( + old["title"], + old["body"], + old["language"], + old["source_refs"], + old["access_review"], + old["translation_provenance"], + attachment_refs=newrefs, + ) + claimed = conn.execute( + select(publications.c.id).where( + publications.c.article_id == article_id, + publications.c.state == "claimed", + ) + ).first() + if claimed is not None: + raise Conflict("ongoing publication") + now = utcnow() + next_revision = expected_revision + 1 + result = conn.execute( + update(articles) + .where( + articles.c.id == article_id, + articles.c.current_revision == expected_revision, + ) + .values( + title=content["title"], + current_revision=next_revision, + state="draft", + updated_at=now, + ) + ) + if result.rowcount != 1: + raise Conflict("revision mismatch") + self._insert_revision(conn, article_id, next_revision, content, actor, now) + conn.execute( + update(publications) + .where( + publications.c.article_id == article_id, + publications.c.revision == expected_revision, + publications.c.state == "pending", + ) + .values(state="failed", last_error="superseded", updated_at=now) + ) + return content, next_revision, now + + def add_attachment( + self, + article_id, + expected_revision, + actor, + name, + media_type, + content, + public=False, + ): + actor = self._require_actor(actor) + expected_revision = self._require_expected(expected_revision) + name = self._bounded(name, "name", 150) + media_type = self._bounded(media_type, "media_type", 128) + if not isinstance(content, bytes): + raise InvalidInput("content") + size = len(content) + if not 1 <= size <= _MAX_ATTACHMENT_SIZE: + raise InvalidInput("content") + if not isinstance(public, bool): + raise InvalidInput("public") + attachment_id = new_id() + sha256 = hashlib.sha256(content).hexdigest() + ref = { + "id": attachment_id, + "name": name, + "media_type": media_type, + "size": size, + "sha256": sha256, + "public": public, + } + with self.engine.begin() as conn: + old = self._revision(conn, article_id, expected_revision) + refs = list(old["attachment_refs"]) + [ref] + # _bump validates the complete 20-file / 20 MiB manifest. + _, next_revision, now = self._bump( + conn, article_id, expected_revision, actor, refs + ) + conn.execute( + attachments.insert().values( + id=attachment_id, + article_id=article_id, + revision=next_revision, + name=name, + media_type=media_type, + content=content, + sha256=sha256, + size=size, + public=public, + created_at=now, + ) + ) + self._event( + conn, + article_id, + next_revision, + "attachment_added", + actor, + {"attachment_id": attachment_id, "sha256": sha256, "size": size}, + ) + return self.get(article_id) + + def remove_attachment( + self, article_id, expected_revision, actor, attachment_id + ): + actor = self._require_actor(actor) + expected_revision = self._require_expected(expected_revision) + with self.engine.begin() as conn: + old = self._revision(conn, article_id, expected_revision) + refs = [] + found = False + for ref in old["attachment_refs"]: + if ref.get("id") == attachment_id: + found = True + else: + refs.append(ref) + if not found: + raise NotFound(attachment_id) + _, next_revision, _ = self._bump( + conn, article_id, expected_revision, actor, refs + ) + self._event( + conn, + article_id, + next_revision, + "attachment_removed", + actor, + {"attachment_id": attachment_id}, + ) + return self.get(article_id) + + def read_attachment(self, article_id, attachment_id, revision=None): + if revision is not None: + revision = self._require_expected(revision, "revision") + with self.engine.connect() as conn: + article = self._article(conn, article_id) + if revision is None: + revision = article.get("current_revision") + if revision is None: + revision = article.get("revision") + current = self._revision(conn, article_id, revision) + ref = next( + ( + item + for item in current["attachment_refs"] + if item.get("id") == attachment_id + ), + None, + ) + if ref is None: + raise NotFound(attachment_id) + row = conn.execute( + select(attachments).where( + attachments.c.id == attachment_id, + attachments.c.article_id == article_id, + ) + ).mappings().first() + if row is None: + raise NotFound(attachment_id) + data = row["content"] + actual = hashlib.sha256(data).hexdigest() + if ( + len(data) != ref["size"] + or actual != ref["sha256"] + or row["sha256"] != ref["sha256"] + or row["size"] != ref["size"] + or row["name"] != ref["name"] + or row["media_type"] != ref["media_type"] + ): + raise Conflict("attachment mismatch") + return { + "content": data, + "name": row["name"], + "media_type": row["media_type"], + "sha256": row["sha256"], + "size": row["size"], + } diff --git a/civiccomms/audience_variants.py b/townlight_comms/audience_variants.py similarity index 100% rename from civiccomms/audience_variants.py rename to townlight_comms/audience_variants.py diff --git a/townlight_comms/editorial.py b/townlight_comms/editorial.py new file mode 100644 index 0000000..0ccc84f --- /dev/null +++ b/townlight_comms/editorial.py @@ -0,0 +1,110 @@ +"""Editorial workflow: create, edit and review only.""" + +from __future__ import annotations + +from sqlalchemy import select + +from .models import ARTICLE_KINDS, articles, publications, revisions +from .store import Conflict, InvalidInput, new_id, utcnow + + +class EditorialMixin: + """Durable append-only editorial operations with audit events.""" + + def _require_actor(self, actor): + return self._bounded(actor, "actor", 128) + + def _require_expected(self, value, name="expected_revision"): + if isinstance(value, bool) or not isinstance(value, int) or value < 1: + raise InvalidInput(name) + return value + + def create(self, actor, kind, title, body, language, sources, + access_review=None, translation_provenance=None): + actor = self._require_actor(actor) + if kind not in ARTICLE_KINDS: + raise InvalidInput("kind") + content = self._content(title, body, language, sources, + access_review, translation_provenance) + article_id, now = new_id(), utcnow() + with self.engine.begin() as conn: + conn.execute(articles.insert().values( + id=article_id, title=content["title"], kind=kind, + current_revision=1, state="draft", + created_at=now, updated_at=now)) + self._insert_revision(conn, article_id, 1, content, actor, now) + self._event(conn, article_id, 1, "created", actor, + {"kind": kind, "sha256": content["sha256"]}) + return self.get(article_id) + + def edit(self, article_id, actor, expected_revision, title, body, language, + sources, access_review=None, translation_provenance=None): + actor = self._require_actor(actor) + expected_revision = self._require_expected(expected_revision) + content = self._content(title, body, language, sources, + access_review, translation_provenance) + now, next_revision = utcnow(), expected_revision + 1 + with self.engine.begin() as conn: + self._article(conn, article_id, expected_revision, lock=True) + self._require_published_archives(conn, article_id) + old = self._revision(conn, article_id, expected_revision) + content = self._content( + title, body, language, sources, access_review, + translation_provenance, + attachment_refs=old["attachment_refs"]) + claimed = conn.execute( + select(publications.c.id).where( + publications.c.article_id == article_id, + publications.c.state == "claimed")).first() + if claimed is not None: + raise Conflict("ongoing publication") + result = conn.execute( + articles.update().where( + articles.c.id == article_id, + articles.c.current_revision == expected_revision).values( + title=content["title"], current_revision=next_revision, + state="draft", updated_at=now)) + if result.rowcount != 1: + raise Conflict("revision mismatch") + self._insert_revision(conn, article_id, next_revision, content, actor, now) + conn.execute(publications.update().where( + publications.c.article_id == article_id, + publications.c.revision == expected_revision, + publications.c.state == "pending").values( + state="failed", last_error="superseded", updated_at=now)) + self._event(conn, article_id, next_revision, "edited", actor, + {"sha256": content["sha256"], + "superseded_revision": expected_revision}) + return self.get(article_id) + + def review(self, article_id, actor, expected_revision, note): + actor = self._require_actor(actor) + expected_revision = self._require_expected(expected_revision) + note = self._bounded(note, "note", 2000) + now = utcnow() + with self.engine.begin() as conn: + article = self._article(conn, article_id, expected_revision, lock=True) + if article["state"] not in ("draft", "review"): + raise Conflict("state") + result = conn.execute( + articles.update().where( + articles.c.id == article_id, + articles.c.current_revision == expected_revision, + articles.c.state.in_(("draft", "review"))).values( + state="review", updated_at=now)) + if result.rowcount != 1: + raise Conflict("state") + self._event(conn, article_id, expected_revision, "reviewed", actor, + {"note": note}) + return self.get(article_id) + + @staticmethod + def _insert_revision(conn, article_id, revision, content, actor, now): + conn.execute(revisions.insert().values( + article_id=article_id, revision=revision, title=content["title"], + body=content["body"], language=content["language"], + source_refs=content["source_refs"], + attachment_refs=content.get("attachment_refs", []), + access_review=content["access_review"], + translation_provenance=content["translation_provenance"], + sha256=content["sha256"], actor=actor, created_at=now)) diff --git a/townlight_comms/email_claims.py b/townlight_comms/email_claims.py new file mode 100644 index 0000000..73377a9 --- /dev/null +++ b/townlight_comms/email_claims.py @@ -0,0 +1,297 @@ +from __future__ import annotations + +import uuid +from datetime import UTC, datetime, timedelta + +from sqlalchemy import and_, case, func, or_, select, update + +from .models import approvals, articles, email_outbox, publications, subscribers +from .store import InvalidInput + +_SKIP = "skipped: not deliverable" +_STALE = "publication revision outdated" +_INACTIVE = "skipped: subscriber inactive or unconfirmed" +_EXPIRED = "lease expired" +_RETRY = "delivery retry scheduled" +_FAILED = "delivery failed" +_UNCERTAIN = "delivery outcome uncertain" +_MAX_ATTEMPTS = 5 +_MAX_BACKOFF = 3600 +_MAX_SKIP_ITERATIONS = 100 + + +def _utc(value): + if value is None: + return None + if value.tzinfo is None: + return value.replace(tzinfo=UTC) + return value.astimezone(UTC) + + +class EmailClaimsMixin: + def claim_email(self, now=None, lease_seconds=120): + if ( + isinstance(lease_seconds, bool) + or not isinstance(lease_seconds, int) + or not 30 <= lease_seconds <= 600 + ): + raise InvalidInput("lease_seconds") + + now = _utc(now) or datetime.now(UTC) + lease_until = now + timedelta(seconds=lease_seconds) + dialect = self.engine.dialect.name + + with self.engine.begin() as conn: + conn.execute( + update(email_outbox) + .where( + and_( + email_outbox.c.state == "claimed", + email_outbox.c.lease_until.is_not(None), + email_outbox.c.lease_until <= now, + ) + ) + .values( + state="uncertain", + last_error=_EXPIRED, + claim_token=None, + lease_until=None, + ) + ) + + for _ in range(_MAX_SKIP_ITERATIONS): + stmt = ( + select( + email_outbox.c.id, + email_outbox.c.recipient, + email_outbox.c.subject, + email_outbox.c.body, + email_outbox.c.message_id, + email_outbox.c.attempts, + email_outbox.c.state, + subscribers.c.active, + subscribers.c.confirmed, + publications.c.revision.label("publication_revision"), + publications.c.channels, + publications.c.article_id, + articles.c.current_revision.label("article_revision"), + approvals.c.revision.label("approval_revision"), + ) + .select_from( + email_outbox.join( + subscribers, + subscribers.c.id == email_outbox.c.subscriber_id, + ) + .join( + publications, + publications.c.id == email_outbox.c.publication_id, + ) + .join(articles, articles.c.id == publications.c.article_id) + .outerjoin( + approvals, + and_( + approvals.c.article_id == publications.c.article_id, + approvals.c.revision == publications.c.revision, + ), + ) + ) + .where( + and_( + email_outbox.c.state == "pending", + or_( + email_outbox.c.next_attempt_at.is_(None), + email_outbox.c.next_attempt_at <= now, + ), + ) + ) + .order_by( + email_outbox.c.next_attempt_at, + email_outbox.c.created_at, + ) + .limit(1) + ) + if dialect == "postgresql": + stmt = stmt.with_for_update(skip_locked=True, of=email_outbox) + row = conn.execute(stmt).mappings().first() + if row is None: + return None + + email_id = row["id"] + if row["attempts"] >= _MAX_ATTEMPTS: + self._terminal(conn, email_id, _FAILED) + continue + if not row["active"] or not row["confirmed"]: + self._terminal(conn, email_id, _INACTIVE, skipped=True) + continue + + channels = row["channels"] + if not isinstance(channels, list) or "email" not in channels: + self._terminal(conn, email_id, _SKIP, skipped=True) + continue + if ( + row["article_revision"] != row["publication_revision"] + or row["approval_revision"] is None + ): + self._terminal(conn, email_id, _STALE) + continue + + token = str(uuid.uuid4()) + stale_ok = and_( + email_outbox.c.id == email_id, + email_outbox.c.state == "pending", + or_( + email_outbox.c.next_attempt_at.is_(None), + email_outbox.c.next_attempt_at <= now, + ), + ) + result = conn.execute( + update(email_outbox) + .where(stale_ok) + .values( + state="claimed", + claim_token=token, + attempts=email_outbox.c.attempts + 1, + lease_until=lease_until, + next_attempt_at=None, + last_error=None, + ) + ) + if result.rowcount != 1: + continue + return { + "id": email_id, + "claim_token": token, + "recipient": row["recipient"], + "subject": row["subject"], + "body": row["body"], + "message_id": row["message_id"], + } + + return None + + def finish_email(self, email_id, claim_token, outcome): + now = datetime.now(UTC) + with self.engine.begin() as conn: + row = ( + conn.execute( + select(email_outbox.c.attempts) + .where( + and_( + email_outbox.c.id == email_id, + email_outbox.c.state == "claimed", + email_outbox.c.claim_token == claim_token, + ) + ) + .limit(1) + ) + .mappings() + .first() + ) + if row is None: + return False + + values = { + "claim_token": None, + "lease_until": None, + "next_attempt_at": None, + } + if outcome == "sent": + values.update(state="sent", sent_at=now, last_error=None) + elif outcome == "retry": + if row["attempts"] >= _MAX_ATTEMPTS: + values.update(state="failed", last_error=_FAILED) + else: + delay = min(_MAX_BACKOFF, 2 ** min(row["attempts"], 12)) + values.update( + state="pending", + next_attempt_at=now + timedelta(seconds=delay), + last_error=_RETRY, + ) + elif outcome == "failed": + values.update(state="failed", last_error=_FAILED) + elif outcome == "uncertain": + values.update(state="uncertain", last_error=_UNCERTAIN) + elif outcome == "skipped": + values.update(state="failed", last_error=_SKIP) + else: + raise ValueError("invalid email outcome") + + result = conn.execute( + update(email_outbox) + .where( + and_( + email_outbox.c.id == email_id, + email_outbox.c.state == "claimed", + email_outbox.c.claim_token == claim_token, + ) + ) + .values(**values) + ) + return result.rowcount == 1 + + def email_summary(self, publication_id): + skipped = and_( + email_outbox.c.state == "failed", + email_outbox.c.last_error.like("skipped%"), + ) + failed = and_( + email_outbox.c.state == "failed", + or_( + email_outbox.c.last_error.is_(None), + ~email_outbox.c.last_error.like("skipped%"), + ), + ) + with self.engine.connect() as conn: + row = conn.execute( + select( + func.coalesce( + func.sum(case((email_outbox.c.state == "sent", 1), else_=0)), + 0, + ).label("sent"), + func.coalesce( + func.sum( + case( + ( + email_outbox.c.state.in_(("pending", "claimed")), + 1, + ), + else_=0, + ) + ), + 0, + ).label("remaining"), + func.coalesce( + func.sum(case((failed, 1), else_=0)), 0 + ).label("failed"), + func.coalesce( + func.sum( + case((email_outbox.c.state == "uncertain", 1), else_=0) + ), + 0, + ).label("uncertain"), + func.coalesce( + func.sum(case((skipped, 1), else_=0)), 0 + ).label("skipped"), + ).where(email_outbox.c.publication_id == publication_id) + ).mappings().one() + return {key: int(row[key]) for key in ("sent", "remaining", "failed", "uncertain", "skipped")} + + @staticmethod + def _terminal(conn, email_id, error, skipped=False): + _ = skipped + conn.execute( + update(email_outbox) + .where( + and_( + email_outbox.c.id == email_id, + email_outbox.c.state == "pending", + ) + ) + .values( + state="failed", + last_error=error, + claim_token=None, + lease_until=None, + next_attempt_at=None, + ) + ) diff --git a/townlight_comms/email_enqueue.py b/townlight_comms/email_enqueue.py new file mode 100644 index 0000000..c859b5b --- /dev/null +++ b/townlight_comms/email_enqueue.py @@ -0,0 +1,222 @@ +from __future__ import annotations + +import hashlib +import re +from urllib.parse import urlsplit + +from cryptography.fernet import Fernet +from sqlalchemy import func, select + +from .models import approvals, articles, email_outbox, publications, revisions, subscribers +from .store import Conflict, InvalidInput, NotFound, Unauthorized, new_id, utcnow + +_CRLF = re.compile(r"[\r\n]+") + + +class EmailEnqueueMixin: + @staticmethod + def _public_url(value): + if value is None: + return None + if not isinstance(value, str) or not value or len(value) > 2048: + raise InvalidInput("public_url") + if any(ord(ch) < 32 or ord(ch) == 127 or ch.isspace() for ch in value): + raise InvalidInput("public_url") + if "?" in value or "#" in value: + raise InvalidInput("public_url") + parts = urlsplit(value) + if parts.scheme.lower() != "https" or not parts.hostname: + raise InvalidInput("public_url") + if parts.username is not None or parts.password is not None: + raise InvalidInput("public_url") + if parts.query or parts.fragment: + raise InvalidInput("public_url") + return value + + @staticmethod + def _topics(value): + if isinstance(value, str): + return {value} + if not isinstance(value, list): + return set() + return {item for item in value if isinstance(item, str)} + + @staticmethod + def _action(pub): + action = pub.get("action") + if hasattr(action, "value"): + action = action.value + if not isinstance(action, str): + return "publish" + return action.strip().lower() + + def _preferences_body(self, conn, body, subscriber_id, token_hash): + from .subscription_apply import _origin + from .subscription_models import subscription_preferences_keys + from .subscriptions import _hash + + row = conn.execute( + select(subscription_preferences_keys.c.encrypted_token).where( + subscription_preferences_keys.c.subscriber_id == subscriber_id + ) + ).first() + if row is None: + return body + token = Fernet(self.recovery_key).decrypt( + row.encrypted_token.encode("ascii") + ).decode("ascii") + if _hash(token) != token_hash: + raise Unauthorized("invalid preferences token") + origin = _origin(self.public_origin) + linked = f"{body}\nManage preferences or unsubscribe: {origin}/communications/preferences/?token={token}" + return "fernet:" + Fernet(self.recovery_key).encrypt( + linked.encode("utf-8") + ).decode("ascii") + + def enqueue_publication_email(self, publication_id, claim_token, public_url): + public_url = self._public_url(public_url) + if not isinstance(claim_token, str) or not claim_token: + raise InvalidInput("claim_token") + now = utcnow() + with self.engine.begin() as conn: + pub_row = conn.execute( + select(publications) + .where(publications.c.id == publication_id) + .with_for_update() + ).mappings().first() + if pub_row is None: + raise NotFound(publication_id) + pub = dict(pub_row) + if pub["state"] != "claimed": + raise Conflict("publication not claimed") + if pub["claim_token"] != claim_token: + raise Unauthorized("claim token") + + channels = pub["channels"] + if not isinstance(channels, list) or "email" not in channels: + raise InvalidInput("email channel") + email_only = bool(channels) and all(channel == "email" for channel in channels) + if public_url is None and not email_only: + raise InvalidInput("public_url") + + article_row = conn.execute( + select(articles).where(articles.c.id == pub["article_id"]) + ).mappings().first() + if article_row is None: + raise NotFound(pub["article_id"]) + article = dict(article_row) + + revision_row = conn.execute( + select(revisions).where( + revisions.c.article_id == pub["article_id"], + revisions.c.revision == pub["revision"], + ) + ).mappings().first() + if revision_row is None: + raise NotFound("revision") + revision = dict(revision_row) + + approval_row = conn.execute( + select(approvals).where( + approvals.c.article_id == pub["article_id"], + approvals.c.revision == pub["revision"], + ) + ).mappings().first() + if approval_row is None: + raise Conflict("approval missing") + if dict(approval_row)["sha256"] != revision["sha256"]: + raise Conflict("approval hash mismatch") + + source_kinds = { + ref.get("kind") + for ref in revision.get("source_refs", []) + if isinstance(ref, dict) + } + announcement = article["kind"] == "announcement" + subscriber_rows = conn.execute( + select(subscribers) + .where( + subscribers.c.active.is_(True), + subscribers.c.confirmed.is_(True), + subscribers.c.language == revision["language"], + ) + .order_by(subscribers.c.id) + ).mappings().all() + + existing = { + row["subscriber_id"] + for row in conn.execute( + select(email_outbox.c.subscriber_id).where( + email_outbox.c.publication_id == publication_id + ) + ).mappings() + } + + title = _CRLF.sub(" ", revision["title"]).strip() or "Notification" + action = self._action(pub) + if action in {"withdraw", "withdrawal", "withdrawn"}: + subject = f"Withdrawn: {title}" + body = f"This communication has been withdrawn: {title}." + elif action in {"correct", "correction", "corrected"}: + subject = f"Correction: {title}" + body = revision["body"] + else: + subject = title + body = revision["body"] + if public_url is not None: + body = f"{body}\n\n{public_url}" + + for sub_row in subscriber_rows: + sub = dict(sub_row) + topics = self._topics(sub["topics"]) + if announcement and not source_kinds: + eligible = "all" in topics + else: + eligible = "all" in topics or bool(topics & source_kinds) + if not eligible: + continue + subscriber_id = sub["id"] + if subscriber_id in existing: + # Already queued for this publication: idempotent no-op, + # not a skipped delivery. Only terminal states count. + continue + message_id = "<{}@townlight.local>".format( + hashlib.sha256( + f"{publication_id}:{subscriber_id}".encode() + ).hexdigest() + ) + outbox_body = self._preferences_body( + conn, body, subscriber_id, sub["token_hash"] + ) + conn.execute( + email_outbox.insert().values( + id=new_id(), + publication_id=publication_id, + subscriber_id=subscriber_id, + message_id=message_id, + recipient=sub["email"], + subject=subject, + body=outbox_body, + state="pending", + attempts=0, + next_attempt_at=now, + created_at=now, + ) + ) + existing.add(subscriber_id) + + counts = { + "pending": 0, + "sent": 0, + "failed": 0, + "uncertain": 0, + "skipped": 0, + } + for state, count in conn.execute( + select(email_outbox.c.state, func.count()) + .where(email_outbox.c.publication_id == publication_id) + .group_by(email_outbox.c.state) + ): + if state in counts: + counts[state] = int(count) + return counts diff --git a/civiccomms/faq.py b/townlight_comms/faq.py similarity index 100% rename from civiccomms/faq.py rename to townlight_comms/faq.py diff --git a/civiccomms/main.py b/townlight_comms/main.py similarity index 75% rename from civiccomms/main.py rename to townlight_comms/main.py index ea47d0f..09ace13 100644 --- a/civiccomms/main.py +++ b/townlight_comms/main.py @@ -2,25 +2,24 @@ import os -from civiccore import __version__ as CIVICCORE_VERSION from fastapi import FastAPI, HTTPException, Response from fastapi.responses import HTMLResponse from pydantic import BaseModel - -from civiccomms import __version__ -from civiccomms.audience_variants import draft_audience_variant -from civiccomms.faq import generate_faq -from civiccomms.meeting_summary import draft_meeting_summary -from civiccomms.newsletter import draft_newsletter -from civiccomms.ordinance_summary import draft_ordinance_summary -from civiccomms.persistence import ( +from townlight_core import __version__ as TOWNLIGHT_CORE_VERSION + +from townlight_comms import __version__ +from townlight_comms.audience_variants import draft_audience_variant +from townlight_comms.faq import generate_faq +from townlight_comms.meeting_summary import draft_meeting_summary +from townlight_comms.newsletter import draft_newsletter +from townlight_comms.ordinance_summary import draft_ordinance_summary +from townlight_comms.persistence import ( CommunicationsDraftRepository, StoredMeetingSummary, StoredSourceReview, ) -from civiccomms.public_ui import render_public_lookup_page -from civiccomms.source_review import review_sources - +from townlight_comms.public_ui import render_public_lookup_page +from townlight_comms.source_review import review_sources app = FastAPI( title='Townlight Communications', @@ -77,18 +76,18 @@ def root() -> dict[str, str]: """Return current product state without overstating unshipped behavior.""" return { - "name": "CivicComms", + "name": "Townlight Communications", "version": __version__, - "status": "public communications foundation plus draft persistence", + "status": "standalone draft-helper prototype", "message": ( - "Townlight Communications package, API foundation, source review, meeting summary drafts, " - "ordinance explainers, newsletter outlines, FAQ prompts, audience variants, optional " - "database-backed source review and meeting summary draft records, and public UI foundation " - "are online; autonomous publication, campaign content, legal advice, certified translation, " - "live LLM calls, social media posting, and communications system-of-record integrations are " - "not implemented yet." + "This standalone FastAPI server is a legacy draft-helper prototype, not a secured production " + "workflow server. The canonical Communications workflow is in the authenticated Windows Suite " + "desktop runtime at /desktop/v1/communications; installed Windows candidate acceptance remains pending." + ), + "next_step": ( + "Use the authenticated Windows Suite Communications candidate at /desktop/v1/communications; " + "the standalone draft helpers are not a production deployment path." ), - "next_step": "Post-v0.1.1 roadmap: source connector imports, Townlight Access review handoff, and approval queues", } @@ -98,20 +97,20 @@ def health() -> dict[str, str]: return { "status": "ok", - "service": "civiccomms", + "service": "townlight_comms", "version": __version__, - "civiccore_version": CIVICCORE_VERSION, + "townlight_core_version": TOWNLIGHT_CORE_VERSION, } -@app.get("/civiccomms", response_class=HTMLResponse) -def public_civiccomms_page() -> str: +@app.get("/townlight_comms", response_class=HTMLResponse) +def public_townlight_comms_page() -> str: """Return the public sample communications support UI.""" return render_public_lookup_page() -@app.post("/api/v1/civiccomms/source-review") +@app.post("/api/v1/townlight_comms/source-review") def source_review(request: SourceReviewRequest) -> dict[str, object]: if _draft_database_url() is not None: stored = _get_draft_repository().create_source_review( @@ -129,14 +128,14 @@ def source_review(request: SourceReviewRequest) -> dict[str, object]: return payload -@app.get("/api/v1/civiccomms/source-review/{review_id}") +@app.get("/api/v1/townlight_comms/source-review/{review_id}") def get_source_review(review_id: str) -> dict[str, object]: if _draft_database_url() is None: raise HTTPException( status_code=503, detail={ "message": "Townlight Communications draft persistence is not configured.", - "fix": "Set CIVICCOMMS_DRAFT_DB_URL to retrieve persisted source review records.", + "fix": "Set TOWNLIGHT_COMMS_DRAFT_DB_URL to retrieve persisted source review records.", }, ) stored = _get_draft_repository().get_source_review(review_id) @@ -145,13 +144,13 @@ def get_source_review(review_id: str) -> dict[str, object]: status_code=404, detail={ "message": "Source review record not found.", - "fix": "Use a review_id returned by POST /api/v1/civiccomms/source-review.", + "fix": "Use a review_id returned by POST /api/v1/townlight_comms/source-review.", }, ) return _stored_source_review_response(stored) -@app.post("/api/v1/civiccomms/meeting-summary") +@app.post("/api/v1/townlight_comms/meeting-summary") def meeting_summary(request: MeetingSummaryRequest) -> dict[str, object]: if _draft_database_url() is not None: stored = _get_draft_repository().create_meeting_summary( @@ -173,14 +172,14 @@ def meeting_summary(request: MeetingSummaryRequest) -> dict[str, object]: return payload -@app.get("/api/v1/civiccomms/meeting-summary/{summary_id}") +@app.get("/api/v1/townlight_comms/meeting-summary/{summary_id}") def get_meeting_summary(summary_id: str) -> dict[str, object]: if _draft_database_url() is None: raise HTTPException( status_code=503, detail={ "message": "Townlight Communications draft persistence is not configured.", - "fix": "Set CIVICCOMMS_DRAFT_DB_URL to retrieve persisted meeting summary records.", + "fix": "Set TOWNLIGHT_COMMS_DRAFT_DB_URL to retrieve persisted meeting summary records.", }, ) stored = _get_draft_repository().get_meeting_summary(summary_id) @@ -189,13 +188,13 @@ def get_meeting_summary(summary_id: str) -> dict[str, object]: status_code=404, detail={ "message": "Meeting summary record not found.", - "fix": "Use a summary_id returned by POST /api/v1/civiccomms/meeting-summary.", + "fix": "Use a summary_id returned by POST /api/v1/townlight_comms/meeting-summary.", }, ) return _stored_meeting_summary_response(stored) -@app.post("/api/v1/civiccomms/ordinance-summary") +@app.post("/api/v1/townlight_comms/ordinance-summary") def ordinance_summary(request: OrdinanceSummaryRequest) -> dict[str, object]: return draft_ordinance_summary( ordinance_id=request.ordinance_id, @@ -204,7 +203,7 @@ def ordinance_summary(request: OrdinanceSummaryRequest) -> dict[str, object]: ).__dict__ -@app.post("/api/v1/civiccomms/newsletter") +@app.post("/api/v1/townlight_comms/newsletter") def newsletter(request: NewsletterRequest) -> dict[str, object]: return draft_newsletter( week_of=request.week_of, @@ -212,7 +211,7 @@ def newsletter(request: NewsletterRequest) -> dict[str, object]: ).__dict__ -@app.post("/api/v1/civiccomms/faq") +@app.post("/api/v1/townlight_comms/faq") def faq(request: FAQRequest) -> dict[str, object]: return generate_faq( topic=request.topic, @@ -220,7 +219,7 @@ def faq(request: FAQRequest) -> dict[str, object]: ).__dict__ -@app.post("/api/v1/civiccomms/audience-variant") +@app.post("/api/v1/townlight_comms/audience-variant") def audience_variant(request: AudienceVariantRequest) -> dict[str, object]: return draft_audience_variant( base_message=request.base_message, @@ -229,14 +228,14 @@ def audience_variant(request: AudienceVariantRequest) -> dict[str, object]: def _draft_database_url() -> str | None: - return os.environ.get("CIVICCOMMS_DRAFT_DB_URL") + return os.environ.get("TOWNLIGHT_COMMS_DRAFT_DB_URL") def _get_draft_repository() -> CommunicationsDraftRepository: global _draft_db_url, _draft_repository db_url = _draft_database_url() if db_url is None: - raise RuntimeError("CIVICCOMMS_DRAFT_DB_URL is not configured.") + raise RuntimeError("TOWNLIGHT_COMMS_DRAFT_DB_URL is not configured.") if _draft_repository is None or db_url != _draft_db_url: _dispose_draft_repository() _draft_db_url = db_url diff --git a/civiccomms/meeting_summary.py b/townlight_comms/meeting_summary.py similarity index 100% rename from civiccomms/meeting_summary.py rename to townlight_comms/meeting_summary.py diff --git a/townlight_comms/migrations.py b/townlight_comms/migrations.py new file mode 100644 index 0000000..7d13d4d --- /dev/null +++ b/townlight_comms/migrations.py @@ -0,0 +1,137 @@ +"""Explicit schema setup and readiness checks for townlight_comms. + +This module never drops, renames, or migrates legacy prototype tables. The +only managed objects are the townlight_comms schema, its contract tables, and +the schema_versions bookkeeping table. +""" + +from __future__ import annotations + +from datetime import UTC, datetime + +from sqlalchemy import Column, DateTime, Integer, MetaData, Table, inspect, select +from sqlalchemy.schema import CreateSchema + +from . import subscription_models as subscription_models # noqa: PLC0414 - required for shared metadata registration side effect +from .models import SCHEMA, metadata + +SCHEMA_VERSION = 1 +VERSION_TABLE = "schema_versions" + +version_metadata = MetaData(schema=SCHEMA) +schema_versions = Table( + VERSION_TABLE, + version_metadata, + Column("version", Integer, primary_key=True), + Column("applied_at", DateTime(timezone=True), nullable=False), +) + + +class MigrationError(RuntimeError): + """Base error for schema setup and readiness failures.""" + + +class FutureVersionError(MigrationError): + """The database was created by a newer townlight_comms version.""" + + +def _bound(engine): + if engine.dialect.name == "sqlite": + translated = engine.execution_options(schema_translate_map={SCHEMA: None}) + return translated, None + return engine, SCHEMA + + +def _versions(conn, schema): + return [ + row[0] + for row in conn.execute( + select(schema_versions.c.version).order_by(schema_versions.c.version) + ) + ] + + +def _reject_future(versions): + future = [version for version in versions if version > SCHEMA_VERSION] + if future: + raise FutureVersionError( + f"database schema version {max(future)} is newer than supported version {SCHEMA_VERSION}" + ) + + +def upgrade(engine): + """Create the managed schema and tables, then record version 1. + + All work occurs in one transaction. Existing future-version databases are + rejected before any DDL is attempted. + """ + + bound, schema = _bound(engine) + with bound.begin() as conn: + inspector = inspect(conn) + if inspector.has_table(VERSION_TABLE, schema=schema): + existing = _versions(conn, schema) + _reject_future(existing) + else: + existing = [] + + if schema is not None: + conn.execute(CreateSchema(schema, if_not_exists=True)) + + metadata.create_all(conn) + version_metadata.create_all(conn) + + current = _versions(conn, schema) + if not current: + conn.execute( + schema_versions.insert().values( + version=SCHEMA_VERSION, + applied_at=datetime.now(UTC), + ) + ) + elif SCHEMA_VERSION not in current: + raise MigrationError("missing schema version 1") + + +def ready(engine): + """Return True when all contract tables/columns and schema version 1 exist. + + The check is read-only. A future schema version raises FutureVersionError. + """ + + bound, schema = _bound(engine) + inspector = inspect(bound) + + versions = [] + if inspector.has_table(VERSION_TABLE, schema=schema): + with bound.connect() as conn: + versions = _versions(conn, schema) + _reject_future(versions) + + expected = { + table.name: {column.name for column in table.columns} + for table in metadata.sorted_tables + } + expected[VERSION_TABLE] = {"version", "applied_at"} + + for name, columns in expected.items(): + if not inspector.has_table(name, schema=schema): + return False + actual = { + column["name"] + for column in inspector.get_columns(name, schema=schema) + } + if actual != columns: + return False + + return versions == [SCHEMA_VERSION] + + +__all__ = [ + "SCHEMA_VERSION", + "VERSION_TABLE", + "FutureVersionError", + "MigrationError", + "ready", + "upgrade", +] diff --git a/townlight_comms/models.py b/townlight_comms/models.py new file mode 100644 index 0000000..7224a04 --- /dev/null +++ b/townlight_comms/models.py @@ -0,0 +1,291 @@ +"""Durable Comms contract — SQLAlchemy Core tables (schema townlight_comms). + +Revisions/approvals are append-only; enforcement lives in the runtime layer. +All timestamps are timezone-aware DateTime values normalized to UTC by the caller. +""" + +from __future__ import annotations + +from sqlalchemy import ( + JSON, + BigInteger, + Boolean, + CheckConstraint, + Column, + DateTime, + ForeignKey, + Index, + Integer, + LargeBinary, + MetaData, + String, + Table, + Text, + UniqueConstraint, + text, +) + +SCHEMA = "townlight_comms" +metadata = MetaData(schema=SCHEMA) + +ARTICLE_STATES = ("draft", "review", "approved", "scheduled", "published", "withdrawn") +ARTICLE_KINDS = ("meeting_summary", "ordinance_explainer", "announcement", "faq", "newsletter") +SOURCE_KINDS = ("meetings", "code", "notice", "311", "parks") + +PUBLICATION_ACTIONS = ("publish", "correct", "withdraw") +PUBLICATION_STATES = ("pending", "claimed", "queued", "published", "failed", "uncertain") +EMAIL_STATES = ("pending", "claimed", "queued", "sent", "failed", "uncertain") + +UUID = String(36) + + +def _enum(col: str, values: tuple) -> str: + joined = ", ".join(f"'{v}'" for v in values) + return f"{col} IN ({joined})" + + +articles = Table( + "articles", + metadata, + Column("id", UUID, primary_key=True), + Column("title", String(512), nullable=False), + Column("kind", String(32), nullable=False), + Column("current_revision", Integer, nullable=False), + Column("state", String(16), nullable=False), + Column("created_at", DateTime(timezone=True), nullable=False), + Column("updated_at", DateTime(timezone=True), nullable=False), + CheckConstraint("current_revision > 0", name="ck_articles_current_revision_positive"), + CheckConstraint(_enum("state", ARTICLE_STATES), name="ck_articles_state"), + CheckConstraint(_enum("kind", ARTICLE_KINDS), name="ck_articles_kind"), + Index("ix_articles_state_updated", "state", "updated_at"), +) + +revisions = Table( + "revisions", + metadata, + Column( + "article_id", + UUID, + ForeignKey(f"{SCHEMA}.articles.id", ondelete="CASCADE", name="fk_revisions_article"), + primary_key=True, + ), + Column("revision", Integer, primary_key=True), + Column("title", String(512), nullable=False), + Column("body", Text, nullable=False), + Column("language", String(16), nullable=False), + Column("source_refs", JSON, nullable=False), + Column("attachment_refs", JSON, nullable=False, default=list), + Column("access_review", JSON, nullable=False), + Column("translation_provenance", JSON, nullable=True), + Column("sha256", String(64), nullable=False), + Column("actor", String(128), nullable=False), + Column("created_at", DateTime(timezone=True), nullable=False), + CheckConstraint("revision > 0", name="ck_revisions_revision_positive"), + Index("ix_revisions_article", "article_id", "revision"), +) + +attachments = Table( + "attachments", + metadata, + Column("id", UUID, primary_key=True), + Column( + "article_id", + UUID, + ForeignKey(f"{SCHEMA}.articles.id", ondelete="CASCADE", name="fk_attachments_article"), + nullable=False, + ), + Column("revision", Integer, nullable=False), + Column("name", String(512), nullable=False), + Column("media_type", String(128), nullable=False), + Column("content", LargeBinary, nullable=False), + Column("sha256", String(64), nullable=False), + Column("size", Integer, nullable=False), + Column("public", Boolean, nullable=False, server_default=text("false")), + Column("created_at", DateTime(timezone=True), nullable=False), + CheckConstraint("revision > 0", name="ck_attachments_revision_positive"), + CheckConstraint("size >= 0", name="ck_attachments_size_nonnegative"), + Index("ix_attachments_article_revision", "article_id", "revision"), +) + +approvals = Table( + "approvals", + metadata, + Column( + "article_id", + UUID, + ForeignKey(f"{SCHEMA}.articles.id", ondelete="CASCADE", name="fk_approvals_article"), + primary_key=True, + ), + Column("revision", Integer, primary_key=True), + Column("sha256", String(64), nullable=False), + Column("actor", String(128), nullable=False), + Column("created_at", DateTime(timezone=True), nullable=False), + CheckConstraint("revision > 0", name="ck_approvals_revision_positive"), +) + +approved_source_snapshots = Table( + "approved_source_snapshots", + metadata, + Column( + "article_id", + UUID, + ForeignKey(f"{SCHEMA}.articles.id", ondelete="CASCADE", name="fk_approved_source_snapshots_article"), + primary_key=True, + ), + Column("revision", Integer, primary_key=True), + Column("revision_sha256", String(64), nullable=False), + Column("snapshots", JSON, nullable=False), + Column("created_at", DateTime(timezone=True), nullable=False), + CheckConstraint("revision > 0", name="ck_approved_source_snapshots_revision_positive"), +) + +publications = Table( + "publications", + metadata, + Column("id", UUID, primary_key=True), + Column( + "article_id", + UUID, + ForeignKey(f"{SCHEMA}.articles.id", ondelete="CASCADE", name="fk_publications_article"), + nullable=False, + ), + Column("revision", Integer, nullable=False), + Column("action", String(16), nullable=False), + Column("channels", JSON, nullable=False), + Column("due_at", DateTime(timezone=True), nullable=False), + Column("state", String(16), nullable=False), + Column("claim_token", String(64), nullable=True), + Column("lease_until", DateTime(timezone=True), nullable=True), + Column("attempts", Integer, nullable=False, server_default=text("0")), + Column("next_attempt_at", DateTime(timezone=True), nullable=True), + Column("website_receipt", JSON, nullable=True), + Column("email_summary", JSON, nullable=True), + Column("last_error", Text, nullable=True), + Column("actor", String(128), nullable=False), + Column("created_at", DateTime(timezone=True), nullable=False), + Column("updated_at", DateTime(timezone=True), nullable=False), + CheckConstraint("revision > 0", name="ck_publications_revision_positive"), + CheckConstraint("attempts >= 0", name="ck_publications_attempts_nonnegative"), + CheckConstraint(_enum("action", PUBLICATION_ACTIONS), name="ck_publications_action"), + CheckConstraint(_enum("state", PUBLICATION_STATES), name="ck_publications_state"), + UniqueConstraint( + "article_id", "revision", "action", + name="uq_publications_article_revision_action", + ), + Index("ix_publications_due", "state", "due_at"), + Index("ix_publications_lease", "state", "lease_until"), +) + +subscribers = Table( + "subscribers", + metadata, + Column("id", UUID, primary_key=True), + Column("email", String(320), nullable=False), + Column("address_hash", String(64), nullable=False, unique=True), + Column("token_hash", String(64), nullable=False, unique=True), + Column("topics", JSON, nullable=False), + Column("language", String(16), nullable=False), + Column("active", Boolean, nullable=False, server_default=text("true")), + Column("confirmed", Boolean, nullable=False, server_default=text("false")), + Column("confirmation_hash", String(64), nullable=True), + Column("created_at", DateTime(timezone=True), nullable=False), + Column("updated_at", DateTime(timezone=True), nullable=False), + Index("ix_subscribers_active", "active"), +) + +email_outbox = Table( + "email_outbox", + metadata, + Column("id", UUID, primary_key=True), + Column( + "publication_id", + UUID, + ForeignKey(f"{SCHEMA}.publications.id", ondelete="CASCADE", name="fk_email_outbox_publication"), + nullable=False, + ), + Column( + "subscriber_id", + UUID, + ForeignKey(f"{SCHEMA}.subscribers.id", ondelete="CASCADE", name="fk_email_outbox_subscriber"), + nullable=False, + ), + Column("message_id", String(255), nullable=False, unique=True), + Column("recipient", String(320), nullable=False), + Column("subject", String(512), nullable=False), + Column("body", Text, nullable=False), + Column("state", String(16), nullable=False), + Column("attempts", Integer, nullable=False, server_default=text("0")), + Column("next_attempt_at", DateTime(timezone=True), nullable=True), + Column("claim_token", String(64), nullable=True), + Column("lease_until", DateTime(timezone=True), nullable=True), + Column("last_error", Text, nullable=True), + Column("created_at", DateTime(timezone=True), nullable=False), + Column("sent_at", DateTime(timezone=True), nullable=True), + CheckConstraint("attempts >= 0", name="ck_email_outbox_attempts_nonnegative"), + CheckConstraint(_enum("state", EMAIL_STATES), name="ck_email_outbox_state"), + UniqueConstraint( + "publication_id", "subscriber_id", + name="uq_email_outbox_publication_subscriber", + ), + Index("ix_email_outbox_due", "state", "next_attempt_at"), + Index("ix_email_outbox_lease", "state", "lease_until"), +) + +events = Table( + "events", + metadata, + Column("id", BigInteger().with_variant(Integer, "sqlite"), primary_key=True, autoincrement=True), + Column( + "article_id", + UUID, + ForeignKey(f"{SCHEMA}.articles.id", ondelete="CASCADE", name="fk_events_article"), + nullable=False, + ), + Column("revision", Integer, nullable=True), + Column("kind", String(32), nullable=False), + Column("actor", String(128), nullable=False), + Column("payload", JSON, nullable=False), + Column("created_at", DateTime(timezone=True), nullable=False), + CheckConstraint("revision IS NULL OR revision > 0", name="ck_events_revision_positive"), + Index("ix_events_article_created", "article_id", "created_at"), + Index("ix_events_kind_created", "kind", "created_at"), +) + +records_receipts = Table( + "records_receipts", + metadata, + Column( + "article_id", + UUID, + ForeignKey(f"{SCHEMA}.articles.id", ondelete="CASCADE", name="fk_records_receipts_article"), + primary_key=True, + ), + Column("revision", Integer, primary_key=True), + Column("archive_sha256", String(64), nullable=False), + Column("records_id", String(128), nullable=False), + Column("file_id", String(128), nullable=False), + Column("created_at", DateTime(timezone=True), nullable=False), + CheckConstraint("revision > 0", name="ck_records_receipts_revision_positive"), + Index("ix_records_receipts_records_id", "records_id"), +) + +__all__ = [ + "ARTICLE_KINDS", + "ARTICLE_STATES", + "EMAIL_STATES", + "PUBLICATION_ACTIONS", + "PUBLICATION_STATES", + "SCHEMA", + "SOURCE_KINDS", + "approvals", + "approved_source_snapshots", + "articles", + "attachments", + "email_outbox", + "events", + "metadata", + "publications", + "records_receipts", + "revisions", + "subscribers", +] diff --git a/civiccomms/newsletter.py b/townlight_comms/newsletter.py similarity index 100% rename from civiccomms/newsletter.py rename to townlight_comms/newsletter.py diff --git a/civiccomms/ordinance_summary.py b/townlight_comms/ordinance_summary.py similarity index 100% rename from civiccomms/ordinance_summary.py rename to townlight_comms/ordinance_summary.py diff --git a/civiccomms/persistence.py b/townlight_comms/persistence.py similarity index 96% rename from civiccomms/persistence.py rename to townlight_comms/persistence.py index 92ff639..2041cef 100644 --- a/civiccomms/persistence.py +++ b/townlight_comms/persistence.py @@ -7,9 +7,8 @@ import sqlalchemy as sa from sqlalchemy import Engine, create_engine -from civiccomms.meeting_summary import draft_meeting_summary -from civiccomms.source_review import review_sources - +from townlight_comms.meeting_summary import draft_meeting_summary +from townlight_comms.source_review import review_sources metadata = sa.MetaData() @@ -24,7 +23,7 @@ sa.Column("missing_items", sa.JSON(), nullable=False), sa.Column("boundary", sa.Text(), nullable=False), sa.Column("created_at", sa.DateTime(timezone=True), nullable=False), - schema="civiccomms", + schema="townlight_comms", ) meeting_summary_records = sa.Table( @@ -40,7 +39,7 @@ sa.Column("citations", sa.JSON(), nullable=False), sa.Column("boundary", sa.Text(), nullable=False), sa.Column("created_at", sa.DateTime(timezone=True), nullable=False), - schema="civiccomms", + schema="townlight_comms", ) @@ -76,11 +75,11 @@ class CommunicationsDraftRepository: def __init__(self, *, db_url: str | None = None, engine: Engine | None = None) -> None: base_engine = engine or create_engine(db_url or "sqlite+pysqlite:///:memory:", future=True) if base_engine.dialect.name == "sqlite": - self.engine = base_engine.execution_options(schema_translate_map={"civiccomms": None}) + self.engine = base_engine.execution_options(schema_translate_map={"townlight_comms": None}) else: self.engine = base_engine with self.engine.begin() as connection: - connection.execute(sa.text("CREATE SCHEMA IF NOT EXISTS civiccomms")) + connection.execute(sa.text("CREATE SCHEMA IF NOT EXISTS townlight_comms")) metadata.create_all(self.engine) def create_source_review( diff --git a/townlight_comms/public_artifact.py b/townlight_comms/public_artifact.py new file mode 100644 index 0000000..ae2aef2 --- /dev/null +++ b/townlight_comms/public_artifact.py @@ -0,0 +1,145 @@ +from __future__ import annotations + +import io +import zipfile + +from sqlalchemy import select + +from .models import approvals, attachments, revisions +from .store import Conflict, InvalidInput, canonical_bytes, digest + +_HEX = set("0123456789abcdef") + + +class ArtifactMixin: + def build_public_artifact(self, article_id, revision, expected_sha256, source_snapshots): + article_id = self._bounded(article_id, "article_id", 256) + if isinstance(revision, bool) or not isinstance(revision, int) or revision < 1: + raise InvalidInput("revision") + if ( + not isinstance(expected_sha256, str) + or len(expected_sha256) != 64 + or any(ch not in _HEX for ch in expected_sha256) + ): + raise InvalidInput("expected_sha256") + + with self.engine.connect() as conn: + revision_row = conn.execute( + select(revisions).where( + revisions.c.article_id == article_id, + revisions.c.revision == revision, + ) + ).mappings().first() + if revision_row is None: + raise Conflict("revision") + rev = dict(revision_row) + + approval = conn.execute( + select(approvals).where( + approvals.c.article_id == article_id, + approvals.c.revision == revision, + approvals.c.sha256 == expected_sha256, + ) + ).mappings().first() + if approval is None: + raise Conflict("approval") + + try: + sources = self._public_sources(rev.get("source_refs")) + refs = self._attachment_refs(rev.get("attachment_refs")) + except InvalidInput: + raise Conflict("revision manifest") from None + + if not isinstance(source_snapshots, list) or len(source_snapshots) != len(sources): + raise InvalidInput("source_snapshots") + snapshots = [] + total_snapshot_bytes = 0 + for snapshot, source in zip(source_snapshots, sources): + if ( + not isinstance(snapshot, dict) + or set(snapshot) != {"reference", "content"} + or snapshot["reference"] != source + ): + raise InvalidInput("source_snapshots") + snapshot_bytes = canonical_bytes(snapshot["content"]) + if len(snapshot_bytes) > 1024 * 1024: + raise InvalidInput("source_snapshots") + total_snapshot_bytes += len(snapshot_bytes) + if total_snapshot_bytes > 5 * 1024 * 1024: + raise InvalidInput("source_snapshots") + if digest(snapshot_bytes) != source.get("sha256"): + raise InvalidInput("source_snapshots") + snapshots.append( + {"reference": source, "content": snapshot["content"]} + ) + + content = { + "title": rev.get("title"), + "body": rev.get("body"), + "language": rev.get("language"), + "source_refs": sources, + "access_review": rev.get("access_review"), + "translation_provenance": rev.get("translation_provenance"), + "attachment_refs": refs, + } + actual_sha256 = digest(canonical_bytes(content)) + if ( + rev.get("sha256") != expected_sha256 + or actual_sha256 != expected_sha256 + ): + raise Conflict("sha256") + + files = [] + for ref in sorted(refs, key=lambda item: item["id"]): + if ref.get("public") is not True: + raise Conflict("attachment_public") + row = conn.execute( + select(attachments).where( + attachments.c.id == ref["id"], + attachments.c.article_id == article_id, + ) + ).mappings().first() + if row is None: + raise Conflict("attachment") + row = dict(row) + data = row.get("content") + if not isinstance(data, (bytes, bytearray, memoryview)): + raise Conflict("attachment") + data = bytes(data) + if ( + row.get("public") is not True + or row.get("name") != ref["name"] + or row.get("media_type") != ref["media_type"] + or row.get("size") != ref["size"] + or row.get("sha256") != ref["sha256"] + or len(data) != ref["size"] + or digest(data) != ref["sha256"] + ): + raise Conflict("attachment_manifest") + files.append((f"attachments/{ref['id']}", data)) + + payload = { + "schema_version": 1, + "article_id": article_id, + "revision": revision, + "title": content["title"], + "body": content["body"], + "language": content["language"], + "source_refs": content["source_refs"], + "source_snapshots": snapshots, + "access_review": content["access_review"], + "translation_provenance": content["translation_provenance"], + "attachment_refs": content["attachment_refs"], + "sha256": actual_sha256, + } + buffer = io.BytesIO() + with zipfile.ZipFile( + buffer, "w", compression=zipfile.ZIP_STORED, allowZip64=False + ) as archive: + for name, data in [("article.json", canonical_bytes(payload))] + files: + info = zipfile.ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0)) + info.compress_type = zipfile.ZIP_STORED + info.create_system = 0 + info.external_attr = 0 + archive.writestr(info, data) + return buffer.getvalue() diff --git a/civiccomms/public_ui.py b/townlight_comms/public_ui.py similarity index 90% rename from civiccomms/public_ui.py rename to townlight_comms/public_ui.py index c5ab515..e96fb84 100644 --- a/civiccomms/public_ui.py +++ b/townlight_comms/public_ui.py @@ -26,15 +26,15 @@ def render_public_lookup_page() -> str:

Townlight / Townlight Communications

Public explanations with sources attached.

-

Townlight Communications v0.1.1 helps staff shape meeting summaries, ordinance explainers, newsletters, FAQs, and audience variants from named municipal source material.

-

Shipping v0.1.1

+

Townlight Communications v0.2.0 helps staff shape meeting summaries, ordinance explainers, newsletters, FAQs, and audience variants from named municipal source material.

+

Shipping v0.2.0

What ships

  • Source-readiness review.
  • Meeting summary draft outlines.
  • Ordinance plain-language explainer drafts.
  • Newsletter and FAQ draft scaffolds.
  • Audience-specific variant drafts.

Human approval required

Every draft must be reviewed, cited, edited, and published by staff. Townlight Communications does not autonomously publish or post content.

-

Boundaries

No campaign or advocacy content, no legal advice, no certified translation, no live LLM calls, and no communications system-of-record integrations ship in v0.1.1.

-

Dependency

Pinned to civiccore==0.3.0. Townlight Core remains dependency-only; it never imports from Townlight Communications.

+

Boundaries

No campaign or advocacy content, no legal advice, no certified translation, no live LLM calls, and no communications system-of-record integrations ship in v0.2.0.

+

Dependency

Pinned to townlight_core==1.3.0.dev2. Townlight Core remains dependency-only; it never imports from Townlight Communications.

diff --git a/townlight_comms/publication_claims.py b/townlight_comms/publication_claims.py new file mode 100644 index 0000000..fe7ad09 --- /dev/null +++ b/townlight_comms/publication_claims.py @@ -0,0 +1,127 @@ +from datetime import timedelta + +from sqlalchemy import or_, select, update + +from .models import approvals, articles, publications +from .store import InvalidInput, new_id, utcnow + + +class PublicationClaimsMixin: + def claim_due(self, now=None, lease_seconds=120): + if not 30 <= lease_seconds <= 600: + raise InvalidInput("lease_seconds must be between 30 and 600") + now = utcnow() if now is None else now + lease_error = "claim lease expired; inspect before retry" + + with self.engine.begin() as conn: + conn.execute( + update(publications) + .where( + publications.c.state == "claimed", + publications.c.lease_until <= now, + ) + .values( + state="uncertain", + last_error=lease_error, + updated_at=now, + ) + ) + + job_row = conn.execute( + select(publications) + .where( + publications.c.state == "pending", + publications.c.due_at <= now, + or_( + publications.c.next_attempt_at.is_(None), + publications.c.next_attempt_at <= now, + ), + ) + .order_by(publications.c.due_at, publications.c.id) + .limit(1) + .with_for_update(skip_locked=True) + ).mappings().first() + + if job_row is None: + return None + + job = dict(job_row) + article_row = conn.execute( + select(articles.c.current_revision) + .where(articles.c.id == job["article_id"]) + ).mappings().first() + + if article_row is None or article_row["current_revision"] != job["revision"]: + conn.execute( + update(publications) + .where( + publications.c.id == job["id"], + publications.c.state == "pending", + ) + .values( + state="failed", + last_error="source changed", + updated_at=now, + ) + ) + return None + + revision = self._revision(conn, job["article_id"], job["revision"]) + + if job["action"] != "withdraw": + approved_row = conn.execute( + select(approvals.c.sha256) + .where( + approvals.c.article_id == job["article_id"], + approvals.c.revision == job["revision"], + ) + .limit(1) + ).mappings().first() + + if ( + approved_row is None + or revision is None + or approved_row["sha256"] != revision["sha256"] + ): + conn.execute( + update(publications) + .where( + publications.c.id == job["id"], + publications.c.state == "pending", + ) + .values( + state="failed", + last_error="source changed", + updated_at=now, + ) + ) + return None + + claim_token = new_id() + lease_until = now + timedelta(seconds=lease_seconds) + result = conn.execute( + update(publications) + .where( + publications.c.id == job["id"], + publications.c.state == "pending", + ) + .values( + state="claimed", + claim_token=claim_token, + lease_until=lease_until, + attempts=publications.c.attempts + 1, + updated_at=now, + ) + ) + if result.rowcount != 1: + return None + + job.update( + state="claimed", + claim_token=claim_token, + lease_until=lease_until, + attempts=job["attempts"] + 1, + updated_at=now, + ) + job["content"] = revision + return job \ No newline at end of file diff --git a/townlight_comms/publication_reconciliation.py b/townlight_comms/publication_reconciliation.py new file mode 100644 index 0000000..73bec68 --- /dev/null +++ b/townlight_comms/publication_reconciliation.py @@ -0,0 +1,185 @@ +"""Reconcile queued publications from caller-supplied queue acknowledgements.""" + +from __future__ import annotations + +from sqlalchemy import and_, case, func, insert, or_, select, update + +from .models import articles, email_outbox, events, publications +from .store import Conflict, InvalidInput, utcnow + +_RECEIPT_STATES = ("delivered", "withdrawn", "rejected", "superseded") +_FAILED = "publication failed" +_UNCERTAIN = "publication outcome uncertain" + + +def _channel(channels, name): + if isinstance(channels, dict): + return bool(channels.get(name)) + return name in (channels or ()) + + +def _receipt(value): + if not isinstance(value, dict): + return None + keys = ("status", "url", "queue_sequence", "queue_digest") + return {key: value[key] for key in keys if key in value} + + +class PublicationReconciliationMixin: + def queued_publications(self, limit=20): + if isinstance(limit, bool) or not isinstance(limit, int) or not 1 <= limit <= 100: + raise InvalidInput("limit") + with self.engine.connect() as conn: + rows = conn.execute( + select(publications) + .where(publications.c.state == "queued") + .order_by( + publications.c.due_at, + publications.c.created_at, + publications.c.id, + ) + .limit(limit) + ).mappings().all() + return [dict(row) for row in rows] + + @staticmethod + def _email_counts(conn, publication_id): + skipped = and_( + email_outbox.c.state == "failed", + email_outbox.c.last_error.like("skipped%"), + ) + failed = and_( + email_outbox.c.state == "failed", + or_( + email_outbox.c.last_error.is_(None), + ~email_outbox.c.last_error.like("skipped%"), + ), + ) + row = conn.execute( + select( + func.coalesce(func.sum(case((email_outbox.c.state == "sent", 1), else_=0)), 0).label("sent"), + func.coalesce(func.sum(case((email_outbox.c.state.in_(("pending", "claimed")), 1), else_=0)), 0).label("remaining"), + func.coalesce(func.sum(case((failed, 1), else_=0)), 0).label("failed"), + func.coalesce(func.sum(case((email_outbox.c.state == "uncertain", 1), else_=0)), 0).label("uncertain"), + func.coalesce(func.sum(case((skipped, 1), else_=0)), 0).label("skipped"), + ).where(email_outbox.c.publication_id == publication_id) + ).mappings().one() + return {key: int(row[key]) for key in ("sent", "remaining", "failed", "uncertain", "skipped")} + + def email_summary(self, publication_id): + with self.engine.connect() as conn: + return self._email_counts(conn, publication_id) + + def reconcile_publication(self, job_id, website_receipt=None): + now = utcnow() + with self.engine.begin() as conn: + job = conn.execute( + select(publications) + .where(publications.c.id == job_id, publications.c.state == "queued") + .with_for_update() + ).mappings().first() + if job is None: + raise Conflict("publication is not queued") + + channels = job["channels"] or () + website_requested = _channel(channels, "website") + email_requested = _channel(channels, "email") + summary = self._email_counts(conn, job_id) + stored = job["website_receipt"] + stored_receipt = stored if isinstance(stored, dict) else {} + ack = None + website_state = "ok" + + if website_requested: + if not isinstance(website_receipt, dict): + raise InvalidInput("website receipt is required") + status = website_receipt.get("status") + url = website_receipt.get("url") + if not url: + raise InvalidInput("website receipt is incomplete") + if stored_receipt.get("queue_sequence") is None or not stored_receipt.get("url"): + raise InvalidInput("stored queue receipt is incomplete") + if website_receipt.get("queue_sequence") != stored_receipt["queue_sequence"]: + raise Conflict("queue sequence mismatch") + stored_digest = stored_receipt.get("queue_digest") + supplied_digest = website_receipt.get("queue_digest") + if stored_digest is not None and supplied_digest is not None and stored_digest != supplied_digest: + raise Conflict("queue digest mismatch") + if url != stored_receipt["url"]: + raise Conflict("queue url changed") + expected = "withdrawn" if job["action"] == "withdraw" else "delivered" + if status == "queued": + website_state = "queued" + elif status not in _RECEIPT_STATES: + raise InvalidInput("invalid website receipt status") + elif status in ("rejected", "superseded") or status != expected: + website_state = "failed" + ack = _receipt(website_receipt) + + email_state = "ok" + if email_requested: + if summary["failed"] > 0: + email_state = "failed" + elif summary["uncertain"] > 0: + email_state = "uncertain" + elif summary["remaining"] > 0: + email_state = "queued" + + if website_state == "failed" or email_state == "failed": + final = "failed" + elif email_state == "uncertain": + final = "uncertain" + elif website_state == "queued" or email_state == "queued": + final = "queued" + else: + final = "published" + + receipt = ack if ack is not None else _receipt(stored) + if final == "queued": + result = conn.execute( + update(publications) + .where(publications.c.id == job_id, publications.c.state == "queued") + .values( + website_receipt=receipt, + email_summary=summary, + updated_at=now, + ) + ) + if result.rowcount != 1: + raise Conflict("publication changed") + return {"job_id": job_id, "state": "queued", "email_summary": summary, "website_receipt": receipt} + + result = conn.execute( + update(publications) + .where(publications.c.id == job_id, publications.c.state == "queued") + .values( + state=final, + website_receipt=receipt, + email_summary=summary, + last_error=_FAILED if final == "failed" else _UNCERTAIN if final == "uncertain" else None, + updated_at=now, + ) + ) + if result.rowcount != 1: + raise Conflict("publication changed") + if final == "published": + article_state = "withdrawn" if job["action"] == "withdraw" else "published" + conn.execute( + update(articles) + .where( + articles.c.id == job["article_id"], + articles.c.current_revision == job["revision"], + ) + .values(state=article_state, updated_at=now) + ) + conn.execute( + insert(events).values( + article_id=job["article_id"], + revision=job["revision"], + kind="publication_reconciled", + actor=job["actor"], + payload={"publication_id": job_id, "action": job["action"], "state": final}, + created_at=now, + ) + ) + return {"job_id": job_id, "state": final, "email_summary": summary, "website_receipt": receipt} diff --git a/townlight_comms/publication_results.py b/townlight_comms/publication_results.py new file mode 100644 index 0000000..cf20a3c --- /dev/null +++ b/townlight_comms/publication_results.py @@ -0,0 +1,109 @@ +"""Publication result finalization using SQLAlchemy Core.""" + +from __future__ import annotations + +from sqlalchemy import insert, select, update + +from .models import articles, events, publications +from .store import Conflict, InvalidInput, utcnow + +SANITIZED_ERROR = "publication failed" +_FINAL_STATES = ("queued", "published", "failed", "uncertain") + + +def _event(conn, *, article_id, revision, kind, actor, payload, created_at): + conn.execute( + insert(events).values( + article_id=article_id, + revision=revision, + kind=kind, + actor=actor, + payload=payload, + created_at=created_at, + ) + ) + + +def _channel(channels, name): + if isinstance(channels, dict): + return bool(channels.get(name)) + return name in (channels or ()) + + +class PublicationResultsMixin: + def finish_publication( + self, + job_id, + claim_token, + website_receipt=None, + email_summary=None, + state="queued", + error=None, + ): + """Finalize a claimed publication and release its lease.""" + if state not in _FINAL_STATES: + raise InvalidInput("invalid publication result state") + now = utcnow() + with self.engine.begin() as conn: + job = conn.execute( + select(publications) + .where( + publications.c.id == job_id, + publications.c.claim_token == claim_token, + publications.c.state == "claimed", + ) + .with_for_update() + ).mappings().first() + if job is None: + raise Conflict("publication claim is no longer held") + channels = job["channels"] or () + if state == "published": + if _channel(channels, "website"): + expected = "withdrawn" if job["action"] == "withdraw" else "delivered" + if not isinstance(website_receipt, dict): + raise InvalidInput("website receipt is required") + if website_receipt.get("status") != expected or not website_receipt.get("url"): + raise InvalidInput("website receipt is incomplete") + if _channel(channels, "email"): + if not isinstance(email_summary, dict): + raise InvalidInput("email summary is required") + if any(email_summary.get(k) != 0 for k in ("remaining", "failed", "uncertain")): + raise InvalidInput("email summary is not complete") + changed = conn.execute( + update(publications) + .where( + publications.c.id == job_id, + publications.c.claim_token == claim_token, + publications.c.state == "claimed", + ) + .values( + state=state, + website_receipt=website_receipt, + email_summary=email_summary, + claim_token=None, + lease_until=None, + last_error=SANITIZED_ERROR if error else None, + updated_at=now, + ) + ) + if changed.rowcount != 1: + raise Conflict("publication claim changed") + if state == "published": + article_state = "withdrawn" if job["action"] == "withdraw" else "published" + conn.execute( + update(articles) + .where( + articles.c.id == job["article_id"], + articles.c.current_revision == job["revision"], + ) + .values(state=article_state, updated_at=now) + ) + _event( + conn, + article_id=job["article_id"], + revision=job["revision"], + kind="publication_finished", + actor=job["actor"], + payload={"publication_id": job_id, "action": job["action"], "state": state}, + created_at=now, + ) diff --git a/townlight_comms/records_archive.py b/townlight_comms/records_archive.py new file mode 100644 index 0000000..88b2139 --- /dev/null +++ b/townlight_comms/records_archive.py @@ -0,0 +1,68 @@ +from __future__ import annotations + +import io +import zipfile + +from sqlalchemy import select + +from .models import publications +from .records_guard import is_publication_exposed +from .store import Conflict, canonical_bytes + +_RECEIPTS_LIMIT = 100 +_ARCHIVE_LIMIT = 40 * 1024 * 1024 + +def _iso(value): + return None if value is None else (value.isoformat() if hasattr(value, "isoformat") else value) +def _counts(value): + if not isinstance(value, dict): + return {} + return {str(k): v for k, v in value.items() if isinstance(v, int) and not isinstance(v, bool)} +class RecordsArchiveMixin: + def build_records_archive(self, article_id, revision, expected_sha256): + article_id = self._bounded(article_id, "article_id", 256) + snapshots = self.get_source_snapshots(article_id, revision, expected_sha256) + public_artifact = self.build_public_artifact(article_id, revision, expected_sha256, snapshots) + with self.engine.connect() as conn: + publication_rows = conn.execute( + select(publications).where( + publications.c.article_id == article_id, + publications.c.revision == revision, + publications.c.action.in_(("publish", "correct")), + ).order_by(publications.c.created_at, publications.c.id).limit(_RECEIPTS_LIMIT + 1) + ).mappings().all() + exposed = [row for row in publication_rows if is_publication_exposed(row)] + if not exposed or len(exposed) > _RECEIPTS_LIMIT: + raise Conflict("publication_receipts") + receipts = [{ + "action": row["action"], + "due_at": _iso(row["due_at"]), + "state": row["state"], + "created_at": _iso(row["created_at"]), + "updated_at": _iso(row["updated_at"]), + "actor": row["actor"], + "website_receipt": row["website_receipt"], + "email_summary": _counts(row["email_summary"]), + } for row in exposed] + receipt_doc = { + "article_id": article_id, + "revision": revision, + "content_sha256": expected_sha256, + "publication_receipts": receipts, + } + files = [ + ("published-content.zip", public_artifact), + ("publication-receipts.json", canonical_bytes(receipt_doc)), + ] + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_STORED, allowZip64=False) as archive: + for name, data in files: + info = zipfile.ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0)) + info.compress_type = zipfile.ZIP_STORED + info.create_system = 0 + info.external_attr = 0 + archive.writestr(info, data) + result = buffer.getvalue() + if len(result) > _ARCHIVE_LIMIT: + raise Conflict("archive_size") + return result diff --git a/townlight_comms/records_guard.py b/townlight_comms/records_guard.py new file mode 100644 index 0000000..fc0d1d0 --- /dev/null +++ b/townlight_comms/records_guard.py @@ -0,0 +1,158 @@ +from __future__ import annotations + +import re +from uuid import UUID + +from sqlalchemy import select, update + +from .models import publications, records_receipts +from .store import Conflict, InvalidInput, utcnow + +_HEX64 = re.compile(r"^[0-9a-f]{64}$") +_PUBLISHED_ACTIONS = ("publish", "correct") +_EXPOSED_ROWS_LIMIT = 1000 + + +def is_publication_exposed(row): + if row is None: + return False + try: + action = row["action"] + state = row["state"] + website = row["website_receipt"] + email = row["email_summary"] + except (KeyError, TypeError): + return False + if action not in _PUBLISHED_ACTIONS: + return False + if state == "published": + return True + if isinstance(website, dict) and website.get("status") == "delivered": + return True + if isinstance(email, dict): + sent = email.get("sent") + if isinstance(sent, int) and not isinstance(sent, bool) and sent > 0: + return True + return False + + +def _uuid(value, name): + if not isinstance(value, str): + raise InvalidInput(name) + try: + return str(UUID(value)) + except (ValueError, AttributeError): + raise InvalidInput(name) from None + + +def _text(value, name, maximum): + if not isinstance(value, str) or not value or len(value) > maximum: + raise InvalidInput(name) + return value + + +def _revision(value): + if isinstance(value, bool) or not isinstance(value, int) or value < 1: + raise InvalidInput("revision") + return value + + +class RecordsGuardMixin: + def _require_published_archives(self, conn, article_id): + exposed_rows = conn.execute( + select(publications) + .where( + publications.c.article_id == article_id, + publications.c.action.in_(_PUBLISHED_ACTIONS), + ) + .order_by(publications.c.revision, publications.c.created_at, publications.c.id) + .limit(_EXPOSED_ROWS_LIMIT + 1) + ).mappings().all() + if len(exposed_rows) > _EXPOSED_ROWS_LIMIT: + raise Conflict("publication_receipts") + exposed_revisions = [] + for row in exposed_rows: + if is_publication_exposed(row) and row["revision"] not in exposed_revisions: + exposed_revisions.append(row["revision"]) + for revision in exposed_revisions: + receipt = conn.execute( + select(records_receipts.c.article_id) + .where( + records_receipts.c.article_id == article_id, + records_receipts.c.revision == revision, + ) + .limit(1) + ).first() + if receipt is None: + raise Conflict( + f"archive published revision {revision} in Records " + "before changes/withdrawal" + ) + + def record_records_receipt( + self, article_id, revision, archive_sha256, records_id, file_id + ): + article_id = _uuid(article_id, "article_id") + revision = _revision(revision) + if not isinstance(archive_sha256, str) or not _HEX64.fullmatch(archive_sha256): + raise InvalidInput("archive_sha256") + records_id = _text(records_id, "records_id", 128) + file_id = _uuid(file_id, "file_id") + + with self.engine.begin() as conn: + self._article(conn, article_id, lock=True) + publication_rows = conn.execute( + select(publications) + .where( + publications.c.article_id == article_id, + publications.c.revision == revision, + publications.c.action.in_(_PUBLISHED_ACTIONS), + ) + ).mappings().all() + if not any(is_publication_exposed(row) for row in publication_rows): + raise Conflict("revision is not published") + + existing = conn.execute( + select(records_receipts).where( + records_receipts.c.article_id == article_id, + records_receipts.c.revision == revision, + ) + ).mappings().first() + now = utcnow() + fields = { + "archive_sha256": archive_sha256, + "records_id": records_id, + "file_id": file_id, + } + if existing is None: + conn.execute( + records_receipts.insert().values( + article_id=article_id, + revision=revision, + archive_sha256=archive_sha256, + records_id=records_id, + file_id=file_id, + created_at=now, + ) + ) + return { + "article_id": article_id, + "revision": revision, + **fields, + "created_at": now, + } + + current = dict(existing) + if all(current[key] == value for key, value in fields.items()): + return current + conn.execute( + update(records_receipts) + .where( + records_receipts.c.article_id == article_id, + records_receipts.c.revision == revision, + ) + .values(**fields, created_at=now) + ) + current.update(fields) + current["created_at"] = now + return current diff --git a/townlight_comms/scheduling.py b/townlight_comms/scheduling.py new file mode 100644 index 0000000..cdc76e4 --- /dev/null +++ b/townlight_comms/scheduling.py @@ -0,0 +1,123 @@ +"""Schedule publish, correction and withdrawal jobs with durable audit state.""" + +from __future__ import annotations + +from datetime import UTC, datetime, timedelta + +from sqlalchemy import select + +from .models import PUBLICATION_ACTIONS, approvals, articles, publications +from .records_guard import is_publication_exposed +from .store import Conflict, InvalidInput, canonical_bytes, new_id, utcnow + +_ALLOWED_CHANNELS = ("website", "email") + + +def _utc(value): + if value.tzinfo is None: + return value.replace(tzinfo=UTC) + return value.astimezone(UTC) + + +class SchedulingMixin: + def schedule(self, article_id, expected_revision, expected_sha256, actor, + due_at, channels, action="publish"): + if not isinstance(actor, str) or not actor or len(actor) > 128: + raise InvalidInput("actor") + if (isinstance(expected_revision, bool) + or not isinstance(expected_revision, int) or expected_revision < 1): + raise InvalidInput("expected_revision") + if not isinstance(expected_sha256, str) or not expected_sha256: + raise InvalidInput("expected_sha256") + if action not in PUBLICATION_ACTIONS: + raise InvalidInput("action") + if (not isinstance(due_at, datetime) + or due_at.tzinfo is None or due_at.utcoffset() is None): + raise InvalidInput("due_at") + due_at = _utc(due_at) + if isinstance(channels, str) or not isinstance(channels, (list, tuple)) or not channels: + raise InvalidInput("channels") + channels = list(channels) + if len(set(channels)) != len(channels) or any(c not in _ALLOWED_CHANNELS for c in channels): + raise InvalidInput("channels") + + now = utcnow() + if due_at > now + timedelta(days=365): + raise InvalidInput("due_at") + with self.engine.begin() as conn: + art = self._article(conn, article_id, expected_revision, lock=True) + rev = self._revision(conn, article_id, expected_revision) + if rev["sha256"] != expected_sha256: + raise Conflict("sha256") + claimed = conn.execute(select(publications.c.id).where( + publications.c.article_id == article_id, + publications.c.state == "claimed", + ).limit(1)).first() + if claimed is not None: + raise Conflict("claimed publication") + + duplicate = False + existing = conn.execute(select(publications).where( + publications.c.article_id == article_id, + publications.c.revision == expected_revision, + publications.c.action == action, + )).mappings().first() + if existing is not None: + if (existing["actor"] == actor + and canonical_bytes(existing["channels"]) == canonical_bytes(channels) + and _utc(existing["due_at"]) == due_at): + duplicate = True + else: + raise Conflict("publication exists") + + if not duplicate: + if action in ("correct", "withdraw"): + self._require_published_archives(conn, article_id) + prior_rows = conn.execute(select(publications).where( + publications.c.article_id == article_id, + publications.c.action.in_(("publish", "correct")), + ).order_by(publications.c.created_at, publications.c.id).limit(1001)).mappings().all() + prior = next((row for row in prior_rows if is_publication_exposed(row)), None) + if prior is None: + raise Conflict("prior publication") + + publication_id = new_id() + if action in ("publish", "correct"): + if art["state"] != "approved": + raise Conflict("state") + approved_sha = conn.execute(select(approvals.c.sha256).where( + approvals.c.article_id == article_id, + approvals.c.revision == expected_revision, + )).scalar_one_or_none() + if approved_sha is None or approved_sha != expected_sha256: + raise Conflict("approval") + update = articles.update().where( + articles.c.id == article_id, + articles.c.current_revision == expected_revision, + articles.c.state == "approved", + ).values(state="scheduled", updated_at=now) + else: + update = articles.update().where( + articles.c.id == article_id, + articles.c.current_revision == expected_revision, + articles.c.state != "withdrawn", + ).values(state="scheduled", updated_at=now) + if conn.execute(update).rowcount != 1: + raise Conflict("state") + + conn.execute(publications.update().where( + publications.c.article_id == article_id, + publications.c.state == "pending", + publications.c.id != publication_id, + ).values(state="failed", last_error="superseded", updated_at=now)) + conn.execute(publications.insert().values( + id=publication_id, article_id=article_id, revision=expected_revision, + action=action, channels=channels, due_at=due_at, state="pending", + attempts=0, actor=actor, created_at=now, updated_at=now, + )) + self._event(conn, article_id, expected_revision, "scheduled", actor, { + "action": action, "publication_id": publication_id, + "sha256": expected_sha256, "channels": channels, + "due_at": due_at.isoformat(), + }) + return self.get(article_id) diff --git a/civiccomms/source_review.py b/townlight_comms/source_review.py similarity index 100% rename from civiccomms/source_review.py rename to townlight_comms/source_review.py diff --git a/townlight_comms/source_snapshots.py b/townlight_comms/source_snapshots.py new file mode 100644 index 0000000..a682b31 --- /dev/null +++ b/townlight_comms/source_snapshots.py @@ -0,0 +1,97 @@ +"""Immutable public source snapshots captured at approval time.""" + +from __future__ import annotations + +import copy + +from sqlalchemy import select + +from .models import approvals, approved_source_snapshots +from .store import Conflict, InvalidInput, canonical_bytes, utcnow + +_HEX = set("0123456789abcdef") + + +class SourceSnapshotMixin: + def _snapshot_identity(self, article_id, revision, expected_sha256): + article_id = self._bounded(article_id, "article_id", 256) + if isinstance(revision, bool) or not isinstance(revision, int) or revision < 1: + raise InvalidInput("revision") + if ( + not isinstance(expected_sha256, str) + or len(expected_sha256) != 64 + or any(ch not in _HEX for ch in expected_sha256) + ): + raise InvalidInput("expected_sha256") + return article_id, revision, expected_sha256 + + @staticmethod + def _approved(conn, article_id, revision, expected_sha256): + return conn.execute( + select(approvals.c.article_id).where( + approvals.c.article_id == article_id, + approvals.c.revision == revision, + approvals.c.sha256 == expected_sha256, + ) + ).first() is not None + + def capture_source_snapshots( + self, article_id, revision, expected_sha256, snapshots + ): + article_id, revision, expected_sha256 = self._snapshot_identity( + article_id, revision, expected_sha256 + ) + # Validates approval, public source digests, and public attachments. + self.build_public_artifact( + article_id, revision, expected_sha256, snapshots + ) + with self.engine.begin() as conn: + self._article( + conn, article_id, expected_revision=revision, lock=True + ) + if not self._approved(conn, article_id, revision, expected_sha256): + raise Conflict("approval") + existing = conn.execute( + select(approved_source_snapshots).where( + approved_source_snapshots.c.article_id == article_id, + approved_source_snapshots.c.revision == revision, + ) + ).mappings().first() + if existing is not None: + if ( + existing["revision_sha256"] != expected_sha256 + or canonical_bytes(existing["snapshots"]) + != canonical_bytes(snapshots) + ): + raise Conflict("source_snapshots") + return True + if not self._approved(conn, article_id, revision, expected_sha256): + raise Conflict("approval") + conn.execute( + approved_source_snapshots.insert().values( + article_id=article_id, + revision=revision, + revision_sha256=expected_sha256, + snapshots=snapshots, + created_at=utcnow(), + ) + ) + return True + + def get_source_snapshots(self, article_id, revision, expected_sha256): + article_id, revision, expected_sha256 = self._snapshot_identity( + article_id, revision, expected_sha256 + ) + with self.engine.connect() as conn: + if not self._approved(conn, article_id, revision, expected_sha256): + raise Conflict("approval") + row = conn.execute( + select(approved_source_snapshots.c.snapshots).where( + approved_source_snapshots.c.article_id == article_id, + approved_source_snapshots.c.revision == revision, + approved_source_snapshots.c.revision_sha256 == expected_sha256, + ) + ).mappings().first() + if row is None: + raise Conflict("source_snapshots") + return copy.deepcopy(row["snapshots"]) diff --git a/townlight_comms/store.py b/townlight_comms/store.py new file mode 100644 index 0000000..1ead070 --- /dev/null +++ b/townlight_comms/store.py @@ -0,0 +1,345 @@ +from __future__ import annotations + +import hashlib +import json +import re +import uuid +from datetime import UTC, datetime +from pathlib import PureWindowsPath +from uuid import UUID + +from sqlalchemy import inspect, select +from sqlalchemy.schema import CreateSchema + +from .models import ( + SCHEMA, + SOURCE_KINDS, + articles, + events, + metadata, + publications, + revisions, +) + +_HEX64 = re.compile(r"^[0-9a-f]{64}$") +_SOURCE_KEYS = {"kind", "id", "revision", "title", "url", "sha256", "eligible"} +_ATTACHMENT_KEYS = {"id", "name", "media_type", "size", "sha256", "public"} +_WINDOWS_RESERVED = { + "CON", + "PRN", + "AUX", + "NUL", + "COM1", + "COM2", + "COM3", + "COM4", + "COM5", + "COM6", + "COM7", + "COM8", + "COM9", + "LPT1", + "LPT2", + "LPT3", + "LPT4", + "LPT5", + "LPT6", + "LPT7", + "LPT8", + "LPT9", +} +_MAX_ATTACHMENT_SIZE = 10 * 1024 * 1024 +_MAX_ATTACHMENTS_TOTAL = 20 * 1024 * 1024 + + +class InvalidInput(ValueError): + pass + + +class Conflict(RuntimeError): + pass + + +class NotFound(LookupError): + pass + + +class Unauthorized(PermissionError): + pass + + +def utcnow(): + return datetime.now(UTC) + + +def new_id(): + return str(uuid.uuid4()) + + +def canonical_bytes(value): + return json.dumps( + value, sort_keys=True, separators=(",", ":"), ensure_ascii=False + ).encode("utf-8") + + +def digest(value): + return hashlib.sha256(value).hexdigest() + + +class RepositoryBase: + def __init__(self, engine, bootstrap=False): + if engine.dialect.name == "sqlite": + self.engine = engine.execution_options( + schema_translate_map={SCHEMA: None} + ) + else: + self.engine = engine + self.schema = None if engine.dialect.name == "sqlite" else SCHEMA + if bootstrap: + if self.schema: + with self.engine.begin() as conn: + conn.execute(CreateSchema(self.schema, if_not_exists=True)) + metadata.create_all(self.engine) + else: + inspector = inspect(self.engine) + for table in metadata.sorted_tables: + if not inspector.has_table(table.name, schema=self.schema): + raise RuntimeError(f"missing table: {table.name}") + + @staticmethod + def _dict(row): + return None if row is None else dict(row._mapping) + + def _article(self, conn, article_id, expected_revision=None, lock=False): + stmt = select(articles).where(articles.c.id == article_id) + if lock: + stmt = stmt.with_for_update() + row = conn.execute(stmt).mappings().first() + if row is None: + raise NotFound(article_id) + if expected_revision is not None: + current = row.get("current_revision") + if current is None: + current = row.get("revision") + if current != expected_revision: + raise Conflict("revision mismatch") + return dict(row) + + def _revision(self, conn, article_id, revision=None): + stmt = select(revisions).where(revisions.c.article_id == article_id) + if revision is None: + stmt = stmt.order_by(revisions.c.revision.desc()) + else: + stmt = stmt.where(revisions.c.revision == revision) + row = conn.execute(stmt.limit(1)).mappings().first() + if row is None: + raise NotFound(f"revision {revision}") + return dict(row) + + def _event(self, conn, article_id, revision, kind, actor, payload): + conn.execute( + events.insert().values( + article_id=article_id, + revision=revision, + kind=kind, + actor=actor, + payload=payload, + created_at=utcnow(), + ) + ) + + @staticmethod + def _bounded(value, name, maximum): + if not isinstance(value, str) or not value or len(value) > maximum: + raise InvalidInput(name) + return value + + def _public_sources(self, refs): + if not isinstance(refs, list) or not 0 <= len(refs) <= 50: + raise InvalidInput("sources") + result = [] + for source in refs: + if not isinstance(source, dict) or set(source) != _SOURCE_KEYS: + raise InvalidInput("source keys") + kind = source["kind"] + if kind not in SOURCE_KINDS: + raise InvalidInput("source kind") + item = { + "kind": kind, + "id": self._bounded(source["id"], "source id", 256), + "revision": self._bounded(source["revision"], "source revision", 256), + "title": self._bounded(source["title"], "source title", 512), + "url": self._bounded(source["url"], "source url", 2048), + "sha256": source["sha256"], + "eligible": source["eligible"], + } + url = item["url"] + if not ( + url.startswith("https://") + or (url.startswith("/") and not url.startswith("//")) + ): + raise InvalidInput("source url") + if not isinstance(item["sha256"], str) or not _HEX64.fullmatch(item["sha256"]): + raise InvalidInput("source sha256") + if item["eligible"] is not True: + raise InvalidInput("source eligible") + result.append(item) + return result + + @staticmethod + def _attachment_name(value): + if not isinstance(value, str) or not value or len(value) > 150: + raise InvalidInput("attachment name") + if any(ch in '<>:"/\\|?*' or ord(ch) < 32 for ch in value): + raise InvalidInput("attachment name") + if value in {".", ".."} or value.endswith((" ", ".")): + raise InvalidInput("attachment name") + if PureWindowsPath(value).name != value: + raise InvalidInput("attachment name") + if value.split(".", 1)[0].upper() in _WINDOWS_RESERVED: + raise InvalidInput("attachment name") + return value + + def _attachment_refs(self, refs): + if refs is None: + return [] + if not isinstance(refs, list) or len(refs) > 20: + raise InvalidInput("attachment_refs") + result = [] + seen = set() + total = 0 + for ref in refs: + if not isinstance(ref, dict) or set(ref) != _ATTACHMENT_KEYS: + raise InvalidInput("attachment_ref keys") + attachment_id = ref["id"] + if not isinstance(attachment_id, str): + raise InvalidInput("attachment id") + try: + UUID(attachment_id) + except (ValueError, AttributeError): + raise InvalidInput("attachment id") + if attachment_id in seen: + raise InvalidInput("attachment id") + seen.add(attachment_id) + name = self._attachment_name(ref["name"]) + media_type = self._bounded( + ref["media_type"], "attachment media_type", 128 + ) + size = ref["size"] + if ( + isinstance(size, bool) + or not isinstance(size, int) + or not 1 <= size <= _MAX_ATTACHMENT_SIZE + ): + raise InvalidInput("attachment size") + sha256 = ref["sha256"] + if not isinstance(sha256, str) or not _HEX64.fullmatch(sha256): + raise InvalidInput("attachment sha256") + public = ref["public"] + if not isinstance(public, bool): + raise InvalidInput("attachment public") + total += size + if total > _MAX_ATTACHMENTS_TOTAL: + raise InvalidInput("attachment total size") + result.append( + { + "id": attachment_id, + "name": name, + "media_type": media_type, + "size": size, + "sha256": sha256, + "public": public, + } + ) + return result + + def _content( + self, + title, + body, + language, + sources, + access_review=None, + translation_provenance=None, + attachment_refs=None, + ): + title = self._bounded(title, "title", 512) + if not isinstance(body, str) or not body.strip() or len(body) > 100000: + raise InvalidInput("body") + language = self._bounded(language, "language", 16) + source_refs = self._public_sources(sources) + access_review = {} if access_review is None else access_review + translation_provenance = ( + {} if translation_provenance is None else translation_provenance + ) + if not isinstance(access_review, dict) or not isinstance( + translation_provenance, dict + ): + raise InvalidInput("content metadata") + if len(canonical_bytes(access_review)) > 100000: + raise InvalidInput("access review") + if len(canonical_bytes(translation_provenance)) > 100000: + raise InvalidInput("translation provenance") + attachment_refs = self._attachment_refs(attachment_refs) + content = { + "title": title, + "body": body, + "language": language, + "source_refs": source_refs, + "access_review": access_review, + "translation_provenance": translation_provenance, + "attachment_refs": attachment_refs, + } + content["sha256"] = digest(canonical_bytes(content)) + return content + + def get(self, article_id): + with self.engine.connect() as conn: + article = self._article(conn, article_id) + current = article.get("current_revision") + if current is None: + current = article.get("revision") + try: + revision = self._revision(conn, article_id, current) + except NotFound: + revision = None + history = [ + dict(row._mapping) + for row in conn.execute( + select(publications) + .where(publications.c.article_id == article_id) + .order_by(publications.c.created_at) + ) + ] + event_rows = [ + dict(row._mapping) + for row in conn.execute( + select(events) + .where(events.c.article_id == article_id) + .order_by(events.c.created_at) + ) + ] + article["revision"] = revision + article["history"] = history + article["events"] = event_rows + return article + + def list_articles(self, state=None, limit=50, offset=0): + if ( + isinstance(limit, bool) + or not isinstance(limit, int) + or not 1 <= limit <= 200 + ): + raise InvalidInput("limit") + if ( + isinstance(offset, bool) + or not isinstance(offset, int) + or not 0 <= offset <= 100000 + ): + raise InvalidInput("offset") + stmt = select(articles) + if state is not None: + stmt = stmt.where(articles.c.state == state) + stmt = stmt.order_by(articles.c.id).limit(limit).offset(offset) + with self.engine.connect() as conn: + return [dict(row._mapping) for row in conn.execute(stmt)] diff --git a/townlight_comms/subscription_apply.py b/townlight_comms/subscription_apply.py new file mode 100644 index 0000000..99543f0 --- /dev/null +++ b/townlight_comms/subscription_apply.py @@ -0,0 +1,224 @@ +"""Apply subscription commands inside a caller-owned transaction.""" + +from __future__ import annotations + +import ipaddress +import json +import re +import secrets +from urllib.parse import urlsplit + +from cryptography.fernet import Fernet +from sqlalchemy import select + +from .models import subscribers +from .store import InvalidInput, Unauthorized, new_id, utcnow +from .subscription_models import subscription_mail, subscription_preferences_keys +from .subscriptions import _email, _hash, _language, _topics + +_TOKEN = re.compile(r"^[A-Za-z0-9_-]{32,128}$") + + +def _shape(payload, required, optional=()): + if not isinstance(payload, dict): + raise InvalidInput("payload") + keys = set(payload) + if not set(required) <= keys or not keys <= set(required) | set(optional): + raise InvalidInput("payload keys") + + +def _token(payload): + token = payload["token"] + if not isinstance(token, str) or not _TOKEN.fullmatch(token): + raise Unauthorized("invalid token") + return token + + +def _origin(public_origin): + if not isinstance(public_origin, str) or not public_origin: + raise InvalidInput("public_origin") + parts = urlsplit(public_origin) + if ( + parts.scheme not in {"http", "https"} + or not parts.netloc + or parts.username is not None + or parts.password is not None + or parts.query + or parts.fragment + or parts.path not in {"", "/"} + or parts.hostname is None + ): + raise InvalidInput("public_origin") + try: + _ = parts.port + except ValueError: + raise InvalidInput("public_origin") from None + if parts.scheme == "http" and parts.hostname != "localhost": + try: + if not ipaddress.ip_address(parts.hostname).is_loopback: + raise InvalidInput("public_origin") + except ValueError: + raise InvalidInput("public_origin") from None + return public_origin.rstrip("/") + + +def _subscribe(conn, payload, key, public_origin): + _shape(payload, {"email", "topics"}, {"language"}) + address = _email(payload["email"]) + selected = _topics(payload["topics"]) + language = _language(payload.get("language", "en")) + address_hash = _hash(address) + found = conn.execute( + select(subscribers.c.id).where(subscribers.c.address_hash == address_hash) + ).first() + if found is not None: + return {"accepted": True} + + origin = _origin(public_origin) + management_token = secrets.token_urlsafe(32) + confirmation_token = secrets.token_urlsafe(32) + now = utcnow() + values = { + "id": new_id(), + "email": address, + "address_hash": address_hash, + "token_hash": _hash(management_token), + "topics": selected, + "language": language, + "active": False, + "confirmed": False, + "confirmation_hash": _hash(confirmation_token), + "created_at": now, + "updated_at": now, + } + conn.execute(subscribers.insert().values(**values)) + encrypted_management_token = Fernet(key).encrypt( + management_token.encode('ascii') + ).decode('ascii') + conn.execute( + subscription_preferences_keys.insert().values( + subscriber_id=values['id'], + encrypted_token=encrypted_management_token, + ) + ) + + confirm_url = f"{origin}/communications/confirm/?token={confirmation_token}" + preferences_url = ( + f"{origin}/communications/preferences/?token={management_token}" + ) + message = { + "subject": "Confirm your subscription", + "body": ( + "Confirm your Townlight subscription:\n" + f"{confirm_url}\n\n" + "Manage your preferences:\n" + f"{preferences_url}\n" + ), + } + encrypted_body = Fernet(key).encrypt( + json.dumps(message, ensure_ascii=False).encode("utf-8") + ).decode("ascii") + conn.execute( + subscription_mail.insert().values( + id=new_id(), + subscriber_id=values["id"], + encrypted_body=encrypted_body, + recipient=address, + message_id=f"{new_id()}@townlight.local", + state="pending", + claim_token=None, + lease_until=None, + attempts=0, + next_attempt_at=now, + last_error=None, + created_at=now, + ) + ) + return {"accepted": True} + + +def _confirm(conn, payload): + _shape(payload, {"token"}) + token_hash = _hash(_token(payload)) + row = conn.execute( + select(subscribers.c.id) + .where(subscribers.c.confirmation_hash == token_hash) + .with_for_update() + ).first() + if row is None: + raise Unauthorized("invalid token") + conn.execute( + subscribers.update() + .where(subscribers.c.id == row.id) + .values( + confirmed=True, + active=True, + confirmation_hash=None, + updated_at=utcnow(), + ) + ) + return {"confirmed": True} + + +def _preferences(conn, payload): + _shape(payload, {"token"}, {"topics", "language", "active"}) + token_hash = _hash(_token(payload)) + row = conn.execute( + select( + subscribers.c.id, + subscribers.c.topics, + subscribers.c.language, + subscribers.c.active, + subscribers.c.confirmed, + ) + .where(subscribers.c.token_hash == token_hash) + .with_for_update() + ).first() + if row is None or not row.confirmed: + raise Unauthorized("invalid token") + + updates = {} + if "topics" in payload: + updates["topics"] = _topics(payload["topics"]) + if "language" in payload: + updates["language"] = _language(payload["language"]) + if "active" in payload: + if not isinstance(payload["active"], bool): + raise InvalidInput("invalid active") + updates["active"] = payload["active"] + if updates: + updates["updated_at"] = utcnow() + conn.execute( + subscribers.update() + .where(subscribers.c.id == row.id) + .values(**updates) + ) + + current = conn.execute( + select( + subscribers.c.topics, + subscribers.c.language, + subscribers.c.active, + ).where(subscribers.c.id == row.id) + ).first() + if current is None: + raise Unauthorized("invalid token") + return { + "topics": list(current.topics), + "language": current.language, + "active": current.active, + } + + +def apply_subscription(conn, operation, payload, *, key, public_origin): + """Apply one explicit subscription command using the supplied connection.""" + if operation == "comms_subscribe": + return _subscribe(conn, payload, key, public_origin) + if operation == "comms_confirm": + return _confirm(conn, payload) + if operation == "comms_preferences": + return _preferences(conn, payload) + raise InvalidInput("operation") + + +__all__ = ["apply_subscription"] diff --git a/townlight_comms/subscription_commands.py b/townlight_comms/subscription_commands.py new file mode 100644 index 0000000..bf289a3 --- /dev/null +++ b/townlight_comms/subscription_commands.py @@ -0,0 +1,98 @@ +"""Idempotent subscription command execution with receipts.""" + +from __future__ import annotations + +import copy +import hashlib +import json +from uuid import UUID + +from sqlalchemy import select + +from .store import Conflict, InvalidInput, utcnow +from .subscription_apply import apply_subscription +from .subscription_models import subscription_commands + +_OPERATIONS = {"comms_subscribe", "comms_confirm", "comms_preferences"} +_MAX_PAYLOAD = 16 * 1024 + + +class SubscriptionCommandMixin: + """Mixin exposing ``execute_subscription_command``.""" + + def execute_subscription_command( + self, command_id, operation, payload, *, key, public_origin + ): + # Canonical UUID: require the canonical lowercase hyphenated form. + try: + canonical_id = str(UUID(command_id)) + except (ValueError, AttributeError, TypeError): + raise InvalidInput("command_id") + if canonical_id != command_id: + raise InvalidInput("command_id") + + if operation not in _OPERATIONS: + raise InvalidInput("operation") + + if not isinstance(payload, dict): + raise InvalidInput("payload") + try: + encoded = json.dumps( + payload, + sort_keys=True, + separators=(",", ":"), + ensure_ascii=False, + allow_nan=False, + ).encode("utf-8") + except (TypeError, ValueError): + raise InvalidInput("payload") + if len(encoded) > _MAX_PAYLOAD: + raise InvalidInput("payload") + payload_hash = hashlib.sha256(encoded).hexdigest() + + with self.engine.begin() as conn: + if conn.dialect.name == "postgresql": + signed = int.from_bytes( + hashlib.sha256( + f"subscription:{canonical_id}".encode() + ).digest()[:8], + "big", + signed=True, + ) + conn.exec_driver_sql( + "SELECT pg_advisory_xact_lock(%s)", (signed,) + ) + + row = conn.execute( + select(subscription_commands).where( + subscription_commands.c.command_id == canonical_id + ) + ).mappings().first() + if row is not None: + if ( + row["operation"] == operation + and row["payload_sha256"] == payload_hash + ): + return copy.deepcopy(row["result"]) + raise Conflict("command id reused") + + result = apply_subscription( + conn, + operation, + payload, + key=key, + public_origin=public_origin, + ) + conn.execute( + subscription_commands.insert().values( + command_id=canonical_id, + operation=operation, + payload_sha256=payload_hash, + result=result, + created_at=utcnow(), + ) + ) + return copy.deepcopy(result) + + +__all__ = ["SubscriptionCommandMixin"] diff --git a/townlight_comms/subscription_delivery.py b/townlight_comms/subscription_delivery.py new file mode 100644 index 0000000..e8a3810 --- /dev/null +++ b/townlight_comms/subscription_delivery.py @@ -0,0 +1,115 @@ +from __future__ import annotations + +import json +from datetime import UTC, datetime, timedelta + +from cryptography.fernet import Fernet, InvalidToken +from sqlalchemy import and_, select, update + +from .store import InvalidInput, new_id, utcnow +from .subscription_models import subscription_mail + +_MAX_ATTEMPTS = 5 +_MAX_BACKOFF = 3600 +_EXPIRED = "lease expired" +_RETRY = "delivery retry scheduled" +_FAILED = "delivery failed" +_UNCERTAIN = "delivery outcome uncertain" + + +def _utc(value): + if value is None: + return utcnow() + if not isinstance(value, datetime): + raise InvalidInput("now") + if value.tzinfo is None: + return value.replace(tzinfo=UTC) + return value.astimezone(UTC) + + +class SubscriptionDeliveryMixin: + def claim_subscription_email(self, *, key, now=None, lease_seconds=120): + if isinstance(lease_seconds, bool) or not isinstance(lease_seconds, int) or not 30 <= lease_seconds <= 600: + raise InvalidInput("lease_seconds") + if not isinstance(key, (bytes, str)) or not key: + raise InvalidInput("key") + now = _utc(now) + lease_until = now + timedelta(seconds=lease_seconds) + with self.engine.begin() as conn: + conn.execute(update(subscription_mail).where( + and_(subscription_mail.c.state == "claimed", + subscription_mail.c.lease_until.is_not(None), + subscription_mail.c.lease_until <= now) + ).values(state="uncertain", last_error=_EXPIRED, claim_token=None, + lease_until=None, next_attempt_at=now)) + stmt = (select(subscription_mail.c.id, subscription_mail.c.encrypted_body, + subscription_mail.c.recipient, subscription_mail.c.message_id) + .where(and_(subscription_mail.c.state == "pending", + subscription_mail.c.next_attempt_at <= now)) + .order_by(subscription_mail.c.next_attempt_at, + subscription_mail.c.created_at) + .limit(1) + .with_for_update(skip_locked=True, of=subscription_mail)) + row = conn.execute(stmt).mappings().first() + if row is None: + return None + token = new_id() + result = conn.execute(update(subscription_mail).where(and_( + subscription_mail.c.id == row["id"], + subscription_mail.c.state == "pending", + )).values(state="claimed", claim_token=token, lease_until=lease_until, + next_attempt_at=now, last_error=None, + attempts=subscription_mail.c.attempts + 1)) + if result.rowcount != 1: + return None + claimed = dict(row) + try: + payload = json.loads(Fernet(key).decrypt( + claimed["encrypted_body"].encode("utf-8") + ).decode("utf-8")) + subject, body = payload["subject"], payload["body"] + if not isinstance(subject, str) or not isinstance(body, str): + raise TypeError + except (InvalidToken, UnicodeDecodeError, json.JSONDecodeError, TypeError, ValueError): + self.finish_subscription_email(claimed["id"], token, "failed", now=now) + raise InvalidInput("subscription mail payload") from None + return {"id": claimed["id"], "claim_token": token, "recipient": claimed["recipient"], + "message_id": claimed["message_id"], "subject": subject, "body": body} + + def finish_subscription_email(self, id, claim_token, outcome, now=None): + if not isinstance(id, str) or not id: + raise InvalidInput("id") + if not isinstance(claim_token, str) or not claim_token: + raise InvalidInput("claim_token") + if outcome not in ("sent", "retry", "failed", "uncertain"): + raise InvalidInput("outcome") + now = _utc(now) + values = {"claim_token": None, "lease_until": None, "next_attempt_at": now} + with self.engine.begin() as conn: + if outcome == "retry": + row = conn.execute(select(subscription_mail.c.attempts).where(and_( + subscription_mail.c.id == id, + subscription_mail.c.state == "claimed", + subscription_mail.c.claim_token == claim_token, + )).limit(1)).mappings().first() + if row is None: + return False + if row["attempts"] >= _MAX_ATTEMPTS: + values.update(state="failed", last_error=_FAILED) + else: + delay = min(_MAX_BACKOFF, 2 ** min(row["attempts"], 12)) + values.update(state="pending", + next_attempt_at=now + timedelta(seconds=delay), + last_error=_RETRY) + elif outcome == "sent": + values.update(state="sent", last_error=None) + elif outcome == "failed": + values.update(state="failed", last_error=_FAILED) + else: + values.update(state="uncertain", last_error=_UNCERTAIN) + result = conn.execute(update(subscription_mail).where(and_( + subscription_mail.c.id == id, + subscription_mail.c.state == "claimed", + subscription_mail.c.claim_token == claim_token, + )).values(**values)) + return result.rowcount == 1 diff --git a/townlight_comms/subscription_models.py b/townlight_comms/subscription_models.py new file mode 100644 index 0000000..81cfbed --- /dev/null +++ b/townlight_comms/subscription_models.py @@ -0,0 +1,89 @@ +"""Durable subscription command and encrypted-mail tables. + +Uses the shared ``townlight_comms`` metadata/SCHEMA from :mod:`townlight_comms.models`. +Mail bodies are stored only as Fernet ciphertext containing subject, body and tokens. +""" + +from __future__ import annotations + +from sqlalchemy import ( + JSON, + CheckConstraint, + Column, + DateTime, + ForeignKey, + Index, + Integer, + String, + Table, + Text, + text, +) + +from .models import SCHEMA, metadata, subscribers + +MAIL_STATES = ("pending", "claimed", "sent", "failed", "uncertain") +_STATE_CHECK = "state IN ('pending', 'claimed', 'sent', 'failed', 'uncertain')" + +subscription_commands = Table( + "subscription_commands", + metadata, + Column("command_id", String(36), primary_key=True), + Column("operation", String(32), nullable=False), + Column("payload_sha256", String(64), nullable=False), + Column("result", JSON, nullable=True), + Column("created_at", DateTime(timezone=True), nullable=False), + Index("ix_subscription_commands_created", "created_at"), +) + +subscription_mail = Table( + "subscription_mail", + metadata, + Column("id", String(36), primary_key=True), + Column( + "subscriber_id", + String(36), + ForeignKey(subscribers.c.id, ondelete="CASCADE", name="fk_subscription_mail_subscriber"), + nullable=False, + ), + # Fernet ciphertext only: subject, body and all tokens remain encrypted. + Column("encrypted_body", Text, nullable=False), + Column("recipient", String(320), nullable=False), + Column("message_id", String(255), nullable=False, unique=True), + Column("state", String(16), nullable=False), + Column("claim_token", String(36), nullable=True), + Column("lease_until", DateTime(timezone=True), nullable=True), + Column("attempts", Integer, nullable=False, default=0, server_default=text("0")), + Column("next_attempt_at", DateTime(timezone=True), nullable=False), + Column("last_error", String(64), nullable=True), + Column("created_at", DateTime(timezone=True), nullable=False), + CheckConstraint(_STATE_CHECK, name="ck_subscription_mail_state"), + CheckConstraint("attempts >= 0", name="ck_subscription_mail_attempts_nonnegative"), + Index("ix_subscription_mail_due", "state", "next_attempt_at"), + Index("ix_subscription_mail_lease", "state", "lease_until"), + Index("ix_subscription_mail_subscriber", "subscriber_id"), +) + +subscription_preferences_keys = Table( + 'subscription_preferences_keys', + metadata, + Column( + 'subscriber_id', + String(36), + ForeignKey( + subscribers.c.id, + ondelete='CASCADE', + name='fk_subscription_preferences_keys_subscriber', + ), + primary_key=True, + ), + Column('encrypted_token', Text, nullable=False), +) + +__all__ = [ + "MAIL_STATES", + "SCHEMA", + "metadata", + "subscription_commands", + "subscription_mail", +] diff --git a/townlight_comms/subscriptions.py b/townlight_comms/subscriptions.py new file mode 100644 index 0000000..52a1bf2 --- /dev/null +++ b/townlight_comms/subscriptions.py @@ -0,0 +1,119 @@ +import hashlib +import secrets +from email.utils import parseaddr + +from sqlalchemy import select +from sqlalchemy.exc import IntegrityError + +from .models import subscribers +from .store import InvalidInput, Unauthorized, new_id, utcnow + +_ALLOWED = frozenset({"all", "meetings", "code", "notice", "311", "parks"}) +_COLS = (subscribers.c.id, subscribers.c.topics, + subscribers.c.language, subscribers.c.active, subscribers.c.confirmed) + + +def _hash(value): + return hashlib.sha256(value.encode("utf-8")).hexdigest() + + +def _email(value): + if not isinstance(value, str): + raise InvalidInput("invalid email") + addr = value.strip() + if not addr or "\r" in addr or "\n" in addr: + raise InvalidInput("invalid email") + name, parsed = parseaddr(addr) + local, _, domain = parsed.rpartition("@") + if name or not local or not domain or "." not in domain or parsed != addr: + raise InvalidInput("invalid email") + return addr.lower() + + +def _topics(value): + if not isinstance(value, (list, tuple, set)): + raise InvalidInput("invalid topics") + items = list(value) + if not items or len(items) > 6 or len(set(items)) != len(items): + raise InvalidInput("invalid topics") + if any(not isinstance(t, str) or t not in _ALLOWED for t in items): + raise InvalidInput("invalid topics") + return items + + +def _language(value): + if not isinstance(value, str) or not value or len(value) > 16: + raise InvalidInput("invalid language") + return value + + +class SubscriptionMixin: + def request_subscription(self, email, topics, language="en"): + address = _email(email) + selected = _topics(topics) + language = _language(language) + address_hash = _hash(address) + generic = {"accepted": True} + try: + with self.engine.begin() as conn: + found = conn.execute(select(subscribers.c.id).where( + subscribers.c.address_hash == address_hash)).first() + if found: + return generic + management_token = secrets.token_urlsafe(32) + confirmation_token = secrets.token_urlsafe(32) + now = utcnow() + values = {"id": new_id(), "email": address, + "address_hash": address_hash, + "token_hash": _hash(management_token), + "topics": selected, "language": language, + "active": False, "confirmed": False, + "confirmation_hash": _hash(confirmation_token), + "created_at": now, "updated_at": now} + conn.execute(subscribers.insert().values(**values)) + except IntegrityError: + return generic + return {"accepted": True, "id": values["id"], + "management_token": management_token, + "confirmation_token": confirmation_token} + + def confirm_subscription(self, token): + if not isinstance(token, str) or not token: + raise Unauthorized("invalid token") + with self.engine.begin() as conn: + row = conn.execute(select(subscribers.c.id).where( + subscribers.c.confirmation_hash == _hash(token))).first() + if not row: + raise Unauthorized("invalid token") + conn.execute(subscribers.update().where( + subscribers.c.id == row.id).values(confirmed=True, active=True, + confirmation_hash=None, updated_at=utcnow())) + return {"confirmed": True} + + def preferences(self, token, topics=None, language=None, active=None): + if not isinstance(token, str) or not token: + raise Unauthorized("invalid token") + with self.engine.begin() as conn: + row = conn.execute(select(*_COLS).where( + subscribers.c.token_hash == _hash(token))).first() + if not row or not row.confirmed: + raise Unauthorized("invalid token") + updates = {} + if topics is not None: + updates["topics"] = _topics(topics) + if language is not None: + updates["language"] = _language(language) + if active is not None: + if not isinstance(active, bool): + raise InvalidInput("invalid active") + updates["active"] = active + if updates: + updates["updated_at"] = utcnow() + conn.execute(subscribers.update().where( + subscribers.c.id == row.id).values(**updates)) + current = conn.execute(select(*_COLS).where( + subscribers.c.id == row.id)).first() + if not current: + raise Unauthorized("invalid token") + return {"id": current.id, "topics": list(current.topics), + "language": current.language, "active": current.active} diff --git a/townlight_comms/workflow.py b/townlight_comms/workflow.py new file mode 100644 index 0000000..a9404c0 --- /dev/null +++ b/townlight_comms/workflow.py @@ -0,0 +1,58 @@ +"""Composed communications repository.""" + +from __future__ import annotations + +from .approval import ApprovalMixin +from .attachments import AttachmentMixin +from .editorial import EditorialMixin +from .email_claims import EmailClaimsMixin +from .email_enqueue import EmailEnqueueMixin +from .public_artifact import ArtifactMixin +from .publication_claims import PublicationClaimsMixin +from .publication_reconciliation import PublicationReconciliationMixin +from .publication_results import PublicationResultsMixin +from .records_archive import RecordsArchiveMixin +from .records_guard import RecordsGuardMixin +from .scheduling import SchedulingMixin +from .source_snapshots import SourceSnapshotMixin +from .store import Conflict, InvalidInput, NotFound, RepositoryBase, Unauthorized +from .subscription_commands import SubscriptionCommandMixin +from .subscription_delivery import SubscriptionDeliveryMixin +from .subscriptions import SubscriptionMixin + + +class CommunicationsRepository( + EditorialMixin, + ApprovalMixin, + SchedulingMixin, + SubscriptionMixin, + SubscriptionCommandMixin, + SubscriptionDeliveryMixin, + PublicationClaimsMixin, + PublicationResultsMixin, + PublicationReconciliationMixin, + EmailEnqueueMixin, + EmailClaimsMixin, + AttachmentMixin, + ArtifactMixin, + SourceSnapshotMixin, + RecordsArchiveMixin, + RecordsGuardMixin, + RepositoryBase, +): + pass + + +__all__ = [ + "ApprovalMixin", + "CommunicationsRepository", + "Conflict", + "EditorialMixin", + "EmailClaimsMixin", + "EmailEnqueueMixin", + "InvalidInput", + "NotFound", + "RepositoryBase", + "SourceSnapshotMixin", + "Unauthorized", +]