diff --git a/docs/IMPLEMENTATION-TRACKER.md b/docs/IMPLEMENTATION-TRACKER.md new file mode 100644 index 0000000..463dfe4 --- /dev/null +++ b/docs/IMPLEMENTATION-TRACKER.md @@ -0,0 +1,197 @@ +# Implementation Tracker + +## Status Overview + +| Area | Status | Next Action | +|------|--------|-------------| +| php-aegis Handover | ✅ Complete | Send to php-aegis team | +| sanctify-php Roadmap | ✅ Complete | Begin Phase 1 | +| Standalone Requirements | ✅ Complete | See STANDALONE.md | +| Target Audience | ✅ Complete | See TARGET-AUDIENCE.md | +| Binary Releases | 🔲 Not Started | **BLOCKER** - Tool cannot run without this | +| Composer Plugin | 🔲 Not Started | **CRITICAL** - Enable `composer require` | +| Docker Container | 🔲 Not Started | **HIGH** - Fallback for binary issues | +| GitHub Action | 🔲 Not Started | High priority | +| Incremental Analysis | 🔲 Not Started | Cache for performance | +| Semantic Support | 🔲 Not Started | Design AST extensions | + +--- + +## Critical Finding: GHC Requirement is a BLOCKER + +### Integration Evidence + +| Project | Could run sanctify-php? | Result | +|---------|------------------------|--------| +| wp-sinople-theme | ⚠️ With difficulty | Needed Haskell setup | +| Zotpress | ❌ **NO** | GHC not available, couldn't run at all | + +> **Zotpress integration failed completely** — sanctify-php could not be executed. +> Manual analysis was performed instead using documented patterns. +> This is not an inconvenience — it's a **total adoption blocker**. + +--- + +## Critical Path: Adoption Blockers + +> **Key Insight**: The Haskell dependency is a BLOCKER, not just an inconvenience. +> In real-world integrations, the tool literally could not be used. +> PHP developers cannot and will not install GHC. + +### sanctify-php Critical Items + +| Item | Priority | Blocks | +|------|----------|--------| +| Pre-built binaries | **CRITICAL** | Everything else | +| Composer plugin wrapper | **CRITICAL** | PHP dev adoption | +| GitHub Action | High | CI/CD adoption | +| Incremental analysis | Medium | Performance at scale | + +### php-aegis Critical Items + +| Item | Priority | Blocks | +|------|----------|--------| +| php-aegis-compat (PHP 7.4+) | **CRITICAL** | WordPress adoption | +| WordPress adapter (snake_case) | High | WP dev experience | +| Extended validators | Medium | Common use cases | + +--- + +## Immediate Actions + +### For php-aegis Team + +1. **Review handover document**: `docs/PHP-AEGIS-HANDOVER.md` +2. **Critical implementation** (adoption blockers): + - [ ] Create `php-aegis-compat` package for PHP 7.4+ + - [ ] Add WordPress adapter with snake_case functions + - [ ] Extend `Validate` class: `int()`, `ip()`, `domain()` +3. **Priority implementation** (unique value): + - [ ] `Aegis\Semantic\Turtle::escapeString()` + - [ ] `Aegis\Semantic\Turtle::escapeIRI()` + - [ ] SPDX headers on all files + +### For sanctify-php Team + +1. **Phase 1 CRITICAL**: Enable `composer require` installation + - [ ] GitHub Actions for binary releases (linux, darwin x86_64/arm64) + - [ ] Composer plugin that auto-downloads binary on install + - [ ] GitHub Action for CI/CD integration + - [ ] Dockerfile for container distribution + +2. **Phase 1 HIGH**: Performance + - [ ] Incremental analysis with file hash cache + - [ ] Only rescan changed files + +3. **Phase 2 Priority**: Semantic web support + - [ ] Create `Sanctify.Analysis.Semantic` module + - [ ] Extend taint sinks for Turtle/JSON-LD contexts + - [ ] Add WordPress semantic theme detection + +--- + +## Cross-Team Coordination + +### Shared Namespace Agreement + +Both tools should recognize these function signatures: + +```php +// php-aegis provides these at runtime +Aegis\Semantic\Turtle::escapeString(string $value): string +Aegis\Semantic\Turtle::escapeIRI(string $iri): string +Aegis\Semantic\JsonLd::escapeValue(mixed $value): string +Aegis\IndieWeb\Micropub::sanitizeContent(string $content, array $context = []): string +Aegis\IndieWeb\IndieAuth::verifyToken(string $token, string $endpoint): array|false +``` + +```haskell +-- sanctify-php recognizes these as safe sinks +aegisSemantic :: [Text] +aegisSemantic = + [ "Aegis\\Semantic\\Turtle::escapeString" + , "Aegis\\Semantic\\Turtle::escapeIRI" + , "Aegis\\Semantic\\JsonLd::escapeValue" + , "Aegis\\IndieWeb\\Micropub::sanitizeContent" + ] +``` + +### Integration Testing + +When both tools are updated: + +```bash +# 1. Analyze code that uses php-aegis +sanctify-php analyze ./project --aegis-aware + +# 2. Verify no false positives for Aegis-escaped output +# 3. Verify Turtle context detection works +# 4. Verify auto-fix inserts correct Aegis calls +``` + +--- + +## Issue Templates + +### For php-aegis Repository + +**Title**: Add semantic web escaping support (RDF/Turtle) + +**Body**: +```markdown +## Context +Integration feedback from wp-sinople-theme identified missing RDF/Turtle escaping functions. + +## Requirements +- [ ] `Aegis\Semantic\Turtle::escapeString()` - W3C Turtle string escaping +- [ ] `Aegis\Semantic\Turtle::escapeIRI()` - IRI validation and escaping +- [ ] Follow escape rules from https://www.w3.org/TR/turtle/#sec-escapes + +## Reference Implementation +See sanctify-php `docs/PHP-AEGIS-HANDOVER.md` for reference code. + +## Testing +Should correctly escape: +- Backslashes, quotes, newlines, tabs +- Unicode control characters (U+0000 to U+001F) +- Invalid IRI characters per RFC 3987 +``` + +### For sanctify-php Repository + +**Title**: Add pre-built binary releases + +**Body**: +```markdown +## Problem +Users need Haskell toolchain to build sanctify-php, preventing adoption. + +## Solution +Provide statically-linked binaries via GitHub Releases for: +- linux-x86_64 +- linux-aarch64 +- darwin-x86_64 +- darwin-aarch64 +- windows-x86_64 + +## Implementation +- [ ] GitHub Actions workflow with matrix strategy +- [ ] Static linking flags +- [ ] GPG signing +- [ ] Release automation + +## Reference +See `docs/ROADMAP.md` Phase 1 for details. +``` + +--- + +## Communication Channels + +- **sanctify-php issues**: https://github.com/hyperpolymath/sanctify-php/issues +- **php-aegis issues**: https://github.com/hyperpolymath/php-aegis/issues + +--- + +*SPDX-License-Identifier: MIT OR AGPL-3.0-or-later* +*SPDX-FileCopyrightText: 2024-2025 hyperpolymath* diff --git a/docs/INTEGRATION-SUMMARY.md b/docs/INTEGRATION-SUMMARY.md new file mode 100644 index 0000000..2a1eacf --- /dev/null +++ b/docs/INTEGRATION-SUMMARY.md @@ -0,0 +1,162 @@ +# Integration Feedback Summary + +Consolidated findings from three real-world integration attempts. + +--- + +## Integration Projects + +| # | Project | Type | sanctify-php Result | php-aegis Result | +|---|---------|------|---------------------|------------------| +| 1 | wp-sinople-theme | Semantic WP theme | ⚠️ Ran with difficulty | ⚠️ Limited value | +| 2 | Zotpress | Mature WP plugin | ❌ **Could not run** | ❌ No value added | +| 3 | (Metrics capture) | - | Improvements measured | Issues documented | + +--- + +## Critical Findings + +### sanctify-php: GHC is a BLOCKER + +``` +┌─────────────────────────────────────────────────────────────┐ +│ The Haskell toolchain requirement is a TOTAL BLOCKER │ +│ │ +│ • Zotpress integration: Could not run sanctify-php at all │ +│ • Manual analysis was performed instead │ +│ • PHP developers will NOT install GHC │ +│ • Pre-built binaries are MANDATORY for any adoption │ +└─────────────────────────────────────────────────────────────┘ +``` + +### php-aegis: Duplicates WordPress Core + +``` +┌─────────────────────────────────────────────────────────────┐ +│ php-aegis provides no value for WordPress projects │ +│ │ +│ WordPress already has: │ +│ • esc_html(), esc_attr(), esc_url(), esc_js() │ +│ • sanitize_text_field(), wp_strip_all_tags() │ +│ • is_email(), wp_http_validate_url() │ +│ │ +│ php-aegis should focus on what WordPress LACKS: │ +│ • RDF/Turtle escaping │ +│ • IndieWeb protocol security │ +│ • ActivityPub content policies │ +└─────────────────────────────────────────────────────────────┘ +``` + +--- + +## Metrics Achieved + +| Metric | Before | After | Change | +|--------|--------|-------|--------| +| Files with `strict_types` | 0 | 24 | +100% | +| PHP version support | 7.4+ | 8.2+ | Upgraded | +| WordPress version | 5.8+ | 6.4+ | Upgraded | +| CI security checks | 0 | 4 | +4 new | + +--- + +## Priority Matrix + +### sanctify-php Priorities + +| Priority | Item | Status | Rationale | +|----------|------|--------|-----------| +| **BLOCKER** | Pre-built binaries | 🔲 Not Started | Tool cannot run without this | +| **Critical** | Composer plugin | 🔲 Not Started | PHP devs expect `composer require` | +| **High** | Docker container | 🔲 Not Started | Fallback for binary issues | +| **High** | GitHub Action | 🔲 Not Started | CI/CD adoption | +| Medium | Incremental analysis | 🔲 Not Started | Performance | +| Medium | Semantic support | 🔲 Not Started | Turtle/JSON-LD contexts | + +### php-aegis Priorities + +| Priority | Item | Status | Rationale | +|----------|------|--------|-----------| +| **Critical** | Define target audience | 🔲 Not Started | Don't compete with WP core | +| **Critical** | php-aegis-compat (7.4+) | 🔲 Not Started | WordPress adoption | +| **High** | Turtle escaping | 🔲 Not Started | **Unique value** | +| **High** | WordPress adapter | 🔲 Not Started | snake_case functions | +| Medium | Extended validators | 🔲 Not Started | int(), ip(), domain() | +| Medium | IndieWeb support | 🔲 Not Started | **Unique value** | + +--- + +## Strategic Decisions Required + +### For php-aegis + +> **Question**: Who is this library for? + +| Option | Description | Recommendation | +|--------|-------------|----------------| +| **A** | Non-WordPress PHP library | Don't compete with WP | +| **B** | WordPress superset library | Provide unique value WP lacks | + +**Recommendation: Option B** — Focus on semantic web, IndieWeb, ActivityPub. + +### For sanctify-php + +> **Question**: How do we achieve adoption? + +| Priority | Action | +|----------|--------| +| 1 | Release pre-built binaries (BLOCKER resolution) | +| 2 | Create Composer plugin wrapper | +| 3 | Create GitHub Action | +| 4 | Add Docker container as fallback | + +--- + +## What Works Well + +### sanctify-php Strengths +- ✅ WordPress-aware security constraints +- ✅ OWASP vulnerability coverage +- ✅ Taint tracking analysis +- ✅ SARIF output for GitHub Security +- ✅ Auto-fix transformations + +### php-aegis Strengths +- ✅ Simple, focused API +- ✅ Zero dependencies +- ✅ PSR-12 compliance +- ✅ Type safety + +--- + +## Documentation Produced + +| Document | Purpose | +|----------|---------| +| `PHP-AEGIS-HANDOVER.md` | Recommendations for php-aegis team | +| `ROADMAP.md` | sanctify-php improvement plan | +| `STANDALONE.md` | Minimum viable standalone requirements | +| `TARGET-AUDIENCE.md` | When to use each tool | +| `IMPLEMENTATION-TRACKER.md` | Cross-team coordination | +| `INTEGRATION-SUMMARY.md` | This consolidated summary | + +--- + +## Next Steps + +### Immediate (Week 1) +1. **sanctify-php**: Set up GitHub Actions for binary releases +2. **php-aegis**: Create php-aegis-compat package scaffold + +### Short-term (Week 2-3) +1. **sanctify-php**: Publish Composer plugin wrapper +2. **php-aegis**: Implement Turtle escaping functions + +### Medium-term (Week 4+) +1. **sanctify-php**: Create GitHub Action for CI/CD +2. **php-aegis**: Add IndieWeb protocol support + +--- + +*SPDX-License-Identifier: MIT OR AGPL-3.0-or-later* +*SPDX-FileCopyrightText: 2024-2025 hyperpolymath* diff --git a/docs/PHP-AEGIS-HANDOVER.md b/docs/PHP-AEGIS-HANDOVER.md new file mode 100644 index 0000000..a3bf208 --- /dev/null +++ b/docs/PHP-AEGIS-HANDOVER.md @@ -0,0 +1,607 @@ +# PHP-Aegis Handover Document + +## Context + +This document provides integration feedback from multiple WordPress projects: +1. **wp-sinople-theme** - Semantic theme with IndieWeb/Micropub support +2. **Zotpress** - Mature WordPress plugin (already well-secured) + +**Integration Report Date**: 2025-12-27 + +--- + +## Executive Summary + +### The Core Problem + +**php-aegis duplicates WordPress core functionality** without providing additional value for WordPress projects. + +| php-aegis | WordPress Equivalent | Winner | +|-----------|---------------------|--------| +| `Validator::email()` | `is_email()` | WordPress (more edge cases) | +| `Validator::url()` | `wp_http_validate_url()` | WordPress (protocol-aware) | +| `Sanitizer::html()` | `esc_html()` | WordPress (context-aware) | +| `Sanitizer::stripTags()` | `wp_strip_all_tags()` | WordPress (more thorough) | +| Generic escaping | `esc_html()`, `esc_attr()`, `esc_url()`, `esc_js()` | **WordPress (context-specific)** | + +### Strategic Decision Required + +php-aegis must choose a positioning: + +**Option A: Non-WordPress PHP Library** +- Document that php-aegis is for Laravel, Symfony, vanilla PHP +- Don't compete with WordPress's mature security APIs +- Focus on frameworks that lack built-in security + +**Option B: WordPress Superset Library** +- Provide capabilities WordPress lacks (semantic web, IndieWeb, ActivityPub) +- Integrate with (not replace) WordPress functions +- Be additive, not duplicative + +**Recommendation: Option B** — Provide unique value WordPress lacks. + +--- + +## Integration Feedback Summary + +### Issues Identified with php-aegis + +| Issue | Severity | Impact | +|-------|----------|--------| +| Duplicates WordPress core | **Critical** | No value add for WP projects | +| Lacks context-aware escaping | **Critical** | WP has html/attr/url/js contexts, Aegis has generic | +| PHP 8.1+ blocks WordPress adoption | **Critical** | WordPress 6.4 supports PHP 7.4+, most hosts still on 7.4/8.0 | +| No WordPress adapter | High | camelCase API vs snake_case WordPress conventions | +| Feature set too minimal | Medium | WordPress has equivalent functions already | +| No RDF/Turtle escaping | High | Semantic themes require W3C-compliant escaping | +| Limited validators | Medium | Only email/url - missing int(), ip(), domain(), uuid(), credit_card() | +| Missing SPDX license headers | Low | Compliance concern for FOSS projects | + +### What Mature WordPress Projects Already Have + +The Zotpress integration revealed that well-maintained WordPress plugins already: +- ✅ Have ABSPATH protection on all files +- ✅ Use prepared statements for all database queries +- ✅ Verify nonces on AJAX handlers +- ✅ Sanitize input and escape output throughout +- ✅ Follow WordPress coding standards + +**Conclusion**: php-aegis provides no value for these projects unless it offers something WordPress doesn't. + +--- + +## Detailed Recommendations + +### 0. CRITICAL: Define Target Audience + +Before any implementation, php-aegis must answer: + +> **Who is this library for?** + +| Audience | Should php-aegis target? | Why | +|----------|-------------------------|-----| +| WordPress plugins/themes | Only if offering unique value | WP core already handles standard security | +| Laravel applications | Yes | Laravel has security but less comprehensive | +| Symfony applications | Yes | Similar to Laravel | +| Vanilla PHP | Yes | No built-in security | +| Semantic web apps | **Yes - unique opportunity** | No existing library handles RDF/Turtle | +| IndieWeb apps | **Yes - unique opportunity** | Micropub/Webmention security not solved | +| ActivityPub/Fediverse | **Yes - unique opportunity** | Complex content policies needed | + +### 1. CRITICAL: PHP 7.4+ Compatibility Layer + +**Problem**: php-aegis requires PHP 8.1+, but WordPress ecosystem reality: +- WordPress 6.4+ officially supports PHP 7.4+ +- Many shared hosts still run PHP 7.4 or 8.0 +- Plugin/theme developers must support the WordPress minimum + +**Solution**: Split into two packages: + +``` +php-aegis (PHP 8.1+) ← Modern API with enums, union types + │ + └── php-aegis-compat (PHP 7.4+) ← Polyfill package for WordPress +``` + +**php-aegis-compat Implementation**: + +```php +=7.4" + }, + "conflict": { + "hyperpolymath/php-aegis": "*" + }, + "autoload": { + "psr-4": { "Aegis\\": "src/" } + } +} +``` + +**Usage in WordPress plugins**: +```php +// In plugin bootstrap +if (PHP_VERSION_ID >= 80100) { + require_once __DIR__ . '/vendor/hyperpolymath/php-aegis/autoload.php'; +} else { + require_once __DIR__ . '/vendor/hyperpolymath/php-aegis-compat/autoload.php'; +} +``` + +### 1. WordPress Adapter (snake_case API) + +**Problem**: WordPress uses `snake_case` functions, php-aegis uses `CamelCase` methods. + +**Solution**: Provide WordPress adapter functions: + +```php + '\\\\', + '"' => '\\"', + "\n" => '\\n', + "\r" => '\\r', + "\t" => '\\t', + ]; + + $escaped = strtr($value, $replacements); + + // Handle control characters (U+0000 to U+001F except handled above) + return preg_replace_callback( + '/[\x00-\x08\x0B\x0C\x0E-\x1F]/', + fn($m) => sprintf('\\u%04X', ord($m[0])), + $escaped + ) ?? $escaped; + } + + /** + * Validate and escape an IRI for Turtle output. + * + * @throws \InvalidArgumentException If IRI is malformed + */ + public static function escapeIRI(string $iri): string + { + // Validate IRI structure + if (!filter_var($iri, FILTER_VALIDATE_URL) && + !preg_match('/^urn:[a-z0-9][a-z0-9-]{0,31}:/i', $iri)) { + throw new \InvalidArgumentException("Invalid IRI: {$iri}"); + } + + // Escape special characters per RFC 3987 + $escape = ['<' => '%3C', '>' => '%3E', '"' => '%22', + '{' => '%7B', '}' => '%7D', '|' => '%7C', + '\\' => '%5C', '^' => '%5E', '`' => '%60']; + + return strtr($iri, $escape); + } +} +``` + +### 3. Add SPDX License Headers + +**Problem**: All source files should have SPDX identifiers for license clarity. + +**Standard Format**: +```php + htmlspecialchars((string)$value, ENT_QUOTES | ENT_HTML5, 'UTF-8'), + EscapeContext::Turtle => Semantic\Turtle::escapeString((string)$value), + // ... + }; + } +} + +// Use readonly properties for immutable security configs +final readonly class SecurityPolicy +{ + public function __construct( + public bool $strictMode = true, + public EscapeContext $defaultContext = EscapeContext::Html, + public array $allowedSchemes = ['https'], + ) {} +} +``` + +--- + +## Suggested Architecture + +### Complementary Roles + +| Tool | Role | When Used | +|------|------|-----------| +| **sanctify-php** | Static analysis & transformation | Build time, CI/CD | +| **php-aegis** | Runtime security library | Application runtime | + +### Integration Points + +``` +┌─────────────────────────────────────────────────────────┐ +│ Development Flow │ +├─────────────────────────────────────────────────────────┤ +│ │ +│ Source Code │ +│ │ │ +│ ▼ │ +│ sanctify-php analyze ◄── Static analysis │ +│ │ Finds missing escaping │ +│ │ Detects taint flows │ +│ │ Reports vulnerabilities │ +│ ▼ │ +│ sanctify-php fix ◄── Auto-transform │ +│ │ Adds php-aegis calls │ +│ │ Inserts strict_types │ +│ ▼ │ +│ Production Code │ +│ │ │ +│ ▼ │ +│ php-aegis (runtime) ◄── Runtime protection │ +│ Semantic escaping │ +│ Protocol sanitization │ +│ Defense in depth │ +│ │ +└─────────────────────────────────────────────────────────┘ +``` + +### Proposed php-aegis Namespace Structure + +``` +Aegis/ +├── Escape.php # Core escaping (extends WP when needed) +├── Sanitize.php # Core sanitization +├── Validate.php # Input validation +├── Semantic/ # ← NEW: RDF/Linked Data +│ ├── Turtle.php # W3C Turtle escaping +│ ├── JsonLd.php # JSON-LD sanitization +│ ├── NTriples.php # N-Triples escaping +│ └── Rdf.php # Generic RDF utilities +├── IndieWeb/ # ← NEW: IndieWeb protocols +│ ├── Micropub.php # Micropub content sanitization +│ ├── Webmention.php # Webmention validation +│ ├── IndieAuth.php # Token verification helpers +│ └── Microsub.php # Microsub security +├── ActivityPub/ # ← NEW: Fediverse +│ ├── Object.php # AS2 object sanitization +│ ├── Signature.php # HTTP signature verification +│ └── Content.php # HTML content policy +├── WordPress/ # WordPress integration layer +│ ├── Hooks.php # Security hook integration +│ └── OptionsEncryption.php # Encrypted options storage +└── Policy/ # Security policies + ├── ContentSecurityPolicy.php + └── PermissionsPolicy.php +``` + +--- + +## sanctify-php Integration Support + +We will add support in sanctify-php to: + +1. **Recognize php-aegis calls as safe sinks** + ```haskell + -- In Sanctify.Analysis.Taint + aegisSafeSinks :: [Text] + aegisSafeSinks = + [ "Aegis\\Escape::html" + , "Aegis\\Semantic\\Turtle::escapeString" + , "Aegis\\IndieWeb\\Micropub::sanitizeContent" + -- ... + ] + ``` + +2. **Auto-insert php-aegis calls during fix** + ```haskell + -- Transform unescaped output to use php-aegis + -- Before: echo $user_input; + -- After: echo \Aegis\Escape::html($user_input); + ``` + +3. **Detect semantic context for appropriate escaping** + ```haskell + -- Detect Turtle output context + -- Recommend: \Aegis\Semantic\Turtle::escapeString() + -- Instead of: esc_html() (wrong context) + ``` + +--- + +## Action Items for php-aegis Team + +### Priority 0 (Critical) — Adoption Blockers +- [ ] Create `php-aegis-compat` package for PHP 7.4+ +- [ ] Add WordPress adapter with snake_case functions +- [ ] Extend `Validate` class: `int()`, `ip()`, `domain()`, `uuid()`, `slug()` + +### Priority 1 (High) — Unique Value +- [ ] Add `Aegis\Semantic\Turtle` namespace with W3C-compliant escaping +- [ ] Add `Aegis\IndieWeb\Micropub` for content sanitization +- [ ] Add SPDX headers to all files + +### Priority 2 (Medium) — Polish +- [ ] Use PHP 8.1+ enums for contexts (in main package only) +- [ ] Add union types throughout API +- [ ] Document differentiation from WordPress core functions +- [ ] Auto-detect WordPress and register hooks + +### Priority 3 (Low) — Extended Features +- [ ] Add ActivityPub sanitization support +- [ ] Add JSON-LD validation +- [ ] Laravel adapter (in addition to WordPress) + +--- + +## Contact + +For questions about this handover or sanctify-php integration: +- Repository: hyperpolymath/sanctify-php +- Issues: https://github.com/hyperpolymath/sanctify-php/issues + +--- + +*SPDX-License-Identifier: MIT OR AGPL-3.0-or-later* +*SPDX-FileCopyrightText: 2024-2025 hyperpolymath* diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md new file mode 100644 index 0000000..10f1a22 --- /dev/null +++ b/docs/ROADMAP.md @@ -0,0 +1,766 @@ +# Sanctify-PHP Roadmap + +## Context + +This roadmap addresses integration feedback from real-world deployment: +1. **wp-sinople-theme** - Semantic theme with IndieWeb/Micropub support +2. **Zotpress** - Mature WordPress plugin (couldn't run sanctify-php at all) + +**Feedback Date**: 2025-12-27 +**Current Version**: 0.1.0.0 + +--- + +## Critical Finding: Tool Unusable Without Binaries + +### Zotpress Integration Failure + +> **sanctify-php could not be run at all** because GHC (Haskell compiler) was not available. +> Manual analysis was performed instead using documented patterns. + +This confirms the #1 adoption blocker: **the Haskell build requirement prevents any usage**. + +### Evidence from Integration Attempts + +| Project | Could run sanctify-php? | Outcome | +|---------|------------------------|---------| +| wp-sinople-theme | ⚠️ With difficulty | Required Haskell setup | +| Zotpress | ❌ **No** | GHC not available, manual analysis only | + +--- + +## Issues Identified + +| Issue | Severity | User Impact | +|-------|----------|-------------| +| Requires Haskell toolchain | **BLOCKER** | Tool literally cannot run | +| No `composer require` install | **Critical** | PHP devs expect Composer installation | +| No pre-built binaries | **Critical** | No workaround for GHC requirement | +| No Docker container | High | Alternative deployment path missing | +| No GitHub Action | High | No easy CI/CD integration | +| No incremental analysis | Medium | Full rescan on every change is slow | +| No RDF/Turtle awareness | High | Semantic themes get false negatives | +| Limited PHP 8.x syntax | Medium | May miss some modern PHP patterns | +| Missing WP integration docs | Medium | Users don't know how to integrate | + +### Key Insight + +> **The Haskell dependency is a BLOCKER, not just an inconvenience.** +> In the Zotpress integration, the tool could not be used at all. +> PHP developers cannot and will not install GHC. +> **Pre-built binaries are not optional — they are required for any adoption.** + +--- + +## Phase 1: Distribution & Accessibility + +**Goal**: Make sanctify-php usable without Haskell knowledge + +### 1.1 Pre-built Binaries + +Provide statically-linked binaries for common platforms: + +``` +releases/ +├── sanctify-php-0.2.0-linux-x86_64 +├── sanctify-php-0.2.0-linux-aarch64 +├── sanctify-php-0.2.0-darwin-x86_64 +├── sanctify-php-0.2.0-darwin-aarch64 +└── sanctify-php-0.2.0-windows-x86_64.exe +``` + +**Implementation**: +- [ ] Add GitHub Actions workflow for cross-compilation +- [ ] Use static linking (`-optl-static -optl-pthread`) +- [ ] Sign binaries (GPG + sigstore) +- [ ] Create release automation script + +**CI Workflow** (`.github/workflows/release.yml`): +```yaml +name: Release Binaries +on: + push: + tags: ['v*'] + +jobs: + build: + strategy: + matrix: + include: + - os: ubuntu-latest + target: x86_64-linux + - os: macos-latest + target: x86_64-darwin + - os: macos-latest + target: aarch64-darwin + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + - uses: haskell-actions/setup@v2 + with: + ghc-version: '9.6' + - run: cabal build --enable-executable-static + - uses: actions/upload-artifact@v4 +``` + +### 1.2 Docker Container + +Provide OCI container for easy deployment: + +```dockerfile +# Dockerfile +FROM haskell:9.6-slim AS builder +WORKDIR /build +COPY . . +RUN cabal build --enable-executable-static +RUN cp $(cabal list-bin sanctify-php) /sanctify-php + +FROM gcr.io/distroless/static-debian12 +COPY --from=builder /sanctify-php /usr/local/bin/sanctify-php +ENTRYPOINT ["sanctify-php"] +``` + +**Usage**: +```bash +# Analyze a project +docker run --rm -v $(pwd):/src ghcr.io/hyperpolymath/sanctify-php analyze /src + +# Generate report +docker run --rm -v $(pwd):/src ghcr.io/hyperpolymath/sanctify-php report /src --format=sarif +``` + +### 1.3 Composer Plugin Wrapper (Critical Path) + +PHP developers expect `composer require`. Provide a Composer plugin that: +1. Detects platform (OS/arch) +2. Downloads the appropriate pre-built binary +3. Provides Composer scripts integration + +**Package Structure**: +``` +sanctify-php-composer/ +├── composer.json +├── src/ +│ ├── Plugin.php # Composer plugin hooks +│ ├── BinaryInstaller.php # Platform detection & download +│ └── ScriptHandler.php # Composer scripts integration +└── bin/ + └── sanctify-php # Wrapper script +``` + +**composer.json**: +```json +{ + "name": "hyperpolymath/sanctify-php", + "description": "PHP security analysis and hardening tool", + "type": "composer-plugin", + "require": { + "php": ">=7.4", + "composer-plugin-api": "^2.0" + }, + "require-dev": { + "composer/composer": "^2.0" + }, + "autoload": { + "psr-4": { "Sanctify\\Composer\\": "src/" } + }, + "extra": { + "class": "Sanctify\\Composer\\Plugin", + "sanctify-binaries": { + "linux-x86_64": "https://github.com/hyperpolymath/sanctify-php/releases/download/v{version}/sanctify-php-linux-x86_64", + "darwin-x86_64": "https://github.com/hyperpolymath/sanctify-php/releases/download/v{version}/sanctify-php-darwin-x86_64", + "darwin-arm64": "https://github.com/hyperpolymath/sanctify-php/releases/download/v{version}/sanctify-php-darwin-aarch64" + } + }, + "scripts": { + "sanctify:analyze": "Sanctify\\Composer\\ScriptHandler::analyze", + "sanctify:fix": "Sanctify\\Composer\\ScriptHandler::fix", + "sanctify:report": "Sanctify\\Composer\\ScriptHandler::report" + }, + "bin": ["bin/sanctify-php"] +} +``` + +**BinaryInstaller.php**: +```php +write("Downloading sanctify-php for {$platform}..."); + + $binPath = self::BINARY_DIR . '/sanctify-php-bin'; + self::download($url, $binPath); + chmod($binPath, 0755); + + $io->write("sanctify-php installed successfully."); + } + + private static function detectPlatform(): string + { + $os = PHP_OS_FAMILY === 'Darwin' ? 'darwin' : 'linux'; + $arch = php_uname('m') === 'arm64' ? 'arm64' : 'x86_64'; + return "{$os}-{$arch}"; + } + + private static function download(string $url, string $dest): void + { + $ch = curl_init($url); + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + $binary = curl_exec($ch); + curl_close($ch); + file_put_contents($dest, $binary); + } +} +``` + +**Usage after installation**: +```bash +# Install +composer require --dev hyperpolymath/sanctify-php + +# Use via Composer scripts +composer sanctify:analyze src/ +composer sanctify:fix src/ -- --policy=conservative +composer sanctify:report src/ -- --format=sarif + +# Or directly +vendor/bin/sanctify-php analyze src/ +``` + +### 1.4 GitHub Action + +Official GitHub Action for CI/CD: + +```yaml +# .github/actions/sanctify-php/action.yml +name: 'Sanctify PHP' +description: 'PHP security analysis and hardening' +branding: + icon: 'shield' + color: 'green' + +inputs: + path: + description: 'Path to analyze' + required: true + default: 'src' + format: + description: 'Output format (text, json, sarif, html, markdown)' + required: false + default: 'sarif' + fail-on: + description: 'Fail on severity level (critical, high, medium, low, none)' + required: false + default: 'high' + upload-sarif: + description: 'Upload SARIF to GitHub Security tab' + required: false + default: 'true' + +outputs: + issues-found: + description: 'Number of security issues found' + value: ${{ steps.analyze.outputs.issues }} + +runs: + using: 'composite' + steps: + - name: Download sanctify-php + shell: bash + run: | + curl -LO https://github.com/hyperpolymath/sanctify-php/releases/latest/download/sanctify-php-linux-x86_64 + chmod +x sanctify-php-linux-x86_64 + sudo mv sanctify-php-linux-x86_64 /usr/local/bin/sanctify-php + + - name: Run analysis + id: analyze + shell: bash + run: | + sanctify-php analyze ${{ inputs.path }} \ + --format=${{ inputs.format }} \ + --output=sanctify-results.${{ inputs.format }} \ + --fail-on=${{ inputs.fail-on }} + echo "issues=$(sanctify-php analyze ${{ inputs.path }} --format=json | jq '.issues | length')" >> $GITHUB_OUTPUT + + - name: Upload SARIF + if: inputs.upload-sarif == 'true' && inputs.format == 'sarif' + uses: github/codeql-action/upload-sarif@v3 + with: + sarif_file: sanctify-results.sarif +``` + +**Usage in workflows**: +```yaml +name: Security +on: [push, pull_request] + +jobs: + sanctify: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: hyperpolymath/sanctify-php-action@v1 + with: + path: src/ + fail-on: high +``` + +### 1.5 Incremental Analysis + +Cache analysis results and only rescan changed files: + +```haskell +-- src/Sanctify/Cache.hs +-- SPDX-License-Identifier: AGPL-3.0-or-later + +module Sanctify.Cache + ( AnalysisCache(..) + , loadCache + , saveCache + , getChangedFiles + ) where + +import qualified Data.Map.Strict as Map +import Crypto.Hash (SHA256, hash) + +data AnalysisCache = AnalysisCache + { cacheVersion :: Text + , fileHashes :: Map FilePath Text -- path -> SHA256 + , cachedResults :: Map FilePath [SecurityIssue] + } + deriving (Generic, FromJSON, ToJSON) + +-- Determine which files need re-analysis +getChangedFiles :: AnalysisCache -> [FilePath] -> IO [FilePath] +getChangedFiles cache files = do + filterM (hasChanged cache) files + where + hasChanged c f = do + currentHash <- hashFile f + pure $ Map.lookup f (fileHashes c) /= Just currentHash +``` + +**CLI usage**: +```bash +# First run: full analysis, creates .sanctify-cache.json +sanctify-php analyze src/ + +# Subsequent runs: only analyze changed files +sanctify-php analyze src/ --incremental + +# Force full rescan +sanctify-php analyze src/ --no-cache +``` + +### 1.6 Guix Package + +Proper Guix package definition for reproducible builds: + +```scheme +;; guix.scm - enhanced for distribution +(define-public sanctify-php + (package + (name "sanctify-php") + (version "0.2.0") + (source (origin + (method git-fetch) + (uri (git-reference + (url "https://github.com/hyperpolymath/sanctify-php") + (commit (string-append "v" version)))) + (sha256 (base32 "...")))) + (build-system haskell-build-system) + (inputs (list ghc-megaparsec ghc-aeson ghc-prettyprinter)) + (synopsis "PHP security hardening and analysis tool") + (description "Static analyzer that detects vulnerabilities and +transforms PHP code for security compliance.") + (license (list license:expat license:agpl3+)) + (home-page "https://github.com/hyperpolymath/sanctify-php"))) +``` + +--- + +## Phase 2: Semantic Web Support + +**Goal**: First-class support for RDF/Turtle/JSON-LD output contexts + +### 2.1 Semantic Output Detection + +Add detection for semantic web output patterns: + +```haskell +-- src/Sanctify/Analysis/Semantic.hs +-- SPDX-License-Identifier: AGPL-3.0-or-later + +module Sanctify.Analysis.Semantic + ( SemanticContext(..) + , detectSemanticContext + , semanticEscapingRules + ) where + +data SemanticContext + = TurtleContext -- RDF Turtle output + | JsonLdContext -- JSON-LD output + | NTriplesContext -- N-Triples output + | RdfXmlContext -- RDF/XML output + | MicroformatsContext -- Microformats2 in HTML + | NoSemanticContext -- Standard HTML/text + deriving (Eq, Show, Generic) + +-- Detect context from surrounding code +detectSemanticContext :: Statement -> Maybe SemanticContext +detectSemanticContext stmt = case stmt of + -- Detect Content-Type headers + FunctionCall "header" [StringLit ct] + | "text/turtle" `isInfixOf` ct -> Just TurtleContext + | "application/ld+json" `isInfixOf` ct -> Just JsonLdContext + | "application/n-triples" `isInfixOf` ct -> Just NTriplesContext + + -- Detect file extensions in output + FunctionCall "file_put_contents" [StringLit path, _] + | ".ttl" `isSuffixOf` path -> Just TurtleContext + | ".jsonld" `isSuffixOf` path -> Just JsonLdContext + + -- Detect semantic template patterns + Echo (StringLit template) + | "@prefix" `isInfixOf` template -> Just TurtleContext + | "\"@context\"" `isInfixOf` template -> Just JsonLdContext + + _ -> Nothing +``` + +### 2.2 Semantic-Aware Taint Sinks + +Extend taint analysis with semantic sinks: + +```haskell +-- In Sanctify.Analysis.Taint + +data SemanticSink + = TurtleLiteral -- String literal in Turtle + | TurtleIRI -- IRI in Turtle + | JsonLdValue -- Value in JSON-LD + | JsonLdId -- @id field in JSON-LD + deriving (Eq, Show) + +semanticSinkEscaping :: SemanticSink -> [Text] +semanticSinkEscaping = \case + TurtleLiteral -> + [ "Aegis\\Semantic\\Turtle::escapeString" + , "sanctify_escape_turtle_string" -- WP helper + ] + TurtleIRI -> + [ "Aegis\\Semantic\\Turtle::escapeIRI" + , "sanctify_escape_turtle_iri" + ] + JsonLdValue -> + [ "json_encode" -- with JSON_HEX_* flags + , "Aegis\\Semantic\\JsonLd::escapeValue" + ] + JsonLdId -> + [ "Aegis\\Semantic\\JsonLd::validateIRI" + , "filter_var" -- with FILTER_VALIDATE_URL + ] +``` + +### 2.3 WordPress Semantic Theme Detection + +Detect semantic WordPress themes: + +```haskell +-- In Sanctify.WordPress.Constraints + +data ThemeType + = StandardTheme + | SemanticTheme -- Uses RDF/Turtle output + | IndieWebTheme -- Uses IndieWeb protocols + | SemanticIndieWeb -- Both semantic + IndieWeb + deriving (Eq, Show) + +detectThemeType :: [FilePath] -> IO ThemeType +detectThemeType files = do + hasSemanticPhp <- any ("semantic.php" `isSuffixOf`) files + hasIndiewebPhp <- any ("indieweb.php" `isSuffixOf`) files + hasTurtleOutput <- anyM containsTurtlePatterns files + hasMicropub <- anyM containsMicropubPatterns files + + pure $ case (hasSemanticPhp || hasTurtleOutput, hasIndiewebPhp || hasMicropub) of + (True, True) -> SemanticIndieWeb + (True, False) -> SemanticTheme + (False, True) -> IndieWebTheme + _ -> StandardTheme +``` + +--- + +## Phase 3: PHP 8.x Syntax Completeness + +**Goal**: Full support for PHP 8.0-8.4 syntax + +### 3.1 Parser Enhancements + +| Feature | PHP Version | Status | Priority | +|---------|-------------|--------|----------| +| Named arguments | 8.0 | ✅ Parsed | - | +| Match expressions | 8.0 | ✅ AST ready | Medium | +| Union types | 8.0 | ✅ Supported | - | +| Nullsafe operator `?->` | 8.0 | ⚠️ Partial | High | +| Constructor promotion | 8.0 | ✅ Supported | - | +| Intersection types | 8.1 | ✅ Supported | - | +| Readonly properties | 8.1 | ✅ Supported | - | +| Enums | 8.1 | ⚠️ Partial | High | +| First-class callables | 8.1 | ❌ Missing | Medium | +| Readonly classes | 8.2 | ❌ Missing | Medium | +| DNF types | 8.2 | ❌ Missing | Low | +| `#[\Override]` attribute | 8.3 | ❌ Missing | Low | +| Typed class constants | 8.3 | ❌ Missing | Medium | + +### 3.2 Enum Support + +```haskell +-- Extend AST for PHP 8.1 enums +data EnumDeclaration = EnumDeclaration + { enumName :: Text + , enumBackingType :: Maybe PHPType -- int | string + , enumCases :: [EnumCase] + , enumMethods :: [MethodDeclaration] + , enumImplements :: [Text] + } + deriving (Eq, Show, Generic) + +data EnumCase = EnumCase + { caseName :: Text + , caseValue :: Maybe Expression -- For backed enums + } + deriving (Eq, Show, Generic) +``` + +### 3.3 Nullsafe Operator + +```haskell +-- Add nullsafe property access +data Expression + = ... + | PropertyAccess Expression Text -- $obj->prop + | NullsafePropertyAccess Expression Text -- $obj?->prop + | MethodCall Expression Text [Argument] + | NullsafeMethodCall Expression Text [Argument] -- $obj?->method() + ... +``` + +--- + +## Phase 4: WordPress Integration + +**Goal**: Comprehensive WordPress integration documentation and tooling + +### 4.1 WordPress Integration Guide + +Create `docs/WORDPRESS.md`: + +```markdown +# WordPress Integration Guide + +## Quick Start + +### Using Pre-built Binary + +\`\`\`bash +# Download for your platform +curl -LO https://github.com/hyperpolymath/sanctify-php/releases/latest/download/sanctify-php-linux-x86_64 +chmod +x sanctify-php-linux-x86_64 +sudo mv sanctify-php-linux-x86_64 /usr/local/bin/sanctify-php + +# Analyze your theme +sanctify-php analyze ./wp-content/themes/my-theme/ +\`\`\` + +### Using Docker + +\`\`\`bash +docker run --rm -v $(pwd)/wp-content:/src \ + ghcr.io/hyperpolymath/sanctify-php analyze /src/themes/my-theme +\`\`\` + +## CI/CD Integration + +### GitHub Actions + +\`\`\`yaml +name: Security Analysis +on: [push, pull_request] + +jobs: + sanctify: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: hyperpolymath/sanctify-php-action@v1 + with: + path: ./wp-content/themes/my-theme + format: sarif + - uses: github/codeql-action/upload-sarif@v3 + with: + sarif_file: sanctify-results.sarif +\`\`\` + +## Configuration + +Create `sanctify.json` in theme root: + +\`\`\`json +{ + "wordpress": true, + "theme_type": "semantic", + "strict_types": "enforce", + "escaping": { + "semantic_context": true, + "indieweb": true + } +} +\`\`\` +``` + +### 4.2 GitHub Action + +Create reusable GitHub Action: + +```yaml +# action.yml +name: 'Sanctify PHP' +description: 'PHP security analysis and hardening' +inputs: + path: + description: 'Path to analyze' + required: true + format: + description: 'Output format (text, json, sarif, html)' + default: 'text' + fix: + description: 'Apply automatic fixes' + default: 'false' +runs: + using: 'docker' + image: 'Dockerfile' + args: + - analyze + - ${{ inputs.path }} + - --format=${{ inputs.format }} +``` + +### 4.3 Composer Integration + +For projects using Composer: + +```json +{ + "scripts": { + "security:analyze": "sanctify-php analyze ./src", + "security:fix": "sanctify-php fix ./src --policy=conservative", + "security:report": "sanctify-php report ./src --format=html -o security-report.html" + } +} +``` + +--- + +## Phase 5: php-aegis Integration + +**Goal**: Seamless integration with php-aegis runtime library + +### 5.1 Recognize php-aegis as Safe + +```haskell +-- Add php-aegis functions to safe function registry +aegisSafeFunctions :: Map Text SafetyLevel +aegisSafeFunctions = Map.fromList + [ ("Aegis\\Escape::html", SafeForHtml) + , ("Aegis\\Escape::attr", SafeForAttribute) + , ("Aegis\\Escape::url", SafeForUrl) + , ("Aegis\\Escape::js", SafeForJs) + , ("Aegis\\Semantic\\Turtle::escapeString", SafeForTurtleLiteral) + , ("Aegis\\Semantic\\Turtle::escapeIRI", SafeForTurtleIRI) + , ("Aegis\\IndieWeb\\Micropub::sanitizeContent", SafeForHtml) + ] +``` + +### 5.2 Auto-Insert php-aegis Calls + +Transform detected vulnerabilities to use php-aegis: + +```haskell +-- In Sanctify.Transform.Sanitize + +insertAegisEscaping :: TaintedSink -> Expression -> Expression +insertAegisEscaping sink expr = case sink of + HtmlOutput -> + FunctionCall "\\Aegis\\Escape::html" [expr] + + TurtleLiteralOutput -> + FunctionCall "\\Aegis\\Semantic\\Turtle::escapeString" [expr] + + TurtleIRIOutput -> + FunctionCall "\\Aegis\\Semantic\\Turtle::escapeIRI" [expr] + + MicropubContent -> + FunctionCall "\\Aegis\\IndieWeb\\Micropub::sanitizeContent" [expr] + + _ -> expr -- Fallback to WordPress functions +``` + +### 5.3 Configuration Option + +```json +{ + "transforms": { + "escaping_library": "php-aegis", // or "wordpress" or "custom" + "fallback_to_wordpress": true + } +} +``` + +--- + +## Timeline & Milestones + +| Phase | Focus | Target Version | +|-------|-------|----------------| +| Phase 1 | Distribution | v0.2.0 | +| Phase 2 | Semantic Web | v0.3.0 | +| Phase 3 | PHP 8.x Complete | v0.4.0 | +| Phase 4 | WordPress Integration | v0.5.0 | +| Phase 5 | php-aegis Integration | v1.0.0 | + +--- + +## Contributing + +We welcome contributions! Priority areas: + +1. **Distribution**: CI/CD for binary releases +2. **Parser**: PHP 8.1+ enum support +3. **Semantic**: RDF/Turtle detection and escaping rules +4. **Documentation**: WordPress integration examples + +See [CONTRIBUTING.md](./CONTRIBUTING.md) for guidelines. + +--- + +*SPDX-License-Identifier: MIT OR AGPL-3.0-or-later* +*SPDX-FileCopyrightText: 2024-2025 hyperpolymath* diff --git a/docs/STANDALONE.md b/docs/STANDALONE.md new file mode 100644 index 0000000..1672438 --- /dev/null +++ b/docs/STANDALONE.md @@ -0,0 +1,292 @@ +# Standalone vs Combined Capabilities + +This document defines what each tool must provide independently and the enhanced capabilities when used together. + +--- + +## Philosophy + +Each tool should be **fully functional standalone**. Integration provides **enhanced capabilities**, not basic functionality. + +``` +┌─────────────────────────────────────────────────────────────────┐ +│ Standalone Operation │ +├─────────────────────────────────────────────────────────────────┤ +│ │ +│ sanctify-php (alone) php-aegis (alone) │ +│ ┌─────────────────┐ ┌─────────────────┐ │ +│ │ Static Analysis │ │ Runtime Library │ │ +│ │ Auto-transform │ │ Escaping/Sanit. │ │ +│ │ Uses WP funcs │ │ Works anywhere │ │ +│ └─────────────────┘ └─────────────────┘ │ +│ │ +├─────────────────────────────────────────────────────────────────┤ +│ Combined Operation │ +├─────────────────────────────────────────────────────────────────┤ +│ │ +│ ┌─────────────────────────────────────────────────┐ │ +│ │ sanctify-php + php-aegis │ │ +│ │ │ │ +│ │ • sanctify detects → inserts php-aegis calls │ │ +│ │ • php-aegis provides runtime protection │ │ +│ │ • Semantic escaping (Turtle, JSON-LD) │ │ +│ │ • IndieWeb protocol security │ │ +│ │ • Deeper taint analysis with Aegis sinks │ │ +│ └─────────────────────────────────────────────────┘ │ +│ │ +└─────────────────────────────────────────────────────────────────┘ +``` + +--- + +## sanctify-php: Minimum Viable Standalone + +### Must Have (MVP) + +| Capability | Status | Notes | +|------------|--------|-------| +| Detect missing `strict_types` | ✅ | Core feature | +| Detect SQL injection | ✅ | Taint tracking | +| Detect XSS vulnerabilities | ✅ | Output escaping | +| Detect CSRF missing nonces | ✅ | WordPress-aware | +| Auto-add `strict_types` | ✅ | Transform | +| Auto-add WordPress escaping | ✅ | Uses `esc_html()` etc. | +| SARIF output for CI | ✅ | GitHub integration | +| **Pre-built binaries** | ❌ → Priority | Adoption blocker | +| **Composer install** | ❌ → Priority | Adoption blocker | + +### Standalone Behavior (Without php-aegis) + +When php-aegis is not installed, sanctify-php must: + +1. **Use WordPress functions for escaping**: + ```php + // sanctify-php auto-fix output (standalone) + echo esc_html($user_input); // NOT Aegis\Escape::html() + ``` + +2. **Use WordPress functions for sanitization**: + ```php + // sanctify-php auto-fix output (standalone) + $clean = sanitize_text_field($_POST['field']); + ``` + +3. **Warn about missing semantic escaping**: + ``` + WARNING: Turtle output detected at semantic.php:45 + No semantic escaping library found. + Consider installing php-aegis for proper Turtle escaping. + Using esc_html() as fallback (may break RDF syntax). + ``` + +### Installation Requirements (Standalone) + +```bash +# MUST work without Haskell +composer require --dev hyperpolymath/sanctify-php + +# Binary auto-downloads on install +# No manual steps required +``` + +--- + +## php-aegis: Minimum Viable Standalone + +### Must Have (MVP) + +| Capability | Status | Notes | +|------------|--------|-------| +| HTML escaping | ✅ | `Escape::html()` | +| Attribute escaping | ✅ | `Escape::attr()` | +| URL validation | ✅ | `Validate::url()` | +| Email validation | ✅ | `Validate::email()` | +| **PHP 7.4+ compatibility** | ❌ → Critical | Adoption blocker | +| **WordPress adapter** | ❌ → Priority | snake_case functions | +| **Int/IP/Domain validators** | ❌ → Priority | Common needs | +| **Turtle escaping** | ❌ → Priority | Unique value | + +### Standalone Behavior (Without sanctify-php) + +When sanctify-php is not used, php-aegis must: + +1. **Work with any PHP framework**: + ```php + // Generic PHP usage + use Aegis\Escape; + echo Escape::html($userInput); + ``` + +2. **Provide WordPress helpers**: + ```php + // WordPress plugin/theme usage + require_once 'vendor/autoload.php'; + // Functions auto-registered if ABSPATH defined + echo aegis_escape_html($userInput); + ``` + +3. **Not require static analysis**: + - Library is purely runtime + - Developer chooses where to use escaping + - No build step needed + +### Installation Requirements (Standalone) + +```bash +# MUST work on PHP 7.4+ +composer require hyperpolymath/php-aegis-compat # PHP 7.4-8.0 +# OR +composer require hyperpolymath/php-aegis # PHP 8.1+ +``` + +--- + +## Combined Capabilities + +When both tools are used together, additional capabilities unlock: + +### 1. Aegis-Aware Auto-Fix + +sanctify-php inserts php-aegis calls instead of WordPress functions: + +```php +// Before +echo $user_input; + +// After (with php-aegis) +echo \Aegis\Escape::html($user_input); + +// After (without php-aegis) +echo esc_html($user_input); +``` + +### 2. Semantic Context Detection + +sanctify-php detects Turtle/JSON-LD output and suggests correct Aegis escaping: + +```php +// sanctify-php detects Turtle context +header('Content-Type: text/turtle'); +echo "<{$subject}> <{$predicate}> \"{$object}\" ."; + +// Recommends: +echo "<" . \Aegis\Semantic\Turtle::escapeIRI($subject) . "> " + . "<" . \Aegis\Semantic\Turtle::escapeIRI($predicate) . "> " + . "\"" . \Aegis\Semantic\Turtle::escapeString($object) . "\" ."; +``` + +### 3. Deep Taint Analysis + +sanctify-php recognizes Aegis sanitizers as safe sinks: + +```php +// sanctify-php knows this is safe +$content = \Aegis\IndieWeb\Micropub::sanitizeContent($_POST['content']); +echo $content; // No warning - recognized as sanitized +``` + +### 4. Configuration Alignment + +Both tools share configuration: + +```json +// sanctify.json +{ + "runtime_library": "php-aegis", + "semantic_contexts": ["turtle", "jsonld"], + "transforms": { + "use_aegis": true, + "fallback": "wordpress" + } +} +``` + +--- + +## Feature Matrix + +| Feature | sanctify-php alone | php-aegis alone | Combined | +|---------|-------------------|-----------------|----------| +| Detect XSS | ✅ | ❌ | ✅ | +| Fix XSS | ✅ (WP funcs) | ❌ | ✅ (Aegis) | +| Runtime escaping | ❌ | ✅ | ✅ | +| Turtle escaping | ⚠️ Warning only | ✅ | ✅ Auto-insert | +| JSON-LD escaping | ⚠️ Warning only | ✅ | ✅ Auto-insert | +| IndieWeb sanitization | ⚠️ Warning only | ✅ | ✅ Auto-insert | +| Taint tracking | ✅ | ❌ | ✅ Enhanced | +| CI/CD integration | ✅ SARIF | ❌ | ✅ SARIF | +| WordPress integration | ✅ | ✅ | ✅ Seamless | +| PHP 7.4 support | ✅ (binary) | ⚠️ (compat pkg) | ✅ | + +--- + +## Adoption Path + +### Path A: Start with sanctify-php (Static Analysis First) + +```bash +# 1. Install and run analysis +composer require --dev hyperpolymath/sanctify-php +vendor/bin/sanctify-php analyze src/ + +# 2. Apply auto-fixes (uses WordPress functions) +vendor/bin/sanctify-php fix src/ + +# 3. Later: Add php-aegis for semantic escaping +composer require hyperpolymath/php-aegis + +# 4. Re-run sanctify to upgrade to Aegis calls +vendor/bin/sanctify-php fix src/ --use-aegis +``` + +### Path B: Start with php-aegis (Runtime Library First) + +```bash +# 1. Install runtime library +composer require hyperpolymath/php-aegis + +# 2. Manually add escaping where needed +# Use Aegis\Escape::html(), Aegis\Semantic\Turtle::escapeString(), etc. + +# 3. Later: Add sanctify-php for automated detection +composer require --dev hyperpolymath/sanctify-php + +# 4. Find missed spots +vendor/bin/sanctify-php analyze src/ +``` + +### Path C: Install Both (Recommended) + +```bash +# Install both together +composer require hyperpolymath/php-aegis +composer require --dev hyperpolymath/sanctify-php + +# Analyze and fix in one step +vendor/bin/sanctify-php fix src/ --use-aegis +``` + +--- + +## Minimum Implementation Checklist + +### sanctify-php v0.2.0 (Standalone-Ready) + +- [ ] Pre-built binaries (linux-x86_64, darwin-x86_64, darwin-arm64) +- [ ] Composer plugin that auto-downloads binary +- [ ] GitHub Action +- [ ] Standalone mode: use WordPress functions when Aegis not found +- [ ] Warning mode: alert when semantic escaping needed but Aegis missing + +### php-aegis v0.2.0 (Standalone-Ready) + +- [ ] php-aegis-compat package (PHP 7.4+) +- [ ] WordPress adapter (snake_case functions) +- [ ] Extended validators: `int()`, `ip()`, `domain()`, `uuid()`, `slug()` +- [ ] Turtle escaping: `Semantic\Turtle::escapeString()`, `escapeIRI()` +- [ ] Works without sanctify-php or any build step + +--- + +*SPDX-License-Identifier: MIT OR AGPL-3.0-or-later* +*SPDX-FileCopyrightText: 2024-2025 hyperpolymath* diff --git a/docs/TARGET-AUDIENCE.md b/docs/TARGET-AUDIENCE.md new file mode 100644 index 0000000..dc1e7ff --- /dev/null +++ b/docs/TARGET-AUDIENCE.md @@ -0,0 +1,231 @@ +# Target Audience & Use Cases + +This document clarifies when to use sanctify-php and php-aegis based on real-world integration feedback. + +--- + +## Quick Decision Matrix + +### Should I use sanctify-php? + +| Your Situation | Use sanctify-php? | Why | +|----------------|------------------|-----| +| New PHP project | ✅ Yes | Catch issues early | +| Legacy codebase audit | ✅ Yes | Find security debt | +| WordPress plugin/theme | ⚠️ Maybe | WP already has security APIs | +| CI/CD security gate | ✅ Yes (when binaries exist) | Automated scanning | +| **GHC not installed** | ❌ **No** | Tool cannot run | + +### Should I use php-aegis? + +| Your Situation | Use php-aegis? | Why | +|----------------|---------------|-----| +| WordPress plugin/theme | ⚠️ **Only for unique features** | WP core has equivalent security | +| Laravel/Symfony app | ✅ Yes | Complements framework security | +| Vanilla PHP app | ✅ Yes | Provides missing security layer | +| Semantic web (RDF/Turtle) | ✅ **Yes - unique value** | No other library handles this | +| IndieWeb (Micropub, etc.) | ✅ **Yes - unique value** | Protocol-specific security | +| ActivityPub/Fediverse | ✅ **Yes - unique value** | Content policy enforcement | + +--- + +## sanctify-php: When to Use + +### Ideal Use Cases + +1. **Security Audits** + - Scanning legacy codebases for vulnerabilities + - Pre-deployment security checks + - Compliance requirements (PCI, SOC2) + +2. **CI/CD Integration** + - Block PRs with security issues + - Generate SARIF reports for GitHub Security + - Track security debt over time + +3. **Code Transformation** + - Auto-add `declare(strict_types=1)` + - Insert missing escaping functions + - Enforce WordPress coding standards + +### When NOT to Use + +1. **GHC Not Available** (BLOCKER) + - sanctify-php requires Haskell compiler + - Until pre-built binaries exist, many environments can't use it + - Workaround: Docker container (when available) + +2. **Already Well-Secured WordPress Plugins** + - Mature plugins like Zotpress already follow WP security best practices + - sanctify-php adds limited value if codebase is already clean + - May still be useful for regression detection + +3. **Quick One-Off Scripts** + - Overhead not worth it for disposable code + - Use php-aegis runtime protection instead + +--- + +## php-aegis: When to Use + +### Ideal Use Cases + +1. **Non-WordPress PHP Applications** + ```php + // Laravel, Symfony, vanilla PHP + use Aegis\Escape; + echo Escape::html($userInput); + ``` + +2. **Semantic Web Applications** (UNIQUE VALUE) + ```php + // RDF/Turtle output - WordPress can't do this + use Aegis\Semantic\Turtle; + echo '"' . Turtle::escapeString($label) . '"'; + ``` + +3. **IndieWeb Applications** (UNIQUE VALUE) + ```php + // Micropub content sanitization + use Aegis\IndieWeb\Micropub; + $safe = Micropub::sanitizeContent($content, ['allow_html' => true]); + ``` + +4. **ActivityPub/Fediverse** (UNIQUE VALUE) + ```php + // Federated content policies + use Aegis\ActivityPub\Content; + $safe = Content::sanitize($post, ContentPolicy::STRICT); + ``` + +### When NOT to Use + +1. **WordPress Plugins/Themes (for standard security)** + + WordPress already provides: + | Need | WordPress Function | php-aegis Adds Nothing | + |------|-------------------|----------------------| + | HTML escape | `esc_html()` | ❌ | + | Attribute escape | `esc_attr()` | ❌ | + | URL escape | `esc_url()` | ❌ | + | JS escape | `esc_js()` | ❌ | + | Email validation | `is_email()` | ❌ | + | Sanitize text | `sanitize_text_field()` | ❌ | + + **Exception**: Use php-aegis for Turtle/RDF/IndieWeb in WordPress themes. + +2. **PHP 7.4 Environments (until compat package exists)** + - php-aegis requires PHP 8.1+ + - WordPress supports PHP 7.4+ + - Need `php-aegis-compat` package first + +--- + +## Combined Use: When Both Tools Add Value + +The tools complement each other best when: + +### Scenario: Semantic WordPress Theme + +``` +┌─────────────────────────────────────────────────────────────┐ +│ WordPress theme with RDF/Turtle output (IndieWeb/Semantic) │ +├─────────────────────────────────────────────────────────────┤ +│ │ +│ sanctify-php: │ +│ • Detects Turtle output context │ +│ • Warns: "esc_html() wrong for Turtle, use Aegis" │ +│ • Auto-inserts: Aegis\Semantic\Turtle::escapeString() │ +│ │ +│ php-aegis: │ +│ • Provides runtime Turtle escaping │ +│ • W3C-compliant string/IRI handling │ +│ • WordPress doesn't have this capability │ +│ │ +└─────────────────────────────────────────────────────────────┘ +``` + +### Scenario: Laravel API with Security Requirements + +``` +┌─────────────────────────────────────────────────────────────┐ +│ Laravel API with strict security requirements │ +├─────────────────────────────────────────────────────────────┤ +│ │ +│ sanctify-php (CI/CD): │ +│ • SARIF reports in GitHub Security │ +│ • Block PRs with SQL injection │ +│ • Enforce type hints on all functions │ +│ │ +│ php-aegis (runtime): │ +│ • Defense in depth for validation │ +│ • Consistent escaping API │ +│ • Additional validators (IP, UUID, credit card) │ +│ │ +└─────────────────────────────────────────────────────────────┘ +``` + +### Scenario: Standard WordPress Plugin + +``` +┌─────────────────────────────────────────────────────────────┐ +│ Standard WordPress plugin (no semantic web) │ +├─────────────────────────────────────────────────────────────┤ +│ │ +│ sanctify-php: ⚠️ Limited value │ +│ • May catch issues WP doesn't │ +│ • Useful for security audit │ +│ • But WP security is already comprehensive │ +│ │ +│ php-aegis: ❌ No value │ +│ • WordPress already has esc_html(), etc. │ +│ • Adding Aegis duplicates existing functions │ +│ • Exception: Use for unique validators WP lacks │ +│ │ +└─────────────────────────────────────────────────────────────┘ +``` + +--- + +## Summary: Unique Value Propositions + +### sanctify-php Unique Value + +| Capability | Competition | sanctify-php Advantage | +|------------|-------------|----------------------| +| PHP static analysis | PHPStan, Psalm | Security-focused, not just types | +| WordPress awareness | PHPCS-WPCS | Deeper taint tracking | +| Auto-fix transforms | None | Automatic code hardening | +| SARIF output | Few tools | GitHub Security integration | +| Semantic context | None | Detects Turtle/JSON-LD contexts | + +### php-aegis Unique Value + +| Capability | Competition | php-aegis Advantage | +|------------|-------------|---------------------| +| Turtle/RDF escaping | **None** | Only library for semantic web | +| Micropub sanitization | **None** | IndieWeb protocol security | +| ActivityPub content | **None** | Fediverse content policies | +| Context-aware escaping | Laravel, WP | Unified API across frameworks | +| UUID/IP/credit card | Various | Consolidated validation library | + +--- + +## Recommendations + +### For php-aegis Team + +1. **Don't compete with WordPress core** — document that php-aegis is for non-WP apps or unique WP needs +2. **Focus on unique value** — Turtle, IndieWeb, ActivityPub are unserved markets +3. **Create framework adapters** — Laravel, Symfony, WordPress (for unique features only) + +### For sanctify-php Team + +1. **Pre-built binaries are MANDATORY** — tool literally cannot be used without them +2. **Docker image as fallback** — for environments that can't install binaries +3. **Document when NOT to use** — mature WP plugins may not benefit + +--- + +*SPDX-License-Identifier: MIT OR AGPL-3.0-or-later* +*SPDX-FileCopyrightText: 2024-2025 hyperpolymath*