Skip to content

Release v0.5.2: bug fixes and dataset ID reuse - #146

Merged
neuromechanist merged 50 commits into
mainfrom
dev
Feb 14, 2026
Merged

neuromechanist merged 50 commits into
mainfrom
dev

Conversation

@neuromechanist

Copy link
Copy Markdown
Contributor

Summary

  • Reuse freed dataset IDs after deletion instead of monotonically incrementing (nm000108/109 deleted -> next dataset gets nm000108 instead of nm000110)
  • Fix regenerate-iam failing when D1 credentials are stale
  • Fix type error in migration for partial account objects
  • Fix gh switch failing in built binary
  • Harden migration check for empty accounts object
  • Fix gh not found when PATH is set in shell profile

Changes since last release (v0.5.1)

  • Dataset ID generation now queries for gaps in existing IDs using a recursive CTE
  • Multiple gh CLI integration fixes for multi-account switching
  • IAM credential regeneration fix

Test plan

  • All 409 tests pass (0 failures)
  • Build succeeds and reports correct version (0.5.2)
  • Verify dataset ID reuse after deletion in dev environment

* Add user roles migration (owner > admin > member)

Adds role column to users table, migrates existing is_admin data,
and sets initial owner/admin assignments for yahya, nemarOwner, nemarAdmin.

* Add UserRole type and role helpers

Adds UserRole type (owner/admin/member), hasRole() hierarchy check,
isValidRole() validator, and role field to AuthUser interface.
Keeps is_admin as deprecated computed field for backward compatibility.

* Update auth middleware for role-based access

Read role column from DB instead of is_admin. Compute is_admin from
role for backward compatibility. Add ownerMiddleware for owner-only routes.

* Add role management endpoint and update admin routes

Add POST /admin/users/:username/role (owner-only) with safety checks:
cannot self-demote, cannot remove last owner, token revocation on
demotion. Update user listing to include role, update regenerate-iam
to use role instead of is_admin.

* Replace is_admin checks with role-based checks in routes

Update datasets.ts: replace all is_admin inline checks with hasRole(),
update IAM query to read role column, update notification queries.
Update auth.ts: return role in login response, update notification query.
Update users.ts: return role in /users/me response.

* Update CLI for role display and management

Add role field to API types (LoginResponse, UserInfo, UserListItem).
Add changeUserRole() API function and 'nemar admin role' command.
Show role badges in user list, role-specific login messages, and
role in 'auth status --refresh' output.

* Update tests for role system

Add test-owner user to test setup, add role column to all test users,
update test assertions to check role field alongside is_admin for
backward compatibility.

* Fix review findings and fully remove is_admin

- Add parseRole() for validated role parsing instead of unsafe casts
- Add isDemotion() helper, export ROLE_HIERARCHY
- Fix privilege escalation: only owners can revoke other owners
- Wrap token revocation and audit log in try-catch
- Remove is_admin from AuthUser, API responses, CLI types, and tests
- Fix IAM null-role logic: use validated user.role from middleware
- Add requireAuth() to role command
- Add migration 0010 to drop is_admin column from users table
- Update test scripts to remove is_admin references
Phase 1 of deletion epic (#128). Adds deleteObjects, deleteDatasetObjects,
and deleteStagingObjects to backend/src/services/s3.ts.

- S3 Multi-Object Delete API with 1000-key batching
- bypassGovernance flag for Object Lock GOVERNANCE mode
- Dataset ID and PR number validation
- Robust XML response parsing with batch count validation
- Try-catch around fetch for partial progress preservation
- Refactored applyObjectLock to reuse computeMd5Base64 helper
- Integration tests in test/s3-deletion.test.ts (skip when no AWS creds)

Closes #123
Phase 2 of deletion epic (#128). Adds deleteRepository to
backend/src/services/github.ts.

- Idempotent: returns true for 204 (deleted) and 404 (already gone)
- Repo name validation (rejects /, .., empty strings)
- Tight status check (204/404 only, not all 2xx)
- Integration tests in test/github-deletion.test.ts

Closes #124
Phase 3 of epic #128: wires S3 and GitHub deletion into a full cascade.

- Add shared deleteDatasetCascade service (GitHub, S3, D1 batch delete)
- Add DELETE /admin/datasets/:id with DOI/owner permission checks
- Add admin delete-dataset CLI command with confirmation prompt
- Add scheduled cron cleanup (sandbox 14d, stale nm 90d)
- Add last_activity_at migration with backfill
- Harden error handling: all steps reflected in deleted field,
  independent try-catch for cron queries and audit log writes
- Fix CLAUDE.md: document deletion system (was still saying "not implemented")
- Fix 'completed' -> 'published' status in pub-request blocking query
- Return HTTP 207 on partial deletion failure (was always 200)
- Handle no-body DELETE requests (don't require JSON body)
- Add pub-request guard to cron stale dataset query
- Include warnings in cron audit log results
- Add explicit dataset_collaborators delete for FK defense-in-depth
- CLI: check result.deleted, show spinner.fail on incomplete deletion
- Merge duplicate DOI check blocks, simplify S3 summary output
- deleteRepository: reject slash, .., empty repo names (path traversal guard)
- hasRole, isDemotion, isValidRole, parseRole: full unit test coverage
* Add dataset release and update CLI commands

Implement `nemar dataset release` for version bump PRs and
`nemar dataset update` for pushing local changes via PR.

- Add semver utility (src/lib/semver.ts) with tests
- Add GET /datasets/:id/versions backend endpoint
- Add getFileContent() to GitHub service
- Update pr-merge workflow: always cleanup staging
- Add D1 migration step to deploy-backend workflow
- Fix 0011 migration: remove non-constant DEFAULT
- Add versioning guide and update command docs

* Address review findings: error handling and safety guards

- Log errors in catch blocks instead of silently swallowing
- Check git add exit codes before proceeding to commit
- Guard monitoring mode behind successful PR creation
- Validate getFileContent response shape
- Fix collaborator query (remove non-existent status column)
- Add D1 migration step to production deploy workflow

* Address review round 2: hard errors, type safety, cleanup

- Version fetch failures are now hard errors (not silent "1.0.0" fallback)
- Wrap all JSON.parse calls in try-catch with user-friendly messages
- Check git status exit code in update command
- Remove unused repoName variable in release monitor
- Narrow VersionInfo.provider to "ezid" | "zenodo" union type
- Fix misleading comment on file categorization regex
- Clarify cleanup-staging step name for always() behavior
- Add maxAttempts comment in update monitor loop

* Distinguish filesystem from JSON parse errors in catch blocks

Bare catch blocks reported all errors as "invalid JSON" which could
hide permission or filesystem errors. Now checks for SyntaxError
to provide accurate error messages.
Both dev and prod use the same D1 database. The --env dev flag
triggers wrangler error 7403 on D1 migrations apply.
Skip Zenodo upload for EZID datasets and use ezidMakePublic()
to transition DOI from reserved to public status.

Fixes #134
- Remove non-existent nemar-s3 remote from generate-archive
  workflow; use web remote URLs registered during upload
- Fetch git-annex branch before init in CI
- Surface git-annex push warnings in upload command
Publish orchestrator step 10 now creates a Zenodo draft deposition
and uploads the archive for EZID datasets. The webhook version DOI
handler does the same for subsequent versions. Zenodo backup is
non-fatal; failures are logged but do not block the EZID flow.
* Add BIDS validator auto-update and --update flag

- Add --reload flag to Deno invocations when cache is stale (>7 days)
- Add --update CLI flag to force refresh validator cache
- Show stale cache warning in --version-info output
- Auto-check for updates when cache is older than 7 days

Closes #139

* Fix review: Windows cache path, pass forceReload

- Add Windows platform cache path (AppData/Local/deno)
- Pass forceReload option through to runBidsValidatorDirect
* Secure auth flow: stop emailing API keys, add key retrieval

- Stop sending API keys via email (security risk)
- Add POST /auth/retrieve-key: email + password -> API key
- Add POST /auth/request-key-regeneration: sends verification email
- Add GET /auth/confirm-key-regeneration: revokes old key, issues new
- Add 'nemar auth retrieve-key' CLI command
- Add 'nemar auth regenerate-key' CLI command
- Update approval email to instruct CLI key retrieval
- Update admin approve messaging to reflect new flow

Closes #140

* Fix review: rate limiting, XSS escaping

- Add new auth endpoints to strict rate limit paths
- Apply escapeHtml to all user data in HTML templates
- Escape username, URLs, and user descriptions
* Add role filtering and improve role CLI discoverability

- Add --role filter to 'nemar admin users' command
- Add role query param support to backend GET /admin/users
- Show [member] badge alongside [owner] and [admin] in user list
- Add detailed help text for role command with permission model
- Add role examples to admin help text

Closes #141

* Fix review: add server-side role validation

- Validate role query param against allowed values
- Return 400 for invalid role instead of empty results
Add retrieve-key, regenerate-key (auth) and role (admin)
to docs generation. Update auth workflow documentation
to reflect secure key retrieval flow.
Bare jsr:@bids/validator resolves once and caches the version.
Using jsr:@bids/validator@^2 allows --reload to actually resolve
to the latest 2.x release from JSR.
* Add multi-account switching support

Extend config to store multiple accounts keyed by username with an
active account pointer. Login adds accounts without overwriting
existing ones. Switch accepts NEMAR or GitHub username and also
triggers gh auth switch. Logout removes only the active account
unless --all is passed. Backward compatible with existing configs
via auto-migration on startup.

* Address review: atomic migration, remove dead code

- Make config migration atomic via config.store assignment with
  try/catch fallback to preserve legacy format on failure
- Remove unused removeAccount export
- Revert clearConfig return type to void (no caller uses it)
Read stderr before awaiting exit to avoid stream race condition.
Always display the error when gh fails instead of silently dropping
non-"not found" errors.
Use Bun.which() to resolve gh path directly. If that fails,
fall back to the user's login shell to resolve it, covering
cases where gh is only in PATH via .zshrc or .bashrc.
Check that accounts map has entries, not just that the key exists.
An empty accounts object ({}) is truthy but would leave the user
in a broken state with no accessible accounts.
await import("bun") gets mangled by bun build --minify into invalid
JS (awaitPromise). Use Bun.spawn and Bun.which globals directly
instead, which are always available at runtime. Remove the shell
fallback since Bun.which already searches the full PATH.
List and delete ALL existing IAM access keys instead of relying
on the D1-tracked encrypted key. Handles ENCRYPTION_KEY rotation
and cases where keys exist in AWS but can't be decrypted from D1.

Also export listAccessKeys and document ENCRYPTION_KEY secret.
Instead of monotonically incrementing from id_sequence, find
the lowest unused number by querying gaps in the datasets table.
This ensures deleted dataset IDs (e.g. nm000108) are reused.
@neuromechanist

Copy link
Copy Markdown
Contributor Author

PR Review Summary

Reviewed by 4 specialized agents: code-reviewer, silent-failure-hunter, code-simplifier, comment-analyzer.

Critical Issues (2 found)

1. Race condition in dataset ID generation [datasetId.ts]

Reported by: code-reviewer, silent-failure-hunter

The old code used atomic UPDATE RETURNING on id_sequence. The new code uses a SELECT-only CTE to find the lowest gap, but the actual INSERT INTO datasets happens much later in datasets.ts (after GitHub repo creation, S3 setup, IAM policy). Two concurrent requests can pick the same freed ID.

The datasets.dataset_id UNIQUE constraint prevents data corruption (second INSERT fails), but the user gets an opaque D1 error instead of a retry.

Recommendation: Add a retry loop in datasets.ts around the generate+insert flow to catch UNIQUE constraint violations and re-generate.

2. Recursive CTE hits SQLite recursion limit for large ranges [datasetId.ts]

Reported by: code-reviewer

The CTE generates every number from start to max+1. SQLite's default recursion limit is 1,000. If max dataset ID reaches nm001107 (start=108), that's 1,000 iterations, hitting the limit. For sandbox xx prefix with a high-numbered dataset, it would fail earlier.

Recommendation: Replace recursive CTE with a non-recursive approach, e.g. generating candidate numbers from existing_number + 1 and checking for gaps.

Important Issues (3 found)

3. Root-level logout shortcut missing --all option [index.ts:75-79]

Reported by: code-reviewer

The root nemar logout doesn't forward --all that was added to auth logout. Also uses -f, --force instead of YES_OPTION/NO_OPTION, so the confirm utility won't see the yes flag.

4. statusAction displays stale config after --refresh [auth.ts:394-456]

Reported by: code-reviewer

getConfig() is called before the refresh block updates the config store. After nemar auth status --refresh, the user sees old values.

5. Silent catch in migrateConfig() [config.ts:113-115]

Reported by: silent-failure-hunter

Empty catch block swallows all errors. If migration fails (corrupt config, permission issue), user appears logged out with no explanation.

Recommendation: Add console.error to surface the failure reason.

Suggestions (4 found)

6. getCurrentSequence silently falls back to 108 [datasetId.ts:70]

Returns 108 if query fails, masking database issues. Should log a warning.

7. IAM key revocation loop stops on first failure [admin.ts:840-848]

If user has 2 keys and first deletion succeeds but second fails, the warning doesn't indicate how many keys remain. Move try-catch inside the loop.

8. switchGitHubAuth outer catch discards error object [auth.ts:504-506]

Bare catch without error object; shows "gh not available" even for unrelated errors.

9. .context/dataset_workflow.md describes old id_sequence approach [stale docs]

Still references SELECT/UPDATE id_sequence which is no longer the implementation.

Code Simplifier Applied (3 changes, uncommitted)

  1. datasetId.ts: Extracted findLowestUnusedNumber() helper to eliminate CTE duplication between generateDatasetId and getCurrentSequence. Fixed biome formatting.
  2. config.ts: Extracted DEFAULT_API_URL constant to replace 4 hardcoded URL strings. Simplified getConfig() and setConfig().
  3. admin.ts: Hoisted shared awsConfig object and import statement above both try blocks that use them, eliminating duplication.

Strengths

  • The gap-reuse approach for dataset IDs is the right design; just needs concurrency hardening
  • IAM regeneration fix correctly handles stale D1 credentials by listing keys from AWS directly
  • Multi-account switching is well-structured with interactive picker and edge case handling
  • switchGitHubAuth properly uses Bun.which() and Bun.spawn() to handle minified binary

Recommended Action

  1. Fix critical Add proper test coverage measurement (90%+ target) #1 (retry loop) and Optimize KV usage to stay within free tier limits #2 (replace recursive CTE)
  2. Address important CLI shows success then failure on admin approve #3-Email delivery issues with Resend (bouncing, suppression list) #5
  3. Commit the code-simplifier changes
  4. Consider suggestions feat: implement per-dataset collaborator access #6-nemar login user experience #9

- Replace recursive CTE with non-recursive gap-finding query
  (avoids SQLite 1000-recursion limit)
- Add retry loop with early INSERT to close TOCTOU race condition
  in dataset ID generation
- Use atomic config.store writes to prevent partial config corruption
- Log migration errors instead of silently swallowing them
- Fix statusAction showing stale config after --refresh
- Capture error in switchGitHubAuth catch block
- Fix setup-ssh help text (no backend registration)
- Fix root-level logout/login option mismatch (--all, --yes/--no)
- Handle partial IAM key revocation failures per-key
- Update stale dataset_workflow.md ID generation docs
@neuromechanist
neuromechanist merged commit d8c70ef into main Feb 14, 2026
18 checks passed

This branch was previously deployed

2 inactive deployments
development — 9a5a6e9c Deployed Feb 14, 2026 by neuromechanist via deploy-dev #56
npm — 9a5a6e9c Deployed Feb 14, 2026 by neuromechanist via publish #267
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