Skip to content

Add admin notify --user for per-user emails - #461

Merged
neuromechanist merged 6 commits into
devfrom
feature/issue-381-notify-user
May 14, 2026
Merged

neuromechanist merged 6 commits into
devfrom
feature/issue-381-notify-user

Conversation

@neuromechanist

Copy link
Copy Markdown
Contributor

Closes #381.

Summary

  • nemar admin notify learns a new --user <username> flag for sending
    transactional emails to a single approved user. --to and --user are
    mutually exclusive; exactly one must be supplied.
  • POST /admin/notify accepts an alternate user payload field; the
    request schema's refinement enforces the same exclusivity at the API
    boundary.
  • New service helper getBroadcastRecipientByUsername() returns a
    structured { ok, email, user_id, username, error } result so the
    route maps clean error codes:
    • unknown username -> 404
    • unapproved or missing email -> 400
  • Per-user sends ignore the announcements email preference (these are
    direct admin contact, not broadcasts).
  • Audit log: recipient_group records user:<username> for per-user
    sends so the group/transactional distinction is queryable later. A new
    migration (0021_broadcast_user_recipient.sql) rebuilds the
    broadcast_emails table so its CHECK constraint accepts both the
    existing enum values (all/admins/members) and the new
    user:<username> form. Existing rows migrate verbatim.

Notes / decisions

  • The broadcast service's recipient list still flows as string[] of
    email addresses; the issue mentioned returning recipient objects with
    {user_id, email, ...}, but the only consumer is sendBroadcast(),
    which doesn't need the user_id. Per-user metadata is captured
    upstream via the audit recipient_group: user:<username> field, so
    this keeps the existing API surface minimal.
  • The CLI's --dry-run works with --user: shows a single recipient
    and the user:<username> label.

Test plan

@github-actions

github-actions Bot commented May 14, 2026 •

Copy link
Copy Markdown

📦 Package Preview

Your package is ready to test!

bun install -g nemar-cli@PR461

Version: 0.8.14-PR461.6fe0031
Commit: 6fe0031


🤖 Updated on each push.

@neuromechanist

Copy link
Copy Markdown
Contributor Author

Code Review — PR #461 (admin notify --user)

Reviewed: backend migration, broadcast service, admin routes, CLI command, api.ts, and test file.


Critical

C1. Migration has no explicit transaction — risk of partial table rebuild
backend/src/db/migrations/0021_broadcast_user_recipient.sql lines 11-45

The rebuild sequence is: CREATE new, INSERT SELECT, DROP old, RENAME new. If the INSERT INTO broadcast_emails_new … SELECT fails mid-way (e.g., a row violates the new CHECK, or a transient D1 error), the script has already created the new empty table and will not automatically roll back. The old table is still intact at that point, but if the failure happens after DROP TABLE broadcast_emails, the data is gone. Add an explicit BEGIN; … COMMIT; wrapper so D1 treats the whole rebuild as a single atomic operation. Every other migration in this project is safe because they're single-statement DDL; a multi-step rebuild is different.

C2. PRAGMA foreign_keys is untested territory in this project's D1 setup
backend/src/db/migrations/0021_broadcast_user_recipient.sql lines 13, 45

This is the first migration in the project to use PRAGMA foreign_keys = OFF/ON. Cloudflare D1's SQLite dialect accepts most PRAGMAs but some have restrictions in a serverless multi-tenant context (they can be silently no-ops or rejected between migration statements). The OFF is needed to allow DROP TABLE broadcast_emails while the sent_by FK to users exists — if it silently fails to disable FK enforcement and broadcast_emails has rows referencing users that no longer exist (unlikely but possible), the DROP could be blocked. Validate this against wrangler d1 migrations apply --local and document the test result before merging.


Important

I1. SingleUserLookupResult is not a discriminated union — forces unsafe as string casts
backend/src/services/broadcast.ts lines 37-43; backend/src/routes/admin.ts lines 5243, 5257

The current interface:

export interface SingleUserLookupResult {
  ok: boolean;
  email?: string;
  user_id?: number;
  username?: string;
  error?: SingleUserLookupError;
}

TypeScript can't narrow email to string from ok === true, so the route must write lookup.email as string. A discriminated union eliminates the cast and makes the contract self-documenting:

export type SingleUserLookupResult =
  | { ok: true; email: string; user_id: number; username: string }
  | { ok: false; error: SingleUserLookupError; user_id?: number; username?: string };

I2. unsubscribed error variant is defined but never returned — dead type
backend/src/services/broadcast.ts line 34

SingleUserLookupError includes "unsubscribed" but getBroadcastRecipientByUsername never returns it (and per the PR description, per-user sends intentionally ignore the announcements preference). Either remove "unsubscribed" from the type, or add a comment explaining that it is reserved for a future preference check. The PR description says preference is intentionally ignored; the type should agree.

I3. user field max length in broadcastRequestSchema (64) mismatches signup max (30)
backend/src/services/broadcast.ts line 22

broadcastRequestSchema allows user: z.string().min(1).max(64) but the signup schema enforces username: z.string().max(30). A username longer than 30 characters can never exist in the database, so the Zod validation will always produce a 404 for values 31–64 characters long. Align the max to 30 to surface a cleaner 400 at the schema layer rather than a confusing 404.


Suggestions

S1. user field in broadcastRequestSchema should add the signup regex
backend/src/services/broadcast.ts line 22

Signup enforces /^[a-zA-Z0-9_-]+$/ on usernames. The broadcastRequestSchema does not. Inputs like "alice:attacker" or "alice\n" pass schema validation and reach the DB lookup (which returns a safe 404 since the username won't match). Adding the regex here produces a schema-level 400 with a descriptive message instead of a DB round-trip 404, and also ensures the resulting user:<username> audit string can never contain unexpected characters even if future code paths are added.

S2. resolveEmailConfig is called in both branches — hoist before the if
backend/src/routes/admin.ts lines 5247 and 5283

Both the per-user and the group paths call const { fromEmail, replyTo, isDev } = resolveEmailConfig(c.env); identically. The function is pure (reads from c.env), so hoisting it above the if (body.user) block removes the duplication and makes both paths' structure parallel.


Nice-to-haves

N1. getBroadcastRecipientByUsername has no unit-test coverage for its three error paths
backend/src/services/broadcast.ts lines 115-132; test/broadcast.test.ts

The new schema tests are good and mock-free. The getBroadcastRecipientByUsername function's not_found / not_approved / no_email branches are not tested. Given the no-mock rule, this requires either the E2E test or a real D1 binding in tests. Consider at minimum noting in the test file that coverage lives in the E2E test, and ensure the E2E test exercises the 404/400 responses (e.g., try --user nonexistent-user in the --dry-run path).


False positives (skipped)

  • XOR logic in broadcastRequestSchema: Boolean(value.to) !== Boolean(value.user) is correct XOR — rejects both-present and neither-present, accepts exactly one. Not a bug.
  • Test file imports mock-free schema: The new broadcastRequestSchema tests exercise pure Zod parsing with no DB or network calls. This is real behavior, not a mock. Consistent with project policy.
  • Audit uses lookup.username not body.user: The route builds auditGroup = \user:${lookup.username}`` from the DB-canonical username, not from the user-supplied string. This is intentional and correct — the DB value is authoritative.
  • no_email empty-string guard: !row.email || !row.email.trim() correctly handles both null and whitespace-only strings. Not a bug.
  • Pre-existing osc.earth test failure: Acknowledged in PR as issue P1: 4 failing tests on dev — fix and add CI gate to prevent regression #452, unrelated to this change.

@neuromechanist

Copy link
Copy Markdown
Contributor Author

Round-2 fix pass — addressed all 5 findings from the review.

Finding Commit Notes
Critical 1: migration not transactional 5a2a033 Wrapped table rebuild in BEGIN;/COMMIT;
Critical 2: PRAGMA foreign_keys 5a2a033 Removed. Verified no FKs reference broadcast_emails, and the new table's FK to users(id) is satisfied by INSERTed rows (which were already valid under the same FK)
Important 1: discriminated union f55f79c + 8df6f6a SingleUserLookupResult is now {ok:true,...} / {ok:false,...}. Both as string casts in admin.ts dropped. Switch on lookup.error now exhaustive with a never assertion.
Important 2: dead "unsubscribed" variant f55f79c Removed from union. Doc-comment already says per-user sends ignore announcement prefs, so the variant was unreachable.
Important 3: user field length aa21f74 z.string().min(1).max(64) → min(3).max(30) to match auth.ts signup constraint (length < 3 || length > 30).

Tests: backend/test/broadcast.test.ts — 20/21 pass (the 1 failure is the pre-existing osc.earth assertion tracked in #452, fixed in PR #465). Typecheck clean.

This branch was previously deployed

1 inactive deployment
npm — 6fe00317 Deployed May 14, 2026 by neuromechanist via publish #821
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant