diff --git a/.agents/agents/app-debug-specialist.md b/.agents/agents/app-debug-specialist.md index 3cc83d1fd..d4c6847c2 100644 --- a/.agents/agents/app-debug-specialist.md +++ b/.agents/agents/app-debug-specialist.md @@ -5,43 +5,44 @@ ## Responsibilities ### Test & Debug Workflow -- Run Maestro tests and capture iOS simulator logs +- Run the repository's app tests and capture simulator or emulator logs - Parse and analyze console output for specific issues - Set up automated logging with react-native-logs -- Manage Metro bundler lifecycle (start, restart, monitor) +- Respect the distinction between targeted interactive debugging and the self-contained canonical E2E runner - Coordinate test runs with log capture ### Log Management - Capture iOS simulator logs: `xcrun simctl spawn booted log stream --predicate 'processImagePath endswith "QuickCryptoExample"' --level debug` - Filter logs for relevant patterns - Save logs to `/tmp/rnqc-session.log` for analysis -- Monitor Metro bundler output at `/tmp/metro.log` +- Monitor interactive Metro client output at `/tmp/rnqc-metro.log` ### Iteration Speed Tools -- Keep Metro running in background (PID in `/tmp/metro.pid`) -- Reload app without full rebuild when possible -- Use Maestro for automated UI testing -- Chain commands efficiently (rebuild TS → rebuild iOS → run test → capture logs) +- Attach to an existing RNQC Metro process for targeted debugging without restarting another project or taking over its port +- Reload the app without a full rebuild when possible +- Use the canonical runner for full-app automated qualification +- Chain targeted commands efficiently without overlapping runner-owned app, device, or Metro resources ## Key Scripts -### Debug Test Runner +### Canonical E2E Runner ```bash -./scripts/debug-test.sh [test-flow] [--rebuild-ts] +bun run e2e:ios +bun run e2e:android ``` +Run these serially from the repository root. The workspace wrappers invoke `example/test/e2e/runner.mjs`, which selects the configured platform target and owns its RNQC app, simulator or emulator, isolated Metro port, artifacts, and cleanup. Follow `docs/local-e2e.md` when signed qualification is required. + ### Manual Workflow ```bash -# 1. Ensure Metro is running -bun start > /tmp/metro.log 2>&1 & echo $! > /tmp/metro.pid +# 1. Attach to the existing RNQC app and Metro; do not restart another project's process # 2. Capture logs xcrun simctl spawn booted log stream \ --predicate 'processImagePath endswith "QuickCryptoExample"' \ --level debug > /tmp/rnqc-session.log 2>&1 & LOG_PID=$! -# 3. Run test -cd example && maestro test test/e2e/import-export-local.yml +# 3. Drive the relevant flow in the RNQC example app # 4. Stop log capture and view kill $LOG_PID @@ -53,20 +54,18 @@ grep -E "pattern" /tmp/rnqc-session.log ### Rebuild & Test Cycle ```bash # Full rebuild (TypeScript + iOS) -cd packages/react-native-quick-crypto && npm run prepare +cd packages/react-native-quick-crypto && bun run prepare cd ../../example && bun ios -# Then run debug test -./scripts/debug-test.sh +# Then drive the affected RNQC example-app flow ``` ### TypeScript-only Changes ```bash # Rebuild TypeScript -cd packages/react-native-quick-crypto && npm run prepare +cd packages/react-native-quick-crypto && bun run prepare -# Metro will auto-reload, or manually restart it -pkill -P $(cat /tmp/metro.pid) && bun start & echo $! > /tmp/metro.pid +# The existing RNQC Metro process should reload the bundle; do not take over its port ``` ### C++ Changes @@ -92,53 +91,33 @@ grep -E "asymmetricKeyDetails|keyDetail|rsaImportKey" /tmp/rnqc-session.log tail -f /tmp/rnqc-session.log ``` -## Metro Management - -### Check if Running -```bash -[ -f /tmp/metro.pid ] && ps -p $(cat /tmp/metro.pid) && echo "Running" || echo "Not running" -``` - -### Start Metro -```bash -cd example && bun start > /tmp/metro.log 2>&1 & echo $! > /tmp/metro.pid -``` +## Metro Diagnostics -### Stop Metro -```bash -kill $(cat /tmp/metro.pid) 2>/dev/null && rm /tmp/metro.pid -``` +For interactive debugging, attach to the existing RNQC process. Never kill or restart another project's Metro or claim its port. The canonical E2E runner starts and cleans up its own isolated Metro process. -### View Metro Logs +### View RNQC Metro Logs ```bash -tail -f /tmp/metro.log +tail -f /tmp/rnqc-metro.log ``` -## Maestro Tests +## Full-App Tests -### Available Flows -- `test/e2e/import-export-local.yml` - Just the importKey/exportKey suite -- `test/e2e/test-suites-flow.yml` - Full test suite - -### Run Specific Test -```bash -cd example && maestro test test/e2e/import-export-local.yml -``` +Use `bun run e2e:ios` followed by `bun run e2e:android` from the repository root. Do not substitute removed Maestro flows. For narrower debugging, drive the relevant existing example-app test path and record exactly what was exercised. ## Debugging Tips -1. **Always keep Metro running** - Don't kill it between test runs -2. **TypeScript changes** - Require Metro reload, not full rebuild -3. **C++ changes** - Require full iOS rebuild -4. **Log capture timing** - Start before test, stop 3-5s after test completes -5. **Check PID files** - Metro and log capture PIDs in `/tmp/` +1. **Respect process ownership** - Attach for interactive work; let the canonical runner own and clean up its resources +2. **TypeScript changes** - Usually require Metro reload, not a full native rebuild +3. **C++ changes** - Require a native rebuild +4. **Log capture timing** - Start before the targeted flow and stop after the relevant output is complete +5. **Platform target** - Verify the runner or interactive session is using the intended RNQC simulator or emulator ## Files to Monitor - `/tmp/rnqc-session.log` - iOS simulator logs -- `/tmp/metro.log` - Metro bundler output -- `/tmp/metro.pid` - Metro process ID -- `example/test/e2e/*.yml` - Maestro test flows +- `/tmp/rnqc-metro.log` - Interactive RNQC Metro client output +- `example/build/e2e///` - Canonical runner results, screenshots, and logs +- `example/test/e2e/runner.mjs` - Canonical full-app runner ## Integration with Main Workflow diff --git a/.agents/agents/orchestrator.md b/.agents/agents/orchestrator.md index c2bae8836..ccd9523aa 100644 --- a/.agents/agents/orchestrator.md +++ b/.agents/agents/orchestrator.md @@ -1,196 +1,69 @@ --- name: orchestrator -description: MUST BE USED for all multi-file operations (3+ files) or cross-domain tasks. Decomposes tasks and coordinates specialist agents. +description: Coordinates complex, cross-domain, or multi-phase work when delegation materially improves correctness or keeps contexts independent. --- -# Pure Orchestrator Agent +# Evidence-Led Orchestrator -**YOU ARE A PURE ORCHESTRATION AGENT. YOU NEVER WRITE CODE.** +Use orchestration for cross-language crypto features, changes with dependent phases, difficult recon, or work that benefits from an independent review. A multi-file documentation update or tightly coupled small fix may be handled directly. Do not delegate merely to satisfy a file count. -## Your Responsibilities +## Responsibilities -1. **Analyze incoming requests** for complexity, dependencies, and architectural impact -2. **Decompose into atomic tasks** that can be parallelized -3. **Assign tasks to appropriate specialists** based on their domain expertise -4. **Monitor progress** and handle inter-agent dependencies -5. **Synthesize results** into coherent deliverables -6. **Maintain architectural integrity** across all work -7. **Track metrics** (token usage, timing, cost) and report them in final summary +1. Establish the goal, scope, repository root, branch, constraints, and delivery boundary. +2. Read the relevant `.agents/rules/*.md` and canonical slash command before action. +3. Separate verified facts, assumptions, decisions, and unverified behavior. +4. Decompose work into the fewest independently committable phases. +5. Coordinate specialists only where their domain expertise changes the outcome. +6. Preserve branch safety, plan state, current verification evidence, and clean handoffs. +7. Require an independent local review and close the plan lifecycle before PR delivery. -## When to Activate +## Planning -Use orchestrator for: +Use early parallel work only for genuinely independent structural discovery. Shared files, APIs, assumptions, generated bindings, and native/TypeScript boundaries make phases dependent; run those phases sequentially with fresh context. -- Tasks touching 3+ files -- Cross-language operations (e.g., TypeScript + C++) -- New feature development with multiple components -- Refactoring that spans multiple domains -- Cryptographic implementations requiring both native and JS layers +Ask structural questions once before implementation when a wrong answer would discard substantial work. Resolve later non-structural choices from the issue, codebase, and established patterns, then record them under **Assumptions**. Stop only when a late discovery invalidates the structure or a required external capability blocks a diff-changing verification. -## Task Decomposition Pattern +For new `/implement` work, keep `plans/todo/-.md` as the source of truth for the live tracker, decisions, assumptions, evidence, and unverified items. Do not create fake retroactive plans for branches already underway. -When you receive a request: +## Model routing -1. **Map all dependencies** +- Bounded implementation and routine verification: Sol at default reasoning. +- General independent review and a failed implementation retry: Sol at high reasoning. +- Initial recon, difficult design, and focused crypto correctness review: Astra. +- Explicit user choices and live provider capabilities override defaults. - - Which layers are affected? (JS, C++, native bridging) - - What are the data flows? - - Are there shared types or interfaces? +These instructions select delegated models; they do not switch the active model. Never silently invoke separately billed tools. Use the minimum useful number of agents. -2. **Identify parallelization opportunities** +## Phase contract - - Which tasks are independent? - - What can run concurrently? - - What must be sequential? +Give each agent a self-contained brief containing: -3. **Create explicit task boundaries** +- Actual repo root from `git rev-parse --show-toplevel`. +- Expected branch and instruction to stop if it differs. +- Exact phase scope and files. +- Relevant issue text, verified recon, rules, and prior corrections. +- Checks selected by changed behavior and affected dependencies. +- Existing evidence that should be reused. +- Required return: paths, commit SHA, checks/results/platforms, deviations, and unfinished work. - - Each specialist gets a clear, focused scope - - Define success criteria - - Specify interfaces/contracts between tasks +Each implementation phase commits through real hooks and leaves a clean tree. Verify the reported result with `git rev-parse HEAD` and `git status --porcelain`. Retry a failed phase once with fresh reviewer-tier context, then stop and report. -4. **Assign to specialists** - - typescript-specialist: TypeScript API surface, types, JS implementations - - cpp-specialist: C++ Nitro Modules, OpenSSL 3.6+ integration, native code - - crypto-specialist: Cryptographic correctness, algorithm implementation, security - - testing-specialist: Test strategies (note: tests run in RN app environment) +## Evidence policy -## Orchestration Examples +Track evidence by commit SHA, exact tool or test, result, and platform. Reuse current evidence; do not ask every phase and reviewer to rerun the same broad suite. -### Example 1: New Crypto Feature (WebCrypto API) +Run the package Jest script only for actual Node-side changes: `cd packages/react-native-quick-crypto && bun run test`. Native runtime changes use the example app and the relevant platform. A full foundational shared-crypto suite requires a stated cross-cutting reason or unexplained failure and one owner. -``` -User Request: "Implement subtle.encrypt/decrypt for AES-GCM" +Documentation-only work needs path, link, command, and consistency validation rather than runtime tests. -Orchestrator analyzes: -- Scope: TypeScript API, C++ implementation, OpenSSL 3.6+ -- Requires: Type definitions, native implementation, bridging +When the native merge gate applies, use the canonical root `bun run e2e:ios` then `bun run e2e:android` recipe and attestation workflow in `docs/local-e2e.md`. The producer owns that serial run, so do not schedule a needless duplicate suite immediately beforehand. Raw evidence can support review, but final delivery requires the trusted pinned patched producer to sign the exact clean committed HEAD after plan completion and all fixes; posting waits until the remote PR head matches. Keep AgentSCM coordination availability distinct from the local attestation producer. -Decomposition: -Wave 1 (Foundation): - - crypto-specialist: Review WebCrypto spec, analyze Node.js ncrypto implementation - - typescript-specialist: Define TypeScript types matching WebCrypto API +## Review and delivery -Wave 2 (Implementation): - - cpp-specialist: Implement AES-GCM using OpenSSL 3.6+ EVP APIs - - typescript-specialist: Create Nitro Module bindings +Use a fresh independent reviewer for the complete `origin/main...HEAD` diff and uncommitted work. The reviewer prints Fix/Skip/Ask decisions and clear Fix items proceed immediately. Local review never waits for a bot. -Wave 3 (Validation): - - crypto-specialist: Verify algorithm correctness, edge cases - - testing-specialist: Design test strategy for RN environment -``` +Before PR delivery, verify commits, clean status, scoped evidence, and any diff-changing runtime behavior. Move the exact completed plan from `plans/todo/` to `plans/done/` in the same branch and remove the ignored progress stub. Commit and complete static review before final native attestation. Then use `/pr` to push, create or update the PR, and post authorized attestation evidence for the matching remote SHA. -### Example 2: Refactoring to Modern C++ +## Final report -``` -User Request: "Migrate hash functions from OpenSSL 1.1.1 to 3.6+" - -Orchestrator analyzes: -- Scope: Multiple C++ files, OpenSSL API changes -- Requires: Understanding deprecations, modern patterns - -Decomposition: -Wave 1 (Research): - - cpp-specialist: Identify all OpenSSL 1.1.1 usage patterns - - crypto-specialist: Map deprecated APIs to OpenSSL 3.6+ equivalents - -Wave 2 (Migration): - - cpp-specialist: Update to EVP_* APIs, modernize C++ patterns - -Wave 3 (Validation): - - crypto-specialist: Ensure cryptographic correctness maintained - - testing-specialist: Verify no regressions -``` - -### Example 3: Node.js Polyfill Feature - -``` -User Request: "Add support for crypto.pbkdf2" - -Orchestrator analyzes: -- Scope: Node.js compatibility, OpenSSL integration -- Requires: API compatibility, native implementation - -Decomposition: -Wave 1 (Specification): - - crypto-specialist: Review Node.js API and ncrypto implementation - - typescript-specialist: Define TypeScript API matching Node.js - -Wave 2 (Implementation): - - cpp-specialist: Implement using OpenSSL 3.6+ PBKDF2 - - typescript-specialist: Create JS wrapper with Node.js semantics - -Wave 3 (Compatibility): - - crypto-specialist: Verify output matches Node.js - - testing-specialist: Create compatibility test suite -``` - -## Communication Protocol - -### Input Format - -You receive tasks in natural language. Extract: - -- Goal (what needs to be accomplished) -- Constraints (compatibility, performance, security) -- Context (related code, dependencies) - -### Output Format - -Provide: - -1. **Task Analysis**: What needs to be done and why -2. **Dependency Map**: What depends on what -3. **Wave Plan**: Sequential waves of parallel tasks -4. **Specialist Assignments**: Who does what -5. **Success Criteria**: How to validate completion -6. **Metrics Summary**: Token usage, timing, estimated cost - -## Rules You Must Follow - -1. **Never commit to main** - always create a feature branch (`feat/`, `fix/`, `refactor/`) before the first commit -2. **Never write code yourself** - always delegate to specialists -3. **Always parallelize independent tasks** - maximize efficiency -4. **Enforce architectural rules** from `.agents/rules/*.md` -5. **Track all metrics** - token usage, timing, cost estimates -6. **Validate completeness** - ensure all requirements met before marking done -7. **Report clearly** - synthesize specialist work into coherent summary - -## Available Specialists - -- **typescript-specialist**: TypeScript code, types, API surface, Nitro bindings -- **cpp-specialist**: C++20 code, OpenSSL integration, smart pointers, modern patterns -- **crypto-specialist**: Cryptographic correctness, algorithm implementation, security analysis -- **testing-specialist**: Test strategy design (acknowledges tests run in RN app) - -## Specialist Selection Logic - -``` -if (task involves TypeScript types or JS API): - assign typescript-specialist - -if (task involves C++ or OpenSSL): - assign cpp-specialist - -if (task involves cryptographic algorithms or security): - assign crypto-specialist - -if (task involves test design or validation strategy): - assign testing-specialist - -if (task spans multiple domains): - decompose and assign to multiple specialists in waves -``` - -## Success Metrics - -Track and report: - -- Total tokens used across all specialists -- Time elapsed (wall clock) -- Estimated cost (if applicable) -- Number of files modified -- Test coverage (when applicable) -- Security considerations addressed - -Remember: You are the conductor, not the musician. Your job is to ensure the symphony of specialists produces harmonious, high-quality code. +Report outcome, changed files or behavior, commit and PR identifiers, current checks by SHA/tool/platform, decisions, and genuine unverified residue. Do not report token, timing, or cost metrics unless the user asks for them. diff --git a/.agents/agents/testing-specialist.md b/.agents/agents/testing-specialist.md index 41a787053..44f59acd8 100644 --- a/.agents/agents/testing-specialist.md +++ b/.agents/agents/testing-specialist.md @@ -346,12 +346,6 @@ You work closely with: - Performance characteristics differ - No access to Node.js-specific APIs -**Don't assume you can run tests** - your job is to: -1. Design comprehensive test strategies -2. Identify test cases and edge cases -3. Provide test vectors and expected outputs -4. Document testing methodology - -The actual test execution happens in the example React Native app. +Agents may execute tests in the example React Native app; no separate human-only permission round is required. For canonical full-app qualification, run `bun run e2e:ios` and then `bun run e2e:android` from the repository root and follow `docs/local-e2e.md` when an attestation is required. Continue to design comprehensive strategies, identify edge cases, provide authoritative vectors and expected outputs, and document exactly what was exercised. Remember: Comprehensive testing is the last line of defense against bugs. Be thorough, be creative in finding edge cases, and always validate against authoritative sources. diff --git a/.agents/commands/address-pr-feedback.md b/.agents/commands/address-pr-feedback.md index c12704d38..065e6d262 100644 --- a/.agents/commands/address-pr-feedback.md +++ b/.agents/commands/address-pr-feedback.md @@ -1,213 +1,150 @@ # /address-pr-feedback - Address PR Feedback -Fetch and address all review bot feedback on the current PR. +Fetch, validate, and resolve all unaddressed feedback on the current PR. Invoking this workflow authorizes replies, the commits needed for fixes, and the qualified push of those commits. Do not reply to PR feedback outside an explicitly invoked feedback workflow. -## Instructions +Do not require CodeRabbit or any other reviewer to exist or finish. Process the feedback that is present; local `/review` remains independent. -### 1. Identify the PR +## 1. Identify and register the PR ```bash -gh pr view --json number,url,state --jq '{number, url, state}' +gh pr view --json number,url,state,author,headRefName,headRefOid --jq '{number,url,state,author,headRefName,headRefOid}' ``` -If no PR exists for the current branch, abort with a message. +Abort if the branch has no open PR. Register its URL with the host thread if a PR-link tool is available. -### 2. Check that review bots are done - -CodeRabbit reviews asynchronously. Before addressing feedback, verify it has finished. +Capture the number: ```bash -# Get all reviews on the PR -gh pr view --json reviews --jq '.reviews[] | {author: .author.login, state: .state}' - -# Check PR comments for bot activity (MUST use --paginate for large PRs) -gh api "repos/{owner}/{repo}/pulls/{pr}/comments" --paginate \ - --jq '[.[] | .user.login] | unique' +PR=$(gh pr view --json number --jq .number) ``` -**CodeRabbit**: Look for a PR comment containing "Walkthrough" or a review with `coderabbitai[bot]` as author. If not present, inform the user: - -> "CodeRabbit hasn't reviewed this PR yet. Wait for its review or run `@coderabbitai review` as a PR comment, then re-run this command." - -**If the bot hasn't finished, stop here.** Do not proceed to fixing issues with incomplete feedback. - -### 3. Fetch ALL review comments +## 2. Fetch all three feedback sources -**CRITICAL**: Always use `--paginate` with `gh api` for review comments. The default page size is 30, which is easily exceeded when CodeRabbit posts 16+ inline comments plus replies. Without `--paginate`, you will miss comments from later review passes. +Always paginate every endpoint. These are separate datasets and none substitutes for another. -#### 3a. Inline review comments +### Inline review comments and replies ```bash -# Get ALL review comments — MUST use --paginate -gh api "repos/{owner}/{repo}/pulls/{pr}/comments" --paginate --jq '.[] | { - id: .id, +gh api "repos/{owner}/{repo}/pulls/$PR/comments" --paginate --jq '.[] | { + id, author: .user.login, - path: .path, - line: .line, - body: .body, - in_reply_to_id: .in_reply_to_id, - created_at: .created_at + path, + line, + body, + in_reply_to_id, + commit_id, + created_at }' ``` -To identify **new unaddressed root comments**, filter by: - -- `in_reply_to_id == null` (root comment, not a reply) -- `user.login == "coderabbitai[bot]"` -- No reply from the PR author (`gh pr view --json author --jq '.author.login'`) exists with matching `in_reply_to_id` - -Useful shortcut to see how many batches exist: +### Review bodies ```bash -gh api "repos/{owner}/{repo}/pulls/{pr}/comments" --paginate \ - --jq '.[] | select(.user.login == "coderabbitai[bot]") | select(.in_reply_to_id == null) | .created_at' \ - | sort | uniq -c | sort -rn +gh api "repos/{owner}/{repo}/pulls/$PR/reviews" --paginate --jq '.[] | { + id, + author: .user.login, + state, + body, + commit_id, + submitted_at +}' ``` -Each unique timestamp cluster represents one review pass. +Read every non-empty review body. Findings outside the diff, summaries, and multi-item reviews often exist only here. -#### 3b. Outside-diff-range comments (in review body) - -CodeRabbit posts "outside diff range" comments in the **review body**, not as inline comments. These are easy to miss. - -```bash -# Get ALL CodeRabbit reviews with non-empty bodies (includes CHANGES_REQUESTED and COMMENTED states) -gh api "repos/{owner}/{repo}/pulls/{pr}/reviews" --paginate \ - --jq '.[] | select(.user.login == "coderabbitai[bot]") | select(.body | length > 0) | {id: .id, state: .state, submitted_at: .submitted_at}' -``` - -Then fetch each review body: +### General PR comments ```bash -gh api "repos/{owner}/{repo}/pulls/{pr}/reviews/{review_id}" --jq '.body' +gh api "repos/{owner}/{repo}/issues/$PR/comments" --paginate --jq '.[] | { + id, + author: .user.login, + body, + created_at +}' ``` -Look for the `⚠️ Outside diff range comments (N)` section in the body. Parse these — they contain file paths, line numbers, and the same comment format as inline comments. - -Also look for these sections in review bodies: +Identify unaddressed root findings. An inline entry with `in_reply_to_id != null` is a reply, not a new root. Account for existing author replies so reruns do not process settled threads or the workflow's own prior replies as findings. -- **"🧹 Nitpick comments (N)"** — valid code quality items -- **"♻️ Duplicate comments (N)"** — re-raised from prior reviews -- **"🤖 Prompt for AI Agents"** — structured fix instructions +## 3. Validate every claim -#### 3c. General PR comments +Open the current file and enough context to verify the comment's mechanism and conclusion. Compare the comment's commit to current HEAD when staleness matters. A confident reviewer comment is evidence to investigate, not ground truth. -```bash -gh api "repos/{owner}/{repo}/issues/{pr}/comments" --paginate \ - --jq '.[] | {id: .id, author: .user.login, body: .body, created_at: .created_at}' -``` - -### 4. Identify actionable feedback +Classify each item: -Collect ALL comments from: +1. **Fix:** Valid and has a clear repository-consistent correction. +2. **Dismiss:** Incorrect, out of scope, or no change is warranted; explain the evidence. +3. **Stale:** Current code already resolves or removes the concern. +4. **Ask:** Two defensible responses materially change behavior or blast radius and repository evidence cannot decide. -- Inline review comments (3a) -- Outside-diff-range / nitpick / duplicate comments from review bodies (3b) -- General PR comments (3c) +Use Ask only for genuine user-choice ambiguity. Resolve naming, factoring, and discoverable conventions autonomously. -Filter to unaddressed items from `coderabbitai[bot]`. +## 4. Print decisions, then act -**Before applying any fix**, first verify the finding against the current code and decide whether a code change is actually needed. If the finding is not valid or no change is required, do not modify code for that item and briefly explain why it was skipped. +Print: -For each comment, determine: +| # | Source | File:Line | Summary | Decision | Rationale | +|---|---|---|---|---|---| +| 1 | Inline / Review body / General | `path:42` | Brief claim | Fix / Dismiss / Stale / Ask | Verified reason | -1. **Valid concern** — fix it -2. **False positive** — reply explaining why -3. **Stale** — code was already changed/removed since the comment was posted -4. **Ambiguous** — ask the user which direction to take +If there are no Ask rows, immediately execute every decision without waiting. If Ask rows exist, continue all independent Fix, Dismiss, and Stale items through verification, push when needed, and replies; then ask only the unresolved choices. -### 5. Present decisions for approval +## 5. Fix, gate, commit, push, verify SHA -**STOP and present a table** before making any changes. The user must approve the plan first. +The order is mandatory: -| # | Source | File:Line | Comment Summary | Decision | Rationale | -| --- | --------------- | -------------------- | ---------------------------- | --------------------- | ----------------- | -| 1 | CR inline | `path/to/file.ts:42` | Brief summary of the comment | Fix / Dismiss / Stale | Why this decision | -| 2 | CR nitpick | `path/to/file.ts:10` | Brief summary | Fix / Dismiss / Stale | Why | -| 3 | CR outside-diff | `path/to/file.ts:78` | Brief summary | Fix / Dismiss / Stale | Why | +**fix → scoped gates → commit → push → verify remote SHA → reply** -Wait for the user to: +Do not post early replies. For fixes: -- **Approve all** — proceed with all decisions as proposed -- **Override specific rows** — change the decision for individual items (e.g., "dismiss #3 instead of fixing") -- **Ask questions** — clarify any items before approving +1. Edit the validated scope. +2. Run checks selected by the changed behavior and affected toolchains. +3. Reuse still-current evidence and rerun only checks invalidated by the fix. +4. Run Node Jest only for actual Node-side changes with `cd packages/react-native-quick-crypto && bun run test`. +5. Build or drive the example app when native runtime behavior requires it; docs-only fixes need no runtime retest. +6. Stage explicit paths and commit through `/commit`. +7. Push normally, never with `--no-verify`. -**Do not proceed to step 6 until the user approves.** +Verify local and remote SHAs: -### 6. Apply fixes locally (do NOT reply to bots yet) - -**CRITICAL — DO NOT reply to bot threads in this step.** Bot replies must happen _after_ push so the bot can verify against the actual remote. Replying with "Fixed" before the commit is on the remote causes the bot to re-flag the comment as unfixed (it reads the remote, not your working tree). +```bash +BRANCH=$(git branch --show-current) +LOCAL_SHA=$(git rev-parse HEAD) +REMOTE_SHA=$(git rev-parse "origin/$BRANCH") +PR_SHA=$(gh pr view "$PR" --json headRefOid --jq .headRefOid) +test "$LOCAL_SHA" = "$REMOTE_SHA" +test "$LOCAL_SHA" = "$PR_SHA" +``` -For each item that needs a code change: +If the native merge gate applies and feedback changed HEAD, the old receipt is not current. After every fix and documentation or plan commit is final, follow `docs/local-e2e.md` to attest the exact clean committed HEAD with the trusted inputs and pinned patched producer, verify the remote PR head equals the signed SHA, and post through the documented CLI. Do not fabricate evidence from earlier logs or manually post the status. Reuse a still-valid receipt after an unrelated base fast-forward only when its bound merge-base and other context are unchanged. -1. Read the file and understand the context around the flagged line. -2. Apply the fix. +If no code or documentation changed because every item is Dismiss or Stale, skip commit and push, use the current PR head SHA, and proceed to replies. -Do not post any thread replies, PR comments, or "Fixed" messages yet. Just edit code. +## 6. Reply after verification -### 7. Run quality gates +Reference the verified SHA and concise evidence. -After all fixes are applied: +For inline roots, reply on the existing thread: ```bash -bun tsc +gh api "repos/{owner}/{repo}/pulls/$PR/comments" -X POST -f body="Fixed in — " -F in_reply_to= ``` -All must pass before committing. - -### 8. Commit and push +Use the same mechanism for Dismiss or Stale with the reason instead of claiming a fix. -If any code changes were made: +Review-body findings have no inline thread. Post one consolidated top-level comment keyed to review IDs: ```bash -git add -git commit -m "fix: address PR review feedback from CodeRabbit" -git push +gh pr comment "$PR" --body-file ``` -**Verify the push landed before moving on.** Confirm `git log origin/ -1` matches your local HEAD, or check `gh api repos/{owner}/{repo}/pulls/{pr} --jq .head.sha`. The bots will read this SHA when re-evaluating, so the reply in step 9 must reference code that is actually on it. - -### 9. Reply to bot threads - -Now that the fix is on the remote, post replies. Reference the new commit SHA in "Fixed" replies so the bot can verify and so the timeline is auditable later. - -**Reply rules:** - -1. **Inline review comments (3a)** — reply on the conversation thread: - - ```bash - gh api "repos/{owner}/{repo}/pulls/{pr}/comments/{comment_id}/replies" \ - -X POST -f body="@coderabbitai Fixed in — " - ``` - -2. **Review-body / outside-diff items (3b)** — no inline thread exists. Post a top-level PR comment: - - ```bash - gh pr comment {pr} --body "@coderabbitai Addressed in : - - Fixed: - - Dismissed: " - ``` - -3. **General PR comments (3c)** — issue comments don't support threaded replies. Post a new PR comment referencing the original: - ```bash - gh pr comment {pr} --body "@coderabbitai Re: comment {comment_id} — Fixed in — " - ``` - -**CodeRabbit replies MUST start with `@coderabbitai`** or the bot will not see them. - -For false positives / stale, use the same reply mechanism with an explanation instead of "Fixed": +General issue comments do not support review threading. Post a new PR comment that references the original comment ID: ```bash -gh api "repos/{owner}/{repo}/pulls/{pr}/comments/{comment_id}/replies" \ - -X POST -f body="@coderabbitai " +gh pr comment "$PR" --body "Re: comment — addressed at — " ``` -### 10. Report summary +Do not require an `@coderabbitai` prefix unless that reviewer specifically requires it. -Present a summary to the user: +## 7. Report -- **Fixed**: List of issues that were fixed with brief descriptions -- **Dismissed**: List of false positives with reasoning -- **Stale**: Comments on code that was already changed/removed -- **Needs input**: Any ambiguous items requiring user decision -- **Quality gates**: Pass/fail status +Report Fixed, Dismissed, Stale, Needs input, checks with SHA/platform, pushed SHA, and reply status. If feedback changed PR scope or delivery, update the PR body through `--body-file`. diff --git a/.agents/commands/commit.md b/.agents/commands/commit.md index 06b8f8f81..64af80551 100644 --- a/.agents/commands/commit.md +++ b/.agents/commands/commit.md @@ -1,54 +1,65 @@ -# Commit Changes +# /commit - Commit Changes -Stage and commit the current changes with a well-crafted message. +Stage and commit only the current task's changes. Standalone `/commit` does not push. ## Instructions -When activated, commit the current working tree changes: - -1. **Sync with remote**: - - Run `git fetch origin main` to get latest upstream - - Run `git log HEAD..origin/main --oneline` to check if main has moved ahead - - If it has, warn the user but don't rebase automatically - -2. **Ensure we're not on main**: - - Run `git branch --show-current` - - If on `main`, create a new feature branch: - - Look at the staged/unstaged changes to infer a branch name - - Run `git checkout -b feat/` - - Inform the user of the new branch name - -3. **Review changes**: - - Run `git diff --stat` and `git diff --staged --stat` to see what's changed - - If nothing is staged, run `git add -A` to stage everything - - Run `git diff --staged --stat` to confirm what will be committed - -4. **Run code quality checks before committing**: - - **C++ files**: If any `.cpp`/`.hpp`/`.h` files are staged, run: - ```bash - clang-format -i - ``` - Then re-stage them with `git add`. - - **TypeScript files**: If any `.ts`/`.tsx` files are staged, run: - ```bash - npx prettier --write - ``` - Then re-stage them with `git add`. - - **Type check**: Run `cd packages/react-native-quick-crypto && bun tsc --noEmit` to verify types. - -5. **Generate commit message**: - - Use conventional commit format: `type: short description` - - Types: `feat`, `fix`, `refactor`, `chore`, `docs`, `test` - - If the change is substantial, add a body paragraph separated by a blank line - - Body should explain **what** changed and **why**, not how (the diff shows how) - - Keep the subject line under 72 characters - -6. **Commit** (with 120000ms timeout — pre-commit hooks run lint-staged, clang-format, tsc, and bob build): - ```bash - git commit -m "" - ``` - **NEVER use `--no-verify`.** Pre-commit hooks exist to catch errors. If they fail, fix the issue. - -7. **Report** the commit hash and summary to the user - -If the user provides arguments (e.g., `/commit "fix: resolve race condition"`), use that as the commit message instead of generating one. +### 1. Synchronize and guard the branch + +```bash +git fetch origin main +git branch --show-current +git log HEAD..origin/main --oneline +git status --short +``` + +Never commit on `main`. If the task started on `main`, create a correctly named `feat/`, `fix/`, or `refactor/` branch before committing and report it. If `origin/main` moved ahead, report that fact but do not rebase automatically. + +### 2. Define the commit scope + +Review both staged and unstaged changes: + +```bash +git diff --stat +git diff --staged --stat +git diff +git diff --staged +``` + +Preserve unrelated edits. Stage explicit task paths with `git add ...`; never default to `git add -A`. If ownership of a changed path is genuinely unclear, leave it unstaged and report it. + +### 3. Run relevant pre-commit checks + +Format and verify what the commit changes: + +- C++ files: run `clang-format -i` on the explicit changed `.cpp`, `.cc`, `.cxx`, `.hpp`, and `.h` paths, then stage them again. +- TypeScript or JavaScript files: run the repository's Bun-backed Prettier/lint scripts for the affected workspace, then stage resulting task-file edits. +- TypeScript API or implementation: run the relevant `bun tsc`. +- Node-side behavior: run `cd packages/react-native-quick-crypto && bun run test` only when actual Node-side code changed. +- ncrypto/OpenSSL changes: run `scripts/check-ncrypto-openssl-deprecations.sh` and other affected native checks. +- Documentation-only changes: run link/path/command consistency checks and `git diff --check`; no runtime test is required. If this commit follows a native attestation, note that delivery needs a new receipt for the new final HEAD rather than treating the prior receipt as current. + +Reuse current evidence when it covers the staged diff. Do not run a broad suite by default. + +### 4. Confirm the index + +```bash +git diff --staged --stat +git diff --staged +``` + +Abort if nothing is staged. Confirm no unrelated file entered the index. + +### 5. Commit through mandatory hooks + +Use a conventional message with a subject under 72 characters. If the user supplied a message, use it. A body should explain what and why. + +```bash +git commit -m ": " +``` + +Allow at least 120 seconds. The tracked hook runs `bun lint-staged`, C++ `clang-format --dry-run --Werror`, `bun tsc`, and `bun --filter="react-native-quick-crypto" prepare`. Never use `--no-verify` or `-n`; fix failures and retry normally. + +### 6. Report + +Report the commit SHA, subject, staged paths, checks run, and any uncommitted paths deliberately left alone. Do not push unless a separately invoked workflow such as `/pr`, `/implement`, or `/address-pr-feedback` authorizes it. diff --git a/.agents/commands/fix-pr.md b/.agents/commands/fix-pr.md new file mode 100644 index 000000000..9201bd2be --- /dev/null +++ b/.agents/commands/fix-pr.md @@ -0,0 +1,5 @@ +# /fix-pr - Address PR Feedback + +This is a short alias for `/address-pr-feedback`. + +Read `.agents/commands/address-pr-feedback.md` completely, then execute that canonical workflow without adding or omitting steps. diff --git a/.agents/commands/handoff.md b/.agents/commands/handoff.md new file mode 100644 index 000000000..ded3b8c51 --- /dev/null +++ b/.agents/commands/handoff.md @@ -0,0 +1,30 @@ +# /handoff - Session Handoff + +Produce a concise, self-contained handoff so the next session can resume without trusting conversation history. + +## Gather + +Read the current branch, recent commits, working tree, linked issue or PR, and the exact active plan if one exists: + +```bash +git branch --show-current +git log --oneline -10 +git status --short +gh pr view --json number,url,state,title,headRefOid 2>/dev/null || true +``` + +Check `.agents/progress/claude-progress.md` and its referenced plan, but do not assume a stale or missing stub describes the branch. + +## Output + +Include only relevant sections: + +- **State:** branch, HEAD SHA, clean or exact uncommitted paths, issue, PR URL/state/head SHA, and active plan phase. +- **Completed:** concrete work with commit SHAs or file paths. +- **Verified:** exact scoped checks, tools or tests, result, commit SHA, and platform. Distinguish native build, installed-app, simulator/device, Node-side, documentation evidence, raw E2E results, and a final signed attestation. For attestation, include the bound SHA and whether the remote PR head matched and posting completed; do not imply GitHub ran the mobile suites. +- **Unverified:** every claim or runtime behavior not actually exercised, why it matters, and what would settle it. +- **Decisions:** non-obvious choices and rationale. +- **Next actions:** ordered commands or files that let the next session continue without a clarification round. +- **Sibling dependencies:** related repository branch, SHA, PR, unpublished change, or external dependency when relevant. + +State whether subagent reports were independently checked. Do not report a test as current if relevant edits occurred after its recorded SHA. Do not hide failures or imply a push, PR update, device run, or review happened when it did not. diff --git a/.agents/commands/implement.md b/.agents/commands/implement.md new file mode 100644 index 000000000..32deef541 --- /dev/null +++ b/.agents/commands/implement.md @@ -0,0 +1,142 @@ +# /implement - Implement an Issue End-to-End + +Take one GitHub issue from recon through an open PR with minimal human intervention. `$ARGUMENTS` is a bare issue number, `#N`, or a full issue URL. With no argument, ask for the issue and stop. + +Invoking `/implement` explicitly authorizes the qualified push and PR creation or update at the end of this workflow. It does not authorize bypassing hooks, shipping known failures, overwriting unrelated work, or guessing through a structural product decision. + +## 1. Read the issue + +Use the issue API rather than search snippets: + +```bash +gh issue view --json number,title,body,labels,comments,state,closedByPullRequestsReferences +``` + +Normalize the returned number. If the issue is closed or already has a closing PR, stop and report it. Derive a lowercase, hyphenated slug of at most five words and use the exact `-` identifier for both the branch and plan. + +## 2. Fresh recon + +Use one fresh Astra recon subagent. Give it the complete issue text and comments plus the actual repository root returned by: + +```bash +git rev-parse --show-toplevel +``` + +Recon must read `AGENTS.md`, the relevant `.agents/rules/*.md`, Node.js `$REPOS/node/deps/ncrypto` before new crypto implementation, and the actual files it cites. It must not edit. + +Require the report to include: + +1. Verified files and line anchors, with each claim based on opening the file. +2. Existing repository patterns to mirror. +3. Two to five independently committable phases and their dependencies. +4. Targeted tests and affected toolchains. +5. Native platforms and driveable example-app checks. +6. Structural questions only. +7. Security and compatibility risks. +8. Explicitly unverified claims. + +Recount issue-provided file lists or quantities instead of trusting them. Mark inference as inference. If recon finds no change to make, stop and report. + +## 3. Resolve structural forks once + +Ask before code only when a wrong answer would discard substantial work: an API contract, a new cross-layer shape, a user-visible behavior the issue does not define, or designs with materially different security or compatibility impact. Present two or three concrete options with the recommendation first. + +Naming, file placement, factoring, and choices established by repository patterns are not structural questions. After this point, record reasonable decisions under **Assumptions** and continue. If a late discovery truly invalidates the chosen structure, stop and report rather than layering work onto it. + +## 4. Guard the checkout and create the tracker + +Before creating a branch: + +```bash +git status --porcelain +git rev-parse --show-toplevel +git fetch origin main +git show-ref --verify --quiet refs/heads//- +``` + +The working tree must be clean. Do not stash or absorb unrelated edits. Confirm the real repository root and stop if the branch already exists. Create `/-` from `origin/main`, where type is `fix`, `feat`, or `refactor`. + +Run `mkdir -p plans/todo`, then create `plans/todo/-.md` with: + +- Problem and intended outcome. +- **Live tracker** checklist for every implementation, qualification, review, and delivery phase. +- **Decisions** for user-selected structural choices. +- **Assumptions** for non-structural choices made during execution. +- **Evidence** entries containing commit SHA, exact tool or test, result, and platform. +- **Unverified** items with the condition that would settle each one. + +Point the ignored `.agents/progress/claude-progress.md` stub at the active plan and commit the plan. Never manufacture a retroactive tracker for an already-running branch merely to claim this workflow was followed. + +## 5. Implement sequentially with fresh context + +Run each dependent phase in order with one fresh Sol subagent at default reasoning. Parallelize only early work that is structurally independent and cannot overlap files or assumptions. + +Each phase prompt must include the actual repo root, expected branch, the plan path, that phase only, relevant recon evidence, prior corrections, applicable rules, and the targeted verification policy. Require the phase agent to: + +1. Confirm the repository root and branch before editing. +2. Re-open every file and verify recon claims. +3. Implement only its assigned phase. +4. Add or update tests selected by changed behavior and dependencies. +5. Run affected checks without repeating still-current evidence. +6. Update the plan tracker, decisions, assumptions, and evidence. +7. Stage only its files and make a conventional commit through the real hooks. +8. Return changed paths, commit SHA, exact checks and platforms, deviations, and unfinished work. + +After every phase, independently verify: + +```bash +git rev-parse HEAD +git status --porcelain +``` + +The SHA must have advanced and the tree must be clean. If the phase fails to commit, leaves changes, or reports unverified required behavior, retry once with a fresh Sol reviewer-tier subagent at high reasoning using the failure output and first report. Stop after the second failure. + +When a phase corrects recon, update the plan and all later prompts. Do not propagate a disproven premise. + +## 6. Qualify the branch + +Select checks from the actual diff and reuse valid phase evidence keyed by SHA, tool or test, and platform. + +- Run relevant TypeScript, lint, formatting, generated-code, C++, OpenSSL, and native checks for every changed toolchain. +- Run `cd packages/react-native-quick-crypto && bun run test` only when actual Node-side code changed. Do not substitute bare `bun test`. +- Test native runtime behavior in the example app. Attach to an existing RNQC app and Metro first; do not restart another project or take over its port. Use `/tmp/rnqc-metro.log` for RNQC Metro diagnostics. +- Build and install the example app when a native change requires a rebuild. Drive the affected tests or flow when feasible and record the platform. +- Do not rerun broad suites per phase. A full foundational shared-crypto suite requires a stated cross-cutting reason or unexplained failure, one owner, and one reusable result. +- Documentation-only changes need link and consistency checks, not a runtime retest. +- When full native qualification is required, preserve still-current targeted evidence but leave the canonical serial iOS-then-Android run to the attestation producer described in `docs/local-e2e.md`; do not run a duplicate broad suite immediately before it. + +A missing credential, unavailable platform, or unverified behavior blocks delivery only when a failure could require changing the diff. Stop and state the exact check needed. If the user explicitly directs shipment, disclose the unverified behavior and residual risk in the PR. + +Qualification fixes go to a fresh Sol implementation subagent and must be committed. Retry at most twice. + +## 7. Independent local review + +Use a fresh reviewer that did not implement the branch: Sol at high reasoning for general review, or Astra for focused difficult crypto correctness review. Follow `.agents/commands/review.md`, including `git fetch origin`, the `origin/main...HEAD` diff, uncommitted state, and every changed toolchain. + +Classify findings as Fix, Skip, or Ask. Apply clear Fix items immediately and continue independent fixes. Under `/implement`, do not add another approval round: resolve Ask items from the issue, code, and established decisions when possible and record the result under **Assumptions**. Stop only for a genuine unresolved structural choice. Commit review fixes and rerun only invalidated checks. + +Local review is required even if a review bot exists; it never waits for a bot. + +## 8. Complete the plan before the PR + +When implementation, qualification, and local review are complete, move the exact tracker in the same branch: + +```bash +mkdir -p plans/done +git mv plans/todo/-.md plans/done/-.md +rm -f .agents/progress/claude-progress.md +``` + +Carry any genuinely outstanding verification item with an owner and disclosure. Commit the plan move before opening the PR. If more than one plan could match, move none and stop for disambiguation. Work that is not implemented remains in `plans/todo/`. + +Finish this lifecycle before signing native qualification evidence. After the plan move and every documentation or review-fix commit, confirm the final SHA and clean tree, complete static review, then use `/pr` for push, final attestation, and posting. Do not discard a valid receipt merely because `main` fast-forwarded when its bound merge-base and other context are unchanged. + +## 9. Finish with /pr + +Read and execute `.agents/commands/pr.md` completely. Recompute scope, verification, and delivery from the actual diff rather than recon. Use `Closes #`, push the qualified commits, reuse an existing PR for the branch when present, and create one otherwise. When the native gate applies, the final signed evidence must bind the exact delivered HEAD and be posted only after the remote PR head matches that SHA. + +If the host exposes a PR-link registration tool, register the full PR URL with the current thread immediately after creating or taking ownership of the PR. + +## Final report + +Keep the report concise: changed behavior, PR URL or exact blocker, independent review findings and dispositions, assumptions, verification evidence by SHA/tool/platform, and explicitly unverified residue. diff --git a/.agents/commands/pr.md b/.agents/commands/pr.md index e7d690c3b..7b14e7971 100644 --- a/.agents/commands/pr.md +++ b/.agents/commands/pr.md @@ -1,38 +1,104 @@ -# /pr - Create Pull Request +# /pr - Create or Update a Pull Request -Create a pull request for the current branch. +Create or update the PR for the current branch. Invoking `/pr` authorizes the qualified push required for this workflow. ## Instructions -When activated, create a pull request for the current branch: +### 1. Establish accurate scope -1. **Verify branch state**: - - Run `git branch --show-current` to get the current branch name - - Ensure we're not on `main` (abort if so) - - Run `git log main..HEAD --oneline` to see commits to include +```bash +git fetch origin +BRANCH=$(git branch --show-current) +git status --short +git log origin/main..HEAD --oneline +git diff --stat origin/main...HEAD +git diff --name-only origin/main...HEAD +``` -2. **Push the branch** (if not already pushed): - - Run `git push -u origin ` +Abort on `main`. The working tree must be clean before push. Use `origin/main`, not a potentially stale local `main`, and use the three-dot diff for PR scope. -3. **Check for related issues**: - - Look at the branch name for issue numbers (e.g., `fix/896-buffer-import` references #896) - - Check commit messages for issue references - - Run `gh issue list --state open --limit 20` to see recent open issues that might be related - - If the PR resolves an issue, note it for the body +### 2. Confirm qualification -4. **Generate PR title and body**: - - Title: Use conventional commit format based on the primary change (e.g., `fix: import Buffer from react-native-quick-crypto`) - - Body should include: - - **Summary**: Brief description of what this PR does - - **Changes**: Bullet list of key changes - - **Testing**: How to test the changes (if applicable) - - **Issue references**: Add `Fixes #XXX` or `Closes #XXX` for any issues this PR resolves (these will auto-close the issues when merged) +Review current evidence for the actual HEAD and every changed toolchain. A qualified branch has: -5. **Create the PR**: - ```bash - gh pr create --title "" --body "<body>" --base main --assignee @me - ``` +- Required commits created through mandatory hooks. +- Relevant scoped checks passing at the current SHA. +- Native behavior built and exercised on the relevant platform when the diff requires it. +- No unverified runtime behavior that could change the diff, unless the user explicitly directed shipment and the PR discloses the gap and risk. +- An independent local review completed without waiting for a bot. +- When the native merge gate applies, final attestation is still pending until it binds the final committed HEAD; earlier raw E2E evidence may support review but does not replace that receipt. -6. **Report the PR URL** to the user +Do not rerun still-current broad evidence merely to open the PR. -If the user provides arguments (e.g., `/pr "Custom title"`), use that as the PR title instead of generating one. +### 3. Complete the exact plan lifecycle + +If the branch identifier is `<type>/<N>-<slug>`, look only for `plans/todo/<N>-<slug>.md`. Do not fuzzy-match or create a retroactive plan. + +If that exact plan exists and the implementation is complete: + +```bash +mkdir -p plans/done +git mv plans/todo/<N>-<slug>.md plans/done/<N>-<slug>.md +rm -f .agents/progress/claude-progress.md +``` + +Carry genuinely outstanding verification items with an owner, then commit the move through `/commit` before pushing. If multiple candidates exist or the work is incomplete, move none and report the mismatch. + +### 4. Reuse an existing PR + +Check for a PR whose head is the current branch: + +```bash +gh pr list --head "$BRANCH" --state all --json number,url,state,title,headRefOid +``` + +Reuse an open PR instead of creating a duplicate. If the only matching PR is closed or merged, stop and report before creating another. + +### 5. Build the PR description from the actual diff + +Write the body to a temporary Markdown file and pass it with `--body-file`. Include: + +- **Summary:** outcome and rationale. +- **Changes:** concrete branch changes. +- **Testing:** exact commands, results, commit SHA, and native platform. Distinguish reused evidence from checks run during PR preparation. +- **Delivery:** what merging actually delivers. Agent/docs changes take effect in the repository on merge; CI changes alter validation on merge; package TypeScript/C++/Nitro changes reach consumers only after an npm release; native changes additionally require the consuming app to rebuild and ship. Example-app-only changes do not publish the library. +- **Not verified:** only explicit residue and risk, if shipment was authorized despite it. +- **Issue:** `Fixes #N` or `Closes #N` when the PR resolves the issue. + +Derive issue references from the exact branch identifier, issue context, and commits. Do not attach unrelated recent issues. + +### 6. Push and create or update + +```bash +git push -u origin "$BRANCH" +``` + +Never use `--no-verify`. Verify the remote branch SHA matches local HEAD before continuing. + +For an existing open PR, update it: + +```bash +gh pr edit <number> --title "<title>" --body-file <body-file> +``` + +Otherwise create it: + +```bash +gh pr create --title "<title>" --body-file <body-file> --base main --assignee @me +``` + +Use a conventional-commit-style title unless the user supplied one. + +### 7. Complete attested native qualification when required + +Follow `docs/local-e2e.md` rather than duplicating its commands. Use the trusted recipe, policy, and registry from `main` with the documented pinned, patched AgentSCM producer on reviewed code only. The checkout must be clean and the attestation must bind the exact final committed HEAD after the plan move, documentation commits, and all fixes. Keep the private key and state owner-private outside the checkout and never read or print secrets. + +Before signing or publishing screenshot evidence, fetch `origin/main` and run `git diff --exit-code origin/main -- .github/local-validation/recipe.json .github/local-validation/policy.json .github/local-validation/registry.json`. Stop if any differ: checkout-relative inputs are trusted only after this check. A PR changing the trust inputs must first get those changes reviewed and landed through the trusted default-branch process. + +The qualified push may happen before or after the local run, but before posting verify that local HEAD, the remote branch, and the pull request head all equal the signed SHA. Use the documented `local-validation post` command when this workflow or the user authorizes posting; never fabricate a receipt from logs or raw test results and never post the status manually. Screenshot posting is a separate, explicit action and is required only when authorized and material. + +Do not run a duplicate broad suite immediately before the producer: its trusted recipe already owns the serial `bun run e2e:ios` then `bun run e2e:android` run. A valid receipt remains usable across an unrelated base fast-forward when its bound merge-base and other context are unchanged. Describe `agentscm/local-validation` as worker-asserted coverage with the limitations in `docs/local-e2e.md`, not as GitHub-run mobile testing or a currently enforced required check unless the live ruleset was verified. + +### 8. Register and report + +Immediately register the full PR URL with the host thread when a PR-link tool is available. Report the URL, pushed SHA, qualification evidence, signed SHA and posting result when applicable, and any disclosed unverified behavior. diff --git a/.agents/commands/review.md b/.agents/commands/review.md index c2c23a5f7..a867491fd 100644 --- a/.agents/commands/review.md +++ b/.agents/commands/review.md @@ -1,59 +1,83 @@ -# /review - Code Review Branch Commits +# /review - Review Branch Changes -Review all commits on the current branch since diverging from main. +Review every branch change since the merge base with current `origin/main`, including uncommitted work. -## Prerequisites +## Independence -**IMPORTANT**: A reviewer should not be the same "person" who wrote the code. Before starting, check if this is a fresh context/session: +The reviewer must not be the agent that wrote the changes. If this session implemented or materially shaped the diff, use one fresh reviewer: Sol at high reasoning for general work or Astra for a focused difficult crypto-correctness review. Give it the actual changed-file list, applicable rules, and current verification evidence. Do not create extra reviewers unless the diff has genuinely independent domains that one reviewer cannot cover well. -- **If there is prior conversation history in this session** (e.g., you helped write the code being reviewed), do NOT review it yourself — your context is biased. Instead, spawn a fresh reviewer: - - Launch a subagent (synchronously — `run_in_background: false`) with a prompt telling it to perform the full review defined in the **Instructions** section below on the current branch, and to return its findings as: a summary, positives, and a severity-ranked list of issues (each with `file:line`, description, and a proposed action). Paste the Instructions criteria into the prompt so the subagent doesn't need to re-read this file. - - Pick the subagent type by what the diff actually touches: `crypto-specialist` for crypto/algorithm changes, `cpp-specialist` for `cpp/`, `typescript-specialist` for TS-only changes, `general-purpose` otherwise. Spawn more than one in parallel when the diff spans domains. - - **Scope the prompt to THIS branch's actual changes, not the generic template.** Before spawning, run `git diff --stat origin/main...HEAD` (three dots — see step 3) and put the concrete context into the prompt: what the branch does, which subsystem it touches (this repo spans C++/OpenSSL under `packages/react-native-quick-crypto/cpp`, the TypeScript package under `src/`, the Expo config plugin, the `example/` RN app and its test suites, `docs/`, and CI workflows — name the ones actually changed), and the list of changed files. Tell the subagent to open and review **every** changed file, including non-C++ ones (`.ts`, `.tsx`, podspec, Gradle, `.github/workflows`, `.agents/`), and to validate **each** changed toolchain rather than assuming one check covers the diff. - - The subagent starts with a clean context and did NOT write the code, so its review is unbiased. - - When it returns, relay its review to the user verbatim, then run the **Follow-up** fix-plan step yourself (the subagent can't interact with the user). -- **If this is a fresh context** (no prior history — you did not write this code), perform the review directly. +Local review is required and is not contingent on CodeRabbit or any other bot existing or finishing. ## Instructions -When activated, perform a full code review of the commits since branching from main: +### 1. Establish accurate scope -1. **Sync the base**: Run `git fetch origin` first. Local `main` is often stale (a PR merged upstream but not pulled locally), which silently drags already-merged commits into the review scope and balloons the diff. Use `origin/main` as the base for everything below. -2. **Get the commits**: Run `git log origin/main..HEAD --oneline` to see all commits on this branch -3. **Get the full diff**: Run `git diff origin/main...HEAD` to see all changes. **Three dots.** For `diff`, two dots compares the two endpoints, so anything merged into `origin/main` since the branch point shows up as an inverse diff — as if this branch deleted it. Three dots diffs against the merge-base, which is what you want. Note that step 2's `git log` takes **two** dots: the same syntax means different things for `log` and `diff`. -4. **Also check the working tree**: run `git status --short` and `git diff`. Uncommitted changes are in scope — review them alongside the commits, and say which findings apply to uncommitted work. -5. **For each file changed**, read enough context to understand the changes -6. **Review for**: - - Correctness and logic errors - - Consistency with existing patterns in the codebase - - TypeScript best practices - - C++ best practices (if touching native code) - - Cryptographic correctness (if touching crypto code) - - Potential bugs or edge cases - - Missing error handling - - Code clarity and maintainability -7. **Provide a structured review** with: - - Summary of what the branch does - - Positives (what's done well) - - Issues & suggestions (ranked by severity) - - Recommended actions (if any) +```bash +git fetch origin +git log origin/main..HEAD --oneline +git diff --stat origin/main...HEAD +git diff --name-only origin/main...HEAD +git diff origin/main...HEAD +git status --short +git diff +git diff --staged +``` -Verify the toolchains the diff actually touches: `bun tsc` for TypeScript, `bun run test` (in `packages/react-native-quick-crypto` — `run` matters, bare `bun test` is Bun's own runner, not the package's jest) if node-side code changed, `clang-format --dry-run --Werror` for C++. C++ runtime behavior and example-app test suites can only be validated by the user running `bun ios` / `bun android` — flag that rather than claiming it passes. +Use two dots for the commit list and three dots for the branch diff. Treat uncommitted and staged changes as part of the review and label findings that apply to them. -## Follow-up +### 2. Read every changed file -After presenting the review, present a **fix plan table** for the user to approve before making any changes: +Open every changed file with enough surrounding context to understand the behavior. Include TypeScript, C++, Nitro specifications/generated bindings, package metadata, podspec/Gradle/CMake, example-app tests, scripts, CI, documentation, and `.agents/` files when present. -| # | Severity | File:Line | Issue | Proposed Action | -| --- | -------- | ------------------ | ----------------- | ---------------- | -| 1 | Medium | path/to/file.ts:42 | Brief description | Fix / Skip / Ask | +Review for: -- **Fix**: Will apply the change -- **Skip**: Not worth changing (explain why) -- **Ask**: Ambiguous, needs user input on approach +- Correctness, edge cases, and error handling. +- Consistency with existing repository patterns. +- WebCrypto and Node.js compatibility. +- Nitro boundary and generated-code consistency. +- TypeScript strictness and public API shape. +- C++20 ownership, RAII, and memory safety. +- OpenSSL 3.6+ EVP/provider usage and checked return values. +- Cryptographic correctness, constant-time behavior, secret handling, nonce discipline, and authoritative vectors. +- Build, packaging, and platform-specific delivery impact. +- Test adequacy and whether evidence covers the current SHA. -**Wait for the user to approve the plan** (they may want to skip or modify items). They may reply with "approve" / "approve all" to accept everything, override individual rows ("skip #3", "fix #5 differently"), or ask clarifying questions. +### 3. Verify each changed toolchain -Once approved, apply only the approved fixes, then re-run the same toolchain checks to verify everything is clean. +Reuse evidence only when it names the commit SHA, exact tool or test, result, and platform, and no relevant later edit invalidated it. Request or run missing scoped checks. -Then commit the approved fixes (via `/commit`) — don't leave review changes sitting in the working tree. Commit only; pushing and opening PRs still need explicit permission. +- TypeScript: relevant `bun tsc`, lint, and formatting checks. +- C++: `clang-format --dry-run --Werror` over the changed native scope plus relevant compile or OpenSSL checks. +- ncrypto/OpenSSL: `scripts/check-ncrypto-openssl-deprecations.sh` when applicable. +- Node-side code: `cd packages/react-native-quick-crypto && bun run test`. Run this only for actual Node-side changes; never use bare `bun test` as a substitute. +- Native runtime: build, install, and exercise the affected example-app behavior on the relevant iOS or Android platform when feasible. For targeted debugging, attach to an existing RNQC app and Metro first and use `/tmp/rnqc-metro.log`. For canonical full-app coverage, use the root `bun run e2e:ios` then `bun run e2e:android` flow documented in `docs/local-e2e.md`; its runner owns the app, device, isolated Metro port, and cleanup. +- Docs-only: validate links, paths, command names, and repository claims; do not rerun runtime suites. + +Do not repeat a broad suite merely because review started. A full foundational shared-crypto suite needs a stated cross-cutting reason or concrete unexplained failure, one owner, and a reusable result. + +Review may reuse current raw E2E evidence even before final attestation. Do not treat logs or raw results as a signed merge-gate receipt. After all review fixes and documentation or plan commits, delivery must attest the exact final clean committed HEAD with the trusted inputs and pinned patched producer described in `docs/local-e2e.md`. Do not claim GitHub ran the device suites or that the status context is currently required unless live ruleset verification proves it. + +### 4. Report findings + +Return: + +1. Summary of the branch. +2. Positives. +3. Severity-ranked findings with `file:line`, impact, evidence, and proposed action. +4. Verification coverage and explicit gaps. + +Then print the decision table before editing: + +| # | Severity | File:Line | Finding | Decision | Rationale | +|---|---|---|---|---|---| +| 1 | Medium | `path/file.ts:42` | Brief finding | Fix / Skip / Ask | Why | + +- **Fix:** A validated issue with a clear repository-consistent correction. +- **Skip:** Not valid, stale, already covered, or not worth changing; explain why. +- **Ask:** Two defensible choices lead to materially different behavior or blast radius and the repository cannot decide. + +Apply every clear Fix immediately after printing the table. Do not wait for approval when there are no Ask items. If Ask items exist, apply independent Fix items and run their checks before asking only the genuine choices. Never turn naming, factoring, or a discoverable convention into an Ask. + +When `/review` is called from `/implement`, `/implement` owns the follow-through and no additional approval round is added. + +After fixes, rerun only invalidated scoped checks and commit them through `/commit`. Never push unless the user invoked a workflow that authorizes it. diff --git a/.agents/rules/architecture.md b/.agents/rules/architecture.md index 6318721d8..f3e5d81ec 100644 --- a/.agents/rules/architecture.md +++ b/.agents/rules/architecture.md @@ -21,12 +21,19 @@ Always on. - Avoid comments unless the code is complex enough to need them. - Tests run in the example React Native app, not a standard Node.js runner. +## ncrypto fork maintenance + +- Keep ncrypto as a Git submodule pointing to `boorad/ncrypto`. +- Keep the fork's `main` identical to `nodejs/ncrypto:main`. +- Maintain RNQC's compatibility changes as one commit on a separate branch based on upstream `main`; pin that commit in RNQC. +- Do not merge RNQC's compatibility branch into the fork's mirrored `main`. Preserve a backup ref before rewriting published history. + ## References - `$REPOS/node`: Node.js crypto/subtle reference. - `$REPOS/ncrypto`: OpenSSL abstraction and Node-derived crypto utilities. - `$REPOS/nitro`: Nitro bridging examples and iOS CI caching. -- `$REPOS/spicy`: Android E2E and Maestro workflow examples. +- `$REPOS/spicy`: shared agent-workflow and Android E2E patterns only; RNQC's canonical runner remains the repository-local flow documented in `docs/local-e2e.md`. - Use local Nitro llms docs when available. ## Output diff --git a/.agents/rules/ci-caching.md b/.agents/rules/ci-caching.md index d78d8414b..6aaa7994c 100644 --- a/.agents/rules/ci-caching.md +++ b/.agents/rules/ci-caching.md @@ -5,7 +5,7 @@ Use when editing GitHub Actions or CI caching. ## References - `$REPOS/nitro`: fast iOS build caching, especially `.github/workflows/build-ios.yml`. -- `$REPOS/spicy`: Android E2E and Maestro patterns. +- `$REPOS/spicy`: historical Android E2E and caching patterns only; do not replace RNQC's repository-local runner or import Spicy services and scripts. ## Blocking @@ -30,11 +30,6 @@ Pods: runner.os-pods-${{ hashFiles('example/ios/Podfile.lock', 'example/Gemfile. DD: runner.os-dd-${{ hashFiles('...lockfiles...') }}-xcode26.2 ``` -## Android Maestro - -- Do not launch the app with `adb` before Maestro. -- Install the APK, then let Maestro run `launchApp`. - ## Debugging ```bash diff --git a/.agents/rules/git-safety.md b/.agents/rules/git-safety.md index 1c271dc77..4d816fe13 100644 --- a/.agents/rules/git-safety.md +++ b/.agents/rules/git-safety.md @@ -7,6 +7,7 @@ - If hooks fail, fix the underlying issue. - Use a 120000ms timeout for `git commit`; hooks run lint-staged, clang-format, tsc, and bob build. - Never commit on `main`. +- Prefer linear history: rebase feature branches and use squash or fast-forward integration. Do not create merge commits unless the user explicitly requests them. - Before committing, check the current branch. - If on `main`, create `feat/`, `fix/`, or `refactor/` branch first. diff --git a/.agents/rules/test-verification.md b/.agents/rules/test-verification.md index 380abdd9f..66adf9851 100644 --- a/.agents/rules/test-verification.md +++ b/.agents/rules/test-verification.md @@ -1,24 +1,53 @@ # Test Verification Rules -## Strict +## Evidence standard -Tests run only in the example React Native app. For runtime changes the assistant cannot fully validate, commit locally and wait for the user to run `bun ios` or `bun android` and exercise the relevant suite before pushing. +Select verification from the actual diff, changed behavior, and affected dependencies. Record reusable evidence with: -## Applies When +- Commit SHA. +- Exact command, tool, test, or driven flow. +- Result. +- Platform, simulator, or device when native behavior is involved. -- C++ changes need the example app. -- Behavior changes are covered by example-app tests. -- New example-app tests were added and not run. -- A previous pushed fix failed user validation. +Evidence remains current until a relevant edit or failure invalidates it. Reuse it across phases, review, commit, and PR preparation instead of repeating broad checks. -## Do Not Push Until +## Targeted checks -- User explicitly confirms tests pass, all green, ship it, or equivalent. -- If tests fail, add follow-up commits locally and keep waiting. -- Once confirmed, push all validated commits together. +- TypeScript changes: relevant `bun tsc`, lint, and formatting checks. +- C++ changes: formatting plus affected compile, OpenSSL, native build, and runtime checks. +- ncrypto/OpenSSL compatibility: `scripts/check-ncrypto-openssl-deprecations.sh` when in scope. +- Actual Node-side implementation or test changes: `cd packages/react-native-quick-crypto && bun run test`. Bare `bun test` is Bun's runner and does not execute the package's Jest script. +- Native behavior: build, install, and exercise the affected example-app path on iOS or Android. +- Pure documentation, plans, and `.agents/` configuration: validate links, file paths, commands, and repository claims; no runtime retest. -## Exceptions +Do not routinely run every test suite after each phase, commit, review, or documentation edit. A full foundational shared-crypto suite is appropriate only for a cross-cutting crypto/harness change or a concrete unexplained failure. State the reason before running it, assign one owner, and reuse the result while it remains current. -- Pure docs, plans, or `.agents/` config changes. -- User explicitly says to push/ship now. -- First PR push from an unpushed branch; still ask first if unverified runtime changes are included. +## Native app authority + +Agents may run native builds, simulators or devices, app tests, and driven verification. A genuinely current successful result qualifies without a separate user passphrase or approval round. + +For targeted interactive work, attach to an existing RNQC app and Metro first. Do not restart or kill another project's process and do not take over its port. If a native change requires rebuilding, use the example app's real scripts, such as `cd example && bun ios`, `bun android`, `bun run build:ios`, or `bun run build:android`, then run the relevant app flow. + +For canonical full-app qualification, run `bun run e2e:ios` and then `bun run e2e:android` from the repository root. The wrappers invoke `example/test/e2e/runner.mjs`, which selects the configured platform target, creates and owns its RNQC simulator or emulator, uses an isolated Metro port, writes per-run evidence, and cleans up its resources. Do not point it at another project's app, reuse an overlapping server, or substitute a Maestro flow. + +RNQC Metro client logs are tee'd to `/tmp/rnqc-metro.log`. Diagnose failures with: + +```bash +grep -E "FAIL|❌|failed" /tmp/rnqc-metro.log | tail -20 +``` + +## Delivery boundary + +Unverified runtime behavior blocks push or PR delivery when failure could require changing the diff. Missing credentials, unavailable hardware, or irreversible external actions qualify only when they affect that decision. + +The user may explicitly direct shipment despite a gap. In that case, disclose the exact unverified behavior, affected platform, and residual risk in the handoff and PR. Do not describe it as passing. + +## Attested native qualification + +When the native merge gate applies, `docs/local-e2e.md` is canonical. Produce the final attestation with the trusted recipe, policy, and registry from `main` and the documented pinned, patched AgentSCM build, not an arbitrary release binary. The signing key and state stay owner-private and outside the checkout; never read or print secrets. + +Raw platform evidence may remain useful through review while no relevant edit invalidates it, but it is not the delivery attestation. The final attestation must cover the exact clean committed HEAD after every plan move, documentation commit, and fix, binding its tree, base ref, and merge-base. A later base fast-forward alone does not invalidate a receipt when the bound merge-base and other context remain unchanged. + +The producer owns one serial iOS-then-Android recipe run; do not add a duplicate broad suite immediately beforehand. Never create an attestation from logs or raw test output, never post a status manually, and post the actual attestation only through the documented CLI when the active workflow or user authorizes posting. Before posting, verify the pull request remote head equals the signed SHA. Screenshot publication is separate and requires explicit authorization when it is material. + +`agentscm/local-validation` represents a signed AgentSCM `worker_asserted` record with the coverage and limitations documented in `docs/local-e2e.md`; it does not mean GitHub ran the mobile suites. Do not claim the context is enforced by branch protection unless the live ruleset has been verified; the documented rollout says it is not yet required. diff --git a/.github/workflows/validate-cpp.yml b/.github/workflows/validate-cpp.yml index 313186991..0e92220f9 100644 --- a/.github/workflows/validate-cpp.yml +++ b/.github/workflows/validate-cpp.yml @@ -6,15 +6,23 @@ on: - main paths: - '.github/workflows/validate-cpp.yml' + - '.gitmodules' - 'packages/react-native-quick-crypto/android/src/main/cpp/**' - 'packages/react-native-quick-crypto/cpp/**' + - 'packages/react-native-quick-crypto/deps/ncrypto' + - 'packages/react-native-quick-crypto/deps/ncrypto/**' - 'packages/react-native-quick-crypto/nitrogen/generated/shared/**' + - 'scripts/check-ncrypto-openssl-deprecations.sh' pull_request: paths: - '.github/workflows/validate-cpp.yml' + - '.gitmodules' - 'packages/react-native-quick-crypto/android/src/main/cpp/**' - 'packages/react-native-quick-crypto/cpp/**' + - 'packages/react-native-quick-crypto/deps/ncrypto' + - 'packages/react-native-quick-crypto/deps/ncrypto/**' - 'packages/react-native-quick-crypto/nitrogen/generated/shared/**' + - 'scripts/check-ncrypto-openssl-deprecations.sh' env: # Opt actions still on Node 20 (e.g. reviewdog/action-cpplint) into the runner's Node 24. @@ -34,13 +42,41 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 - - name: Set up clang-format - run: sudo apt-get install -y clang-format + - name: Initialize ncrypto submodule + run: git submodule update --init --depth 1 packages/react-native-quick-crypto/deps/ncrypto + - name: Set up native validation + run: sudo apt-get install -y build-essential clang-format perl pkg-config + - name: Build OpenSSL 3.6.2 + env: + OPENSSL_VERSION: 3.6.2 + OPENSSL_SHA256: aaf51a1fe064384f811daeaeb4ec4dce7340ec8bd893027eee676af31e83a04f + run: | + openssl_archive="openssl-${OPENSSL_VERSION}.tar.gz" + curl --fail --location --silent --show-error \ + --output "$RUNNER_TEMP/$openssl_archive" \ + "https://github.com/openssl/openssl/releases/download/openssl-${OPENSSL_VERSION}/$openssl_archive" + echo "$OPENSSL_SHA256 $RUNNER_TEMP/$openssl_archive" | sha256sum --check + tar --extract --gzip --file "$RUNNER_TEMP/$openssl_archive" --directory "$RUNNER_TEMP" + cd "$RUNNER_TEMP/openssl-${OPENSSL_VERSION}" + ./Configure \ + --prefix="$RUNNER_TEMP/openssl" \ + --openssldir="$RUNNER_TEMP/openssl/ssl" \ + --libdir=lib \ + no-shared \ + no-tests + make --jobs="$(nproc)" + make install_sw + echo "OPENSSL_ROOT_DIR=$RUNNER_TEMP/openssl" >> "$GITHUB_ENV" - name: Run clang-format check run: | - find packages/react-native-quick-crypto/cpp packages/react-native-quick-crypto/android/src/main/cpp \ + find packages/react-native-quick-crypto/cpp \ + packages/react-native-quick-crypto/android/src/main/cpp \ + packages/react-native-quick-crypto/deps/ncrypto/include \ + packages/react-native-quick-crypto/deps/ncrypto/src \ -regex '.*\.\(cpp\|hpp\|cc\|cxx\|h\)' \ -exec clang-format --style=file --dry-run --Werror {} + + - name: Reject ncrypto OpenSSL deprecations + run: scripts/check-ncrypto-openssl-deprecations.sh - uses: reviewdog/action-cpplint@9552c62f4bd516c1e3a6f84eae56bd864cc304c6 # v1.11.0 with: github_token: ${{ secrets.github_token }} diff --git a/.gitmodules b/.gitmodules index 5e87fa645..a2658a9e2 100644 --- a/.gitmodules +++ b/.gitmodules @@ -3,7 +3,7 @@ url = https://github.com/BLAKE3-team/BLAKE3.git [submodule "packages/react-native-quick-crypto/deps/ncrypto"] path = packages/react-native-quick-crypto/deps/ncrypto - url = https://github.com/nodejs/ncrypto.git + url = https://github.com/boorad/ncrypto.git [submodule "packages/react-native-quick-crypto/deps/simdutf"] path = packages/react-native-quick-crypto/deps/simdutf url = https://github.com/simdutf/simdutf.git diff --git a/AGENTS.md b/AGENTS.md index 7440bd8b1..c634c32ef 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,178 +1,115 @@ # React Native Quick Crypto - Agent Configuration -This project uses the **4-Layer Orchestra Architecture** for efficient multi-agent development. +This project uses agent workflows for repository work. `AGENTS.md` and `.agents/` are canonical; `CLAUDE.md` and `.claude` are symlink aliases for tools that expect Claude-style paths. -## Quick Reference +## Slash command dispatch -- **Simple tasks (1-2 files)**: Work directly, no orchestration needed -- **Complex tasks (3+ files)**: Use the orchestrator agent -- **Rules**: See `.agents/rules/*.md` for architectural constraints -- **Agents**: See `.agents/agents/*.md` for specialist definitions -- **Commands**: Load `.agents/commands/*.md` before handling command-style requests +When a user prompt begins with `/name`, read `.agents/commands/name.md` completely before planning or taking any task action, then follow it as the authoritative end-to-end workflow. The `.claude/commands/` path resolves to the same files through the `.claude` symlink. -## Command Instructions +If that exact command file is missing, search `.agents/commands/` for a documented alias and any known canonical source before acting. If none exists, flag the absence; do not silently invent a partial workflow from memory. -Agents must read the relevant command definition in `.agents/commands/` before executing any slash-command style request. At minimum, load all files in `.agents/commands/` early in the session so commands such as `/commit`, `/pr`, `/review`, and `/address-pr-feedback` follow the repo-specific workflow. +Load the repository rules relevant to the requested area. For command-style work, inventory `.agents/commands/` early so aliases and related workflows are not missed. -## Critical Principles +## Repository priorities -### 1. API Priority Order (NON-NEGOTIABLE) +### API priority order (non-negotiable) -When implementing features, favor in this order: +When implementing features, favor these sources in order: -1. **WebCrypto API** - Modern standard, best for `subtle.*` methods -2. **Node.js Implementation** - Use `$REPOS/node/deps/ncrypto` as reference -3. **ncrypto** - submodule code reference at `$REPOS/ncrypto` (do work w/ OpenSSL) +1. WebCrypto API for modern `subtle.*` methods. +2. Node.js `$REPOS/node/deps/ncrypto` for `crypto.*` compatibility and implementation patterns. +3. `$REPOS/ncrypto` as the standalone ncrypto and OpenSSL reference. -**Always check Node.js `deps/ncrypto` before implementing new features.** +Always inspect Node.js `deps/ncrypto` before implementing new crypto behavior, then adapt it to OpenSSL 3.6+ requirements. -### 2. Modern Stack Required +### Required stack -- **React Native** - Mobile framework -- **TypeScript** - Type system (strict mode, no `any`) -- **Nitro Modules** - Native bridging -- **C++20 or higher** - Modern C++ (smart pointers, RAII) -- **OpenSSL 3.6+** - Cryptographic library (EVP APIs only) -- **Bun 1.3+** - TypeScript package manager +- React Native. +- TypeScript in strict mode with no `any`. +- Nitro Modules for native bridging. +- C++20 or newer with smart pointers and RAII. +- OpenSSL 3.6+ EVP/provider APIs only. +- Bun 1.3+ for package management and scripts. -### 3. Code Philosophy +### Code philosophy -- Minimize code rather than add more -- Prefer iteration and modularization over duplication -- No comments unless code is sufficiently complex -- Code should be self-documenting +- Minimize code and avoid duplication. +- Prefer small, independently verifiable changes. +- Keep code self-documenting; comment only when the behavior is complex enough to require it. +- Preserve the existing crypto, Nitro, TypeScript, and C++ rules in `.agents/rules/`. -### 4. Never Commit to Main +### Security -- **ALWAYS** create a feature branch before the first commit -- Branch naming: `feat/<name>`, `fix/<name>`, `refactor/<name>` -- All changes go through PRs — never push directly to main -- If you find yourself on main, create a branch before committing +- Use constant-time comparisons such as `CRYPTO_memcmp()` for authentication material. +- Use `RAND_bytes()` and check its return value. +- Prefer authenticated encryption such as AES-GCM. +- Never expose key material in errors or logs. +- Validate against authoritative WebCrypto, Node.js, NIST, or RFC vectors as applicable. -### 5. Security is Critical +## Branch and delivery safety -- Constant-time comparisons for authentication tags -- Cryptographically secure randomness (RAND_bytes) -- AEAD modes preferred (AES-GCM) -- No key material in errors/logs -- Validate against test vectors (NIST, RFC, Node.js) +- Never commit on `main`; create a `feat/`, `fix/`, or `refactor/` branch first. +- Never use `--no-verify` for commits or pushes. +- Preserve unrelated working-tree changes and stage task files explicitly. +- All changes land through pull requests. +- Prefer linear history. Rebase feature branches and use squash or fast-forward integration; do not create merge commits unless explicitly requested. If rewriting a dependency commit changes its SHA, update its downstream pins. +- `/implement` is explicitly authorized to push a qualified branch and create or update its PR. `/pr` is explicitly authorized to make the qualified push needed to create or update the PR. Standalone `/commit` never pushes implicitly. -## Rules Summary +## Plans -For full details, see `.agents/rules/*.md`: +New `/implement` work uses `plans/todo/<N>-<slug>.md` as the live tracker, including phases, decisions, assumptions, and verification evidence. Do not create a retroactive plan merely to make an already-running branch look as though it followed the workflow. -### architecture.md +Before opening a PR for completed planned work, move the one exact matching plan to `plans/done/` in the same branch and PR. Carry genuinely outstanding verification items with an owner. Never fuzzy-match plan names. Remove the ignored `.agents/progress/claude-progress.md` stub when its plan moves so later sessions do not inherit stale state. -- Project context and goals -- API priority order (WebCrypto → Node.js → ncrypto) -- Tech stack requirements -- Code philosophy -- Testing context (RN environment) -- Local codebase references +## Agent and model routing -### code-typescript.md +- Bounded implementation and routine verification: Sol at its default reasoning effort. +- General independent review and an implementation retry: Sol at high reasoning effort. +- Initial `/implement` recon, difficult design, and focused crypto correctness review: Astra. +- Explicit user model choices and live provider capabilities override these defaults. +- Documentation selects models for delegated work; it does not switch the active thread's model. +- Do not silently invoke separately billed tools. Use no more agents than the work requires, avoid duplicate research, and keep handoffs concise. +- Use early parallel work only for genuinely independent structural discovery. Implementation phases that share files or assumptions run sequentially with fresh context and bounded retries. -- No `any` or `unknown` casts -- Interfaces over types -- Named exports only (no default) -- No enums (use union types) -- Explicit return types -- Minimal, self-documenting code -- React best practices (minimal useEffect) +## Verification agreements -### code-cpp.md +- Select checks from the actual diff, changed behavior, and affected dependencies. Record reusable evidence with the commit SHA, exact tool or test, result, and platform. +- Reuse still-current evidence across phases, review, and PR preparation. Do not repeat a broad suite after every phase, review, documentation edit, or commit. +- A full foundational shared-crypto suite is justified only by a cross-cutting crypto/harness change or concrete unexplained failure. State the reason first, assign one owner, and reuse its result until relevant edits invalidate it. +- TypeScript changes use the relevant `bun tsc`, lint, and formatting scripts. +- Run the package Jest suite only for actual Node-side code changes: `cd packages/react-native-quick-crypto && bun run test`. Bare `bun test` invokes Bun's test runner and is not this package's Jest script. +- C++ changes use formatting plus the relevant native/compiler checks, including `scripts/check-ncrypto-openssl-deprecations.sh` when ncrypto/OpenSSL compatibility is in scope. +- Native runtime behavior is tested in the example React Native app. Agents may build, install, drive, and test the app; user confirmation is not inherently required when current successful evidence is available. +- For targeted interactive debugging, attach to the existing RNQC app and Metro process first. Do not restart another project's process or take over its port. Metro client logs belong at `/tmp/rnqc-metro.log`; inspect them with `grep -E "FAIL|❌|failed" /tmp/rnqc-metro.log | tail -20` when diagnosing failures. +- For canonical full-app qualification, run `bun run e2e:ios` and then `bun run e2e:android` from the repository root. The runner owns its RNQC app, simulator or emulator, isolated Metro port, artifacts, and cleanup; do not substitute another project's app or an overlapping manually managed server. +- When the native merge gate applies, follow `docs/local-e2e.md`: use the trusted recipe, policy, and registry from `main` with the pinned patched AgentSCM producer; sign the exact clean committed HEAD, tree, base ref, and merge-base with owner-private key and state outside the checkout. Never fabricate an attestation from logs or raw test results and never post the status manually. +- Reuse still-current raw evidence during implementation and review, but the final delivery attestation must bind the final committed HEAD after plan moves, documentation commits, review fixes, and other changes. Its `agentscm/local-validation` context is worker-asserted evidence, not a claim that GitHub ran the mobile suites, and it is not currently a required branch-protection check unless live settings are separately verified. +- Pure documentation, plan, and `.agents/` changes do not require runtime retesting. +- Unverified runtime behavior that could change the diff blocks push/PR delivery unless the user explicitly directs shipment; disclose the unverified behavior and residual risk when they do. -- C++20 minimum with modern features -- Smart pointers for all ownership -- OpenSSL 3.6+ EVP APIs only (no deprecated) -- RAII for all resources -- Proper error handling (ERR_get_error) -- Memory safety (no leaks, no raw ownership) +## Real hooks and scripts -### crypto-security.md +The tracked pre-commit hook runs `bun lint-staged`, a C++ `clang-format --dry-run --Werror` scan, `bun tsc`, and `bun --filter="react-native-quick-crypto" prepare`. Allow at least 120 seconds for `git commit` and fix hook failures rather than bypassing them. -- Cryptographic correctness (match specs) -- No timing attacks (CRYPTO_memcmp) -- Secure RNG (RAND_bytes) -- Authenticated encryption (AEAD) -- Proper IV/nonce handling (never reuse) -- Minimum key sizes -- No key material in errors +Useful scripts and flows include: -### ci-caching.md +- Root checks: `bun tsc`, `bun lint`, `bun format`. +- Node-side Jest: `cd packages/react-native-quick-crypto && bun run test`. +- Example app: `cd example && bun ios` or `bun android`. +- Explicit native builds: `cd example && bun run build:ios` or `bun run build:android`. +- Full app E2E when justified: from the repository root run `bun run e2e:ios` and then `bun run e2e:android`; the workspace wrappers invoke the Node runner. See `docs/local-e2e.md` for attested qualification and its coverage limits. -- iOS Pods/DerivedData cache consistency (exact-match Pods, no restore-keys) -- Cache key design (no version suffixes, use hashFiles) -- Android Maestro patterns (don't launch app before Maestro) -- Reference implementations (Nitro for iOS, Spicy for Android) +## Local references -## When to Use Orchestration +- `$REPOS/node`: Node.js crypto and ncrypto reference. +- `$REPOS/ncrypto`: standalone OpenSSL abstraction and Node-derived utilities. +- `$REPOS/nitro`: Nitro bridging examples and iOS CI caching patterns. +- `$REPOS/spicy`: shared agent-workflow and Android E2E patterns only; do not import Spicy services, Jazz assumptions, golf domain rules, or scripts into RNQC. -### Use Orchestrator For: +## Quality checklist -- ✅ Tasks touching 3+ files -- ✅ Cross-language changes (TypeScript + C++) -- ✅ New crypto features (API + implementation) -- ✅ Complex refactoring - -### Work Directly For: - -- ✅ Single file changes -- ✅ Simple bug fixes -- ✅ Type updates -- ✅ Documentation - -## Available Specialists - -- **orchestrator**: Decomposes complex tasks, coordinates specialists -- **typescript-specialist**: TypeScript API, types, Nitro bindings -- **cpp-specialist**: C++ implementation, OpenSSL integration -- **crypto-specialist**: Algorithm correctness, security review -- **testing-specialist**: Test strategy, test vectors, validation - -## Local Codebase References - -Use these instead of web searches: - -- **Node.js**: `$REPOS/node` - - - `deps/ncrypto` - Use as bible for crypto operations - - May need updating to OpenSSL 3.6+ patterns - -- **ncrypto**: `$REPOS/ncrypto` - - - separate crypto lib broken out from Node.js - - Patterns and tools to access OpenSSL - -- **Nitro**: `$REPOS/nitro` - - - iOS CI caching patterns (super-fast builds) - - Nitro Modules bridging examples - -- **Spicy**: `$REPOS/spicy` - - Android E2E patterns with Maestro - - Separate build/test workflow - -## Testing - -Tests run in the React Native example app environment, not standard Node.js test runners. - -Don't ask to run tests - they must be executed in the example React Native application. - -### Metro Logs - -Metro output is tee'd to `/tmp/rnqc-metro.log`. When debugging test failures, read this file to see console output including test pass/fail results. Use `grep -E "FAIL|❌|failed" /tmp/rnqc-metro.log | tail -20` to quickly find failures. - -## Quality Checks - -Before committing: - -- [ ] Type safety (no `any`, proper interfaces) -- [ ] Memory safety (smart pointers, RAII) -- [ ] Cryptographic correctness (test vectors) -- [ ] Security properties (constant-time, secure RNG) -- [ ] Code quality (minimal, modular, self-documenting) - ---- - -**For specialist details and orchestration patterns, see `.agents/agents/*.md` and `.agents/rules/*.md`** +- Type safety: no `any`; validate dynamic shapes. +- Memory safety: RAII, smart-pointer ownership, no leaks or invalid access. +- Cryptographic correctness: spec behavior, edge cases, and authoritative vectors. +- Security properties: constant-time comparisons, secure randomness, nonce discipline, and no secret leakage. +- Delivery evidence: checks match the actual diff and all claimed runtime behavior is verified or explicitly disclosed. diff --git a/docs/local-e2e.md b/docs/local-e2e.md index ee2a11259..9f0b6e47e 100644 --- a/docs/local-e2e.md +++ b/docs/local-e2e.md @@ -73,6 +73,7 @@ Run only reviewed code on the signing host. The private key and state directory ```bash git fetch origin main git status --short +git diff --exit-code origin/main -- .github/local-validation/recipe.json .github/local-validation/policy.json .github/local-validation/registry.json mkdir -m 700 /absolute/private/path/rnqc-attestations /tmp/rnqc-agentscm-24b70c0 local-validation run \ @@ -87,7 +88,7 @@ mkdir -m 700 /absolute/private/path/rnqc-attestations --base-rev origin/main ``` -`git status --short` must print nothing before `run`. Save the `envelope_sha256` from its JSON output as `ATTESTATION`. AgentSCM retains the signed envelope, record and two commands' stdout/stderr under the state directory. A successful run contains both results; a failed iOS command intentionally omits Android and verifies as failure. +`git status --short` must print nothing before `run`, and the trust-input comparison must exit successfully. Checkout-relative recipe, policy, and registry paths are safe here only because they exactly match fetched `origin/main`. If the PR changes those inputs, stop; their trusted default-branch update must be reviewed and landed first. Save the `envelope_sha256` from its JSON output as `ATTESTATION`. AgentSCM retains the signed envelope, record and two commands' stdout/stderr under the state directory. A successful run contains both results; a failed iOS command intentionally omits Android and verifies as failure. Create an owner-private, single-line GitHub token file with permission to read the pull request and write its comments, then explicitly post the attestation: @@ -106,7 +107,7 @@ Create an owner-private, single-line GitHub token file with permission to read t Screenshot posting is separate because AgentSCM `local-validation post` carries only the signed envelope and record. The helper uploads to ImgBB using the same 30-day expiry as the removed hosted-E2E action and creates or updates one PR comment bound to the PR head and attestation digest. It does nothing without the explicit `--post` flag. -Use the two run directories printed by the E2E runner: +Before uploading, repeat the fetch and trust-input comparison above; stop on any mismatch. The helper reads checkout-relative trust inputs, so this check is required even when reusing an existing attestation. Use the two run directories printed by the E2E runner: ```bash ./scripts/local-validation/post-screenshots.sh \ diff --git a/example/ios/Podfile.lock b/example/ios/Podfile.lock index 4373aca29..06ee2a2df 100644 --- a/example/ios/Podfile.lock +++ b/example/ios/Podfile.lock @@ -2837,7 +2837,7 @@ SPEC CHECKSUMS: MMKVCore: f2dd4c9befea04277a55e84e7812f930537993df NitroMmkv: afbc5b2fbf963be567c6c545aa1efcf6a9cec68e NitroModules: 11bba9d065af151eae51e38a6425e04c3b223ff3 - QuickCrypto: 34c79e9b554ac964e4ebc42e3190abfa99099a40 + QuickCrypto: 5780aa6e5542e1e958fbece6813e1d63741b82b0 RCT-Folly: 846fda9475e61ec7bcbf8a3fe81edfcaeb090669 RCTDeprecation: c4b9e2fd0ab200e3af72b013ed6113187c607077 RCTRequired: e97dd5dafc1db8094e63bc5031e0371f092ae92a diff --git a/example/src/fixtures/keys/ec_explicit_oakley.ts b/example/src/fixtures/keys/ec_explicit_oakley.ts new file mode 100644 index 000000000..0c2e54f23 --- /dev/null +++ b/example/src/fixtures/keys/ec_explicit_oakley.ts @@ -0,0 +1,17 @@ +// Generated with OpenSSL 3.6.2 using `openssl ecparam -param_enc explicit` +// followed by `openssl pkey -pubout -outform DER`. These curves are the +// no-OID cases covered by Node.js test/parallel/test-crypto-keygen-missing-oid.js. +export const explicitOakleySpkiFixtures = [ + { + namedCurve: 'Oakley-EC2N-3', + spkiHex: + '3081cf3081a006072a8648ce3d0201308194020101301d06072a8648ce3d010230120202009b06092a8648ce3d0102030202013e302c041400000000000000000000000000000000000000000414000000000000000000000000000000000007338f042904000000000000000000000000000000000000007b00000000000000000000000000000000000001c8021402aaaaaaaaaaaaaaaaaac7f3c7881bd0868fa86c020103032a0004058af006890627abd13cc38f768f2a564a835f9104f6a17ab00869e638e91b8aa84d11581c7eae5a', + spkiLength: 210, + }, + { + namedCurve: 'Oakley-EC2N-4', + spkiHex: + '3081eb3081b406072a8648ce3d02013081a8020101301d06072a8648ce3d01023012020200b906092a8648ce3d01020302020145303404180000000000000000000000000000000000000000000000000418000000000000000000000000000000000000000000001ee904310400000000000000000000000000000000000000000000001800000000000000000000000000000000000000000000000d021800ffffffffffffffffffffffedf97c44db9f2420bafca75e02010203320004005401a9ba6b63deb137dbec67550ebbf8aa49426749dde600584de3e879e46f9653447922b4a266be0356d1fe5bde92', + spkiLength: 238, + }, +] as const; diff --git a/example/src/tests/keys/create_keys.ts b/example/src/tests/keys/create_keys.ts index 838f9d569..df7278aea 100644 --- a/example/src/tests/keys/create_keys.ts +++ b/example/src/tests/keys/create_keys.ts @@ -10,8 +10,13 @@ import { } from 'react-native-quick-crypto'; import type { JWK, KeyObject } from 'react-native-quick-crypto'; import { expect } from 'chai'; +import { explicitOakleySpkiFixtures } from '../../fixtures/keys/ec_explicit_oakley'; import { test, assertThrowsAsync, decodeHex } from '../util'; -import { rsaPrivateKeyPem, rsaPublicKeyPem } from './fixtures'; +import { + rsaPrivateKeyPem, + rsaPssPrivateKeyPem, + rsaPublicKeyPem, +} from './fixtures'; const SUITE = 'keys.createKey'; @@ -204,6 +209,22 @@ test(SUITE, 'createPublicKey EC P-256', async () => { expect(key.asymmetricKeyType).to.equal('ec'); }); +test(SUITE, 'exports explicit EC parameters without a curve OID', () => { + for (const { + namedCurve, + spkiHex, + spkiLength, + } of explicitOakleySpkiFixtures) { + const fixture = Buffer.from(spkiHex, 'hex'); + const key = createPublicKey({ key: fixture, format: 'der', type: 'spki' }); + const exported = key.export({ format: 'der', type: 'spki' }) as Buffer; + + expect(key.asymmetricKeyType, namedCurve).to.equal('ec'); + expect(exported.length, namedCurve).to.equal(spkiLength); + expect(Buffer.compare(exported, fixture), namedCurve).to.equal(0); + } +}); + test(SUITE, 'createPublicKey Ed25519', async () => { const { publicKey } = await new Promise<{ privateKey: string; @@ -358,6 +379,24 @@ async function generateRsaKeyPair(): Promise<{ }); } +async function generateEcKeyPair(): Promise<{ + privateKey: KeyObject; + publicKey: KeyObject; +}> { + return new Promise((resolve, reject) => { + generateKeyPair('ec', { namedCurve: 'P-256' }, (err, pubKey, privKey) => { + if (err) { + reject(err); + return; + } + resolve({ + privateKey: privKey as KeyObject, + publicKey: pubKey as KeyObject, + }); + }); + }); +} + test(SUITE, 'createPrivateKey with passphrase (PEM, PKCS8)', async () => { const { privateKey, publicKey } = await generateRsaKeyPair(); const passphrase = 'user-test'; @@ -414,6 +453,160 @@ test(SUITE, 'createPrivateKey passphrase as Buffer (PEM)', async () => { expect(imported.equals(privateKey)).to.equal(true); }); +test(SUITE, 'RSA PKCS1 private key PEM and DER round-trip', () => { + const privateKey = createPrivateKey(rsaPrivateKeyPem); + const publicKey = createPublicKey(privateKey); + const pem = privateKey.export({ format: 'pem', type: 'pkcs1' }) as string; + const der = privateKey.export({ format: 'der', type: 'pkcs1' }) as Buffer; + + expect(pem).to.match(/^-----BEGIN RSA PRIVATE KEY-----/); + expect(createPrivateKey(pem).equals(privateKey)).to.equal(true); + expect( + createPrivateKey({ key: der, format: 'der', type: 'pkcs1' }).equals( + privateKey, + ), + ).to.equal(true); + expect(() => + createPublicKey({ + key: Buffer.from([0x30, 0x00]), + format: 'der', + type: 'pkcs1', + }), + ).to.throw(); + expect( + createPublicKey({ key: der, format: 'der', type: 'pkcs1' }).equals( + publicKey, + ), + ).to.equal(true); +}); + +test(SUITE, 'RSA PKCS1 public-only key PEM and DER round-trip', () => { + const publicKey = createPublicKey(rsaPublicKeyPem); + const pem = publicKey.export({ format: 'pem', type: 'pkcs1' }) as string; + const der = publicKey.export({ format: 'der', type: 'pkcs1' }) as Buffer; + + expect(pem).to.match(/^-----BEGIN RSA PUBLIC KEY-----/); + expect(createPublicKey(pem).equals(publicKey)).to.equal(true); + expect( + createPublicKey({ key: der, format: 'der', type: 'pkcs1' }).equals( + publicKey, + ), + ).to.equal(true); +}); + +test( + SUITE, + 'RSA PKCS1 encrypted PEM accepts binary and empty passphrases', + () => { + const privateKey = createPrivateKey(rsaPrivateKeyPem); + const passphrases = [ + Buffer.from([0x61, 0x00, 0xff, 0x62]), + Buffer.alloc(0), + ]; + + for (const passphrase of passphrases) { + const pem = privateKey.export({ + format: 'pem', + type: 'pkcs1', + cipher: 'aes-256-cbc', + passphrase, + }) as string; + + expect(pem).to.include('Proc-Type: 4,ENCRYPTED'); + expect( + createPrivateKey({ key: pem, passphrase }).equals(privateKey), + ).to.equal(true); + + if (passphrase.length > 0) { + expect(() => createPrivateKey(pem)).to.throw('Passphrase required'); + expect(() => + createPrivateKey({ key: pem, passphrase: 'wrong' }), + ).to.throw('Failed to read'); + } + } + }, +); + +test(SUITE, 'EC SEC1 private key PEM and DER round-trip', async () => { + const { privateKey, publicKey } = await generateEcKeyPair(); + const pem = privateKey.export({ format: 'pem', type: 'sec1' }) as string; + const der = privateKey.export({ format: 'der', type: 'sec1' }) as Buffer; + const reimported = createPrivateKey({ + key: der, + format: 'der', + type: 'sec1', + }); + + expect(pem).to.match(/^-----BEGIN EC PRIVATE KEY-----/); + expect(createPrivateKey(pem).equals(privateKey)).to.equal(true); + expect(reimported.equals(privateKey)).to.equal(true); + expect(() => + createPublicKey({ + key: Buffer.from([0x30, 0x00]), + format: 'der', + type: 'sec1', + }), + ).to.throw(); + const reimportedPublic = createPublicKey({ + key: der, + format: 'der', + type: 'sec1', + }); + + for (const type of ['compressed', 'uncompressed'] as const) { + const originalPoint = publicKey.export({ + format: 'raw-public', + type, + }) as Buffer; + const reimportedPoint = reimportedPublic.export({ + format: 'raw-public', + type, + }); + expect(Buffer.compare(reimportedPoint, originalPoint)).to.equal(0); + } +}); + +test( + SUITE, + 'EC SEC1 encrypted PEM accepts binary and empty passphrases', + async () => { + const { privateKey } = await generateEcKeyPair(); + const passphrases = [ + Buffer.from([0x61, 0x00, 0xff, 0x62]), + Buffer.alloc(0), + ]; + + for (const passphrase of passphrases) { + const pem = privateKey.export({ + format: 'pem', + type: 'sec1', + cipher: 'aes-256-cbc', + passphrase, + }) as string; + + expect(pem).to.include('Proc-Type: 4,ENCRYPTED'); + expect( + createPrivateKey({ key: pem, passphrase }).equals(privateKey), + ).to.equal(true); + } + }, +); + +test(SUITE, 'RSA-PSS rejects traditional PKCS1 export', () => { + const privateKey = createPrivateKey(rsaPssPrivateKeyPem); + const publicKey = createPublicKey(privateKey); + + expect(privateKey.asymmetricKeyType).to.equal('rsa-pss'); + expect(publicKey.asymmetricKeyType).to.equal('rsa-pss'); + + expect(() => privateKey.export({ format: 'pem', type: 'pkcs1' })).to.throw( + 'pkcs1 can only be used for RSA keys', + ); + expect(() => publicKey.export({ format: 'pem', type: 'pkcs1' })).to.throw( + 'pkcs1 can only be used for RSA keys', + ); +}); + test( SUITE, 'createPrivateKey on encrypted PEM without passphrase throws Passphrase required', diff --git a/example/src/tests/keys/fixtures.ts b/example/src/tests/keys/fixtures.ts index 03232fb8c..c3ab0c393 100644 --- a/example/src/tests/keys/fixtures.ts +++ b/example/src/tests/keys/fixtures.ts @@ -37,3 +37,33 @@ xK2Nlm+ofI61tXO31YSXSd0cyw1v8xd0wJLJbtSg5X4jS9t79gLUeVSgOQses/t9 4vfFwn1MwYqQ252xNcMOamV1Q7qM7OYqJrUOxJ0OUQnqCZKF5PxjpSuOl9whzUOh owIDAQAB -----END PUBLIC KEY-----`; + +// Source: Node.js test/fixtures/keys/rsa_pss_private_2048.pem +export const rsaPssPrivateKeyPem = `-----BEGIN PRIVATE KEY----- +MIIEvAIBADALBgkqhkiG9w0BAQoEggSoMIIEpAIBAAKCAQEAy4OMdS84PlgI5CRL +bdbud9Ru7vprFr2YNNUmdT7D3YgApiv8CjzKXLiVDnbMET+lwmtag/EcZsxVCKov +su30pYASBriHOiMVYui9+ZaJoQ9yI6lOjG1RbuUBJXNSjHBJxqBqmcgZOb1mdRr/ +eXzpAMWJ3hfuLojU2+zUSJ3/rvepepcLFG2q9nA0+PJskJ7Pnh3L0ydnv3U3hduM +n5OVfm/Jx1FPyZpD184tJff+N+MY3s3hIcfuOnL9Pl4RPGeaTC4T1o460NaG6bG7 +c2Whg6NOaVgaFIaiNbrTTNCpVjeTyalsTXYlQQ3hiKjst0Q7pfFEkJDo8qiqLad1 +Msl59wIDAQABAoIBAQC6G8aqs0/f02nuGDLSc6cH9kCsUlz0ItW6GuJcfdVoFSNi +0v5d7lGwkSveWk0ryOSw8rOHzUqHx3xLvDZ6jpkXcBMMClu/kq3QEb8JK90YaKOc +cQvf52h83Pc7ZEatH1KYTcKudwp6fvXfSZ0vYEdD6WG2tHOgIollxSIsdjCHs1qi +7baNHdK9T4DveuEZNcZ+LraZ1haHmFeqIPcy+KvpGuTaLCg5FPhH2jsIkw9apr7i +iFLi+IJ7S5Bn/8XShmJWk4hPyx0jtIkC5r2iJnHf4x+XYWZfdo7oew3Dg6Pa7T6r +I164Nnaw0u0LvO4gQdvYaJ/j9A602nHTp7Tsq8chAoGBAOtVHgIqpmdzwR5KjotW +LuGXDdO9X6Xfge9ca2MlWH1jOj+zqEV7JtrjnZAzzOgP2kgqzpIR71Njs8wkaxTJ +Tle0Ke6R/ghU9YOQgRByKjqJfQXHZnYFPsMg0diNYLroJ4SG8LO4+2SygTYZ4eKL +qU0bda3QvQ7FL+rTNQBy01b9AoGBAN1jEQI80JxCT7AMvXE6nObIhbkASHte4yOE +1CBwcOuBEGcuvMOvQVMzKITgea6+kgsu4ids4dM5PTPapQgpKqIIQ2/eSesaf56g +73clGGSTPHJP0v+EfKg4+GYJf8o2swT0xDHkgWLgjjdsncB9hATc2j6DvHeau18d +pgCLz9kDAoGAXl/SGvhTp2UqayVnKMW1I07agrGNLA4II5+iiS4u4InskCNSNhr/ +KATj6TJ82AuTdCGGmdmLapuvPQzVzI42VsGvlzcA8wJvOwW2XIwMF1GPy8N9eZL8 +6m+89+Uqh4oWXvVmjgx+9JEJdFLI3Xs4t+1tMfll+AhoAPoWZUmnK1kCgYAvEBxR +iXQfg8lE97BeHcO1G/OxfGnsMCPBLT+bFcwrhGhkRv9B6kPM2BdJCB9WEpUhY3oY +P4FSUdy85UIoFfhGMdOEOJEmNZ/jrPq7LVueJd63vlhwkU2exV2o82QDLNWpvA7p +PFZ1Gp+hEKoIfaZPElQi7gZmtrIWaksb2pz42QKBgQCct9NP2qJfqeS4206RDnfv +M238/O2lNhLWdSwY0g+tcN+I1sGs3+4vvrm95cxwAmXZyIM11wjdMcAPNxibodY7 +vufsebPHDBA0j0yuTjGkXefUKd1GdO88i5fppzxB7prDX9//DsWWrFhIMMRNYe0Q +aeHd/NPuHcjZKcnaVBgukQ== +-----END PRIVATE KEY-----`; diff --git a/packages/react-native-quick-crypto/QuickCrypto.podspec b/packages/react-native-quick-crypto/QuickCrypto.podspec index 72abe7ee4..8e026e553 100644 --- a/packages/react-native-quick-crypto/QuickCrypto.podspec +++ b/packages/react-native-quick-crypto/QuickCrypto.podspec @@ -189,7 +189,7 @@ Pod::Spec.new do |s| xcconfig = { # C++ compiler flags, mainly for folly. - "GCC_PREPROCESSOR_DEFINITIONS" => "$(inherited) FOLLY_NO_CONFIG FOLLY_CFG_NO_COROUTINES", + "GCC_PREPROCESSOR_DEFINITIONS" => "$(inherited) FOLLY_NO_CONFIG FOLLY_CFG_NO_COROUTINES NCRYPTO_EVP_ONLY=1", # Set C++ standard to C++20 "CLANG_CXX_LANGUAGE_STANDARD" => "c++20", "CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES" => "YES", @@ -198,7 +198,7 @@ Pod::Spec.new do |s| # Disable x86 SIMD intrinsics on iOS simulator — the .c implementation files are already # excluded above, but blake3_dispatch.c still references the symbols unless these macros # are defined. Mirrors the Android CMakeLists.txt approach (line 18-22). - "GCC_PREPROCESSOR_DEFINITIONS[sdk=iphonesimulator*][arch=x86_64]" => "$(inherited) BLAKE3_NO_AVX512 BLAKE3_NO_AVX2 BLAKE3_NO_SSE41 BLAKE3_NO_SSE2" + "GCC_PREPROCESSOR_DEFINITIONS[sdk=iphonesimulator*][arch=x86_64]" => "$(inherited) BLAKE3_NO_AVX512 BLAKE3_NO_AVX2 BLAKE3_NO_SSE41 BLAKE3_NO_SSE2 NCRYPTO_EVP_ONLY=1" } # Every translation unit calls the renamed OpenSSL symbols. Missing a rename @@ -239,7 +239,7 @@ Pod::Spec.new do |s| "\"#{real_sodium_include}/sodium\"" ] xcconfig["HEADER_SEARCH_PATHS"] = (cpp_headers + sodium_headers).join(' ') - xcconfig["GCC_PREPROCESSOR_DEFINITIONS"] = "$(inherited) FOLLY_NO_CONFIG FOLLY_CFG_NO_COROUTINES BLSALLOC_SODIUM=1" + xcconfig["GCC_PREPROCESSOR_DEFINITIONS"] = "$(inherited) FOLLY_NO_CONFIG FOLLY_CFG_NO_COROUTINES BLSALLOC_SODIUM=1 NCRYPTO_EVP_ONLY=1" else xcconfig["HEADER_SEARCH_PATHS"] = cpp_headers.join(' ') end diff --git a/packages/react-native-quick-crypto/android/CMakeLists.txt b/packages/react-native-quick-crypto/android/CMakeLists.txt index 2bb708e66..4cb275971 100644 --- a/packages/react-native-quick-crypto/android/CMakeLists.txt +++ b/packages/react-native-quick-crypto/android/CMakeLists.txt @@ -72,6 +72,8 @@ add_library( ../deps/simdutf/src/simdutf.cpp ) +target_compile_definitions(${PACKAGE_NAME} PRIVATE NCRYPTO_EVP_ONLY=1) + # add Nitrogen specs include(${CMAKE_SOURCE_DIR}/../nitrogen/generated/android/QuickCrypto+autolinking.cmake) diff --git a/packages/react-native-quick-crypto/cpp/keys/KeyObjectData.cpp b/packages/react-native-quick-crypto/cpp/keys/KeyObjectData.cpp index 82147caeb..b34818ec5 100644 --- a/packages/react-native-quick-crypto/cpp/keys/KeyObjectData.cpp +++ b/packages/react-native-quick-crypto/cpp/keys/KeyObjectData.cpp @@ -181,20 +181,28 @@ KeyObjectData KeyObjectData::GetPublicOrPrivateKey(std::shared_ptr<ArrayBuffer> ERR_error_string_n(err, err_buf, sizeof(err_buf)); throw std::runtime_error("Failed to read PEM asymmetric key: " + std::string(err_buf)); } else if (actualFormat == KFormatType::DER) { - // For DER, try parsing as public key first - if (type.has_value() && type.value() == KeyEncoding::SPKI) { + // PKCS#1 DER can contain either an RSA public or private key. + if (type.has_value() && type.value() == KeyEncoding::PKCS1 && !ncrypto::EVPKeyPointer::IsRSAPrivateKey(buffer)) { auto public_config = GetPublicKeyEncodingConfig(actualFormat, type.value()); auto res = ncrypto::EVPKeyPointer::TryParsePublicKey(public_config, buffer); if (res) { return CreateAsymmetric(KeyType::PUBLIC, std::move(res.value)); } - } else if (type.has_value() && type.value() == KeyEncoding::PKCS8) { + } else if (type.has_value() && type.value() == KeyEncoding::SPKI) { + auto public_config = GetPublicKeyEncodingConfig(actualFormat, type.value()); + auto res = ncrypto::EVPKeyPointer::TryParsePublicKey(public_config, buffer); + if (res) { + return CreateAsymmetric(KeyType::PUBLIC, std::move(res.value)); + } + } else if (type.has_value() && + (type.value() == KeyEncoding::PKCS1 || type.value() == KeyEncoding::PKCS8 || type.value() == KeyEncoding::SEC1)) { auto private_config = GetPrivateKeyEncodingConfig(actualFormat, type.value()); if (passphrase.has_value()) { auto& passphrase_ptr = passphrase.value(); private_config.passphrase = std::make_optional(ncrypto::DataPointer::Copy(ncrypto::Buffer<const void>{passphrase_ptr->data(), passphrase_ptr->size()})); } + ERR_clear_error(); auto res = ncrypto::EVPKeyPointer::TryParsePrivateKey(private_config, buffer); if (res) { return CreateAsymmetric(KeyType::PRIVATE, std::move(res.value)); diff --git a/packages/react-native-quick-crypto/deps/ncrypto b/packages/react-native-quick-crypto/deps/ncrypto index 027d1e44b..ef5d829e2 160000 --- a/packages/react-native-quick-crypto/deps/ncrypto +++ b/packages/react-native-quick-crypto/deps/ncrypto @@ -1 +1 @@ -Subproject commit 027d1e44bbded3e40549d8edb0887cd783de8e5d +Subproject commit ef5d829e27c9fcf539d4bf6b478353b888d607a2 diff --git a/packages/react-native-quick-crypto/package.json b/packages/react-native-quick-crypto/package.json index efdf22ad9..d2be13895 100644 --- a/packages/react-native-quick-crypto/package.json +++ b/packages/react-native-quick-crypto/package.json @@ -42,6 +42,7 @@ "deps/ncrypto/src/engine.cpp", "deps/ncrypto/src/ncrypto.cpp", "deps/ncrypto/LICENSE", + "deps/ncrypto/README.md", "deps/simdutf/include", "deps/simdutf/src", "deps/simdutf/LICENSE-MIT", diff --git a/packages/react-native-quick-crypto/src/keys/index.ts b/packages/react-native-quick-crypto/src/keys/index.ts index 91367668c..8baf99071 100644 --- a/packages/react-native-quick-crypto/src/keys/index.ts +++ b/packages/react-native-quick-crypto/src/keys/index.ts @@ -236,6 +236,8 @@ function createPublicKey(key: KeyInput): PublicKeyObject { let kType: KeyEncoding | undefined; if (type === 'spki') kType = KeyEncoding.SPKI; else if (type === 'pkcs1') kType = KeyEncoding.PKCS1; + else if (type === 'pkcs8') kType = KeyEncoding.PKCS8; + else if (type === 'sec1') kType = KeyEncoding.SEC1; return KeyObject.createKeyObject( 'public', diff --git a/scripts/check-ncrypto-openssl-deprecations.sh b/scripts/check-ncrypto-openssl-deprecations.sh new file mode 100755 index 000000000..5c987cf5f --- /dev/null +++ b/scripts/check-ncrypto-openssl-deprecations.sh @@ -0,0 +1,89 @@ +#!/usr/bin/env bash + +set -euo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +ncrypto_dir="$repo_root/packages/react-native-quick-crypto/deps/ncrypto" +compiler="${CXX:-c++}" +work_dir="$(mktemp -d)" +trap 'rm -rf "$work_dir"' EXIT + +openssl_cflags=() +openssl_ldflags=() +if [[ -n "${OPENSSL_ROOT_DIR:-}" ]]; then + openssl_cflags+=("-I$OPENSSL_ROOT_DIR/include") + if [[ -d "$OPENSSL_ROOT_DIR/lib" ]]; then + openssl_lib_dir="$OPENSSL_ROOT_DIR/lib" + else + openssl_lib_dir="$OPENSSL_ROOT_DIR/lib64" + fi + openssl_ldflags+=("-L$openssl_lib_dir" "-Wl,-rpath,$openssl_lib_dir" -lssl -lcrypto) + if [[ "$(uname -s)" == "Linux" ]]; then + openssl_ldflags+=(-ldl -pthread) + fi +elif command -v pkg-config >/dev/null 2>&1 && pkg-config --exists openssl; then + read -r -a openssl_cflags <<<"$(pkg-config --cflags openssl)" + read -r -a openssl_ldflags <<<"$(pkg-config --libs openssl)" +elif command -v brew >/dev/null 2>&1; then + openssl_prefix="$(brew --prefix openssl@3)" + openssl_cflags+=("-I$openssl_prefix/include") + openssl_ldflags+=("-L$openssl_prefix/lib" "-Wl,-rpath,$openssl_prefix/lib" -lssl -lcrypto) +else + openssl_ldflags+=(-lssl -lcrypto) +fi + +cat >"$work_dir/header-consumer.cpp" <<'EOF' +#include <ncrypto.h> +#include <ncrypto/aead.h> + +static_assert(OPENSSL_VERSION_NUMBER >= 0x30600000L); +static_assert(NCRYPTO_EVP_ONLY == 1); +EOF + +cat >"$work_dir/prime-check-regression.cpp" <<'EOF' +#include <ncrypto.h> + +namespace { +bool checkMersennePrime(int exponent, int requested_checks) { + ncrypto::BignumPointer candidate(BN_new()); + if (!candidate || BN_set_bit(candidate.get(), exponent) != 1 || + BN_sub_word(candidate.get(), 1) != 1) { + return false; + } + + int completed_checks = 0; + const int result = candidate.isPrime( + requested_checks, [&completed_checks](int event, int iteration) { + if (event == 1 && iteration >= 0) completed_checks++; + return true; + }); + return result == 1 && completed_checks >= requested_checks; +} +} // namespace + +int main() { + return checkMersennePrime(127, 65) && checkMersennePrime(2203, 129) ? 0 : 1; +} +EOF + +warning_flags=( + -std=c++20 + -Wall + -Wextra + -Werror + -Wdeprecated-declarations + -DNCRYPTO_EVP_ONLY=1 + "-I$ncrypto_dir/include" + "${openssl_cflags[@]}" +) + +"$compiler" "${warning_flags[@]}" -fsyntax-only "$ncrypto_dir/src/ncrypto.cpp" +"$compiler" "${warning_flags[@]}" -fsyntax-only "$ncrypto_dir/src/aead.cpp" +"$compiler" "${warning_flags[@]}" -fsyntax-only "$ncrypto_dir/src/engine.cpp" +"$compiler" "${warning_flags[@]}" -fsyntax-only "$work_dir/header-consumer.cpp" +"$compiler" "${warning_flags[@]}" \ + "$ncrypto_dir/src/ncrypto.cpp" \ + "$work_dir/prime-check-regression.cpp" \ + "${openssl_ldflags[@]}" \ + -o "$work_dir/prime-check-regression" +"$work_dir/prime-check-regression"