[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7AS07K8N7P4J8VQ59ZEAWG4":3,"skill-same:01M7AS07K8N7P4J8VQ59ZEAWG4":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M7AS07K8N7P4J8VQ59ZEAWG4","codebase-modernization",null,"Use this skill whenever you are working on an EXISTING codebase that needs to be modernized, migrated, or brought up to the Security-First Scrum standard. Trigger when asked to: fix security issues in legacy code, migrate authentication to MSAL\u002FEntra ID, replace hardcoded secrets with Key Vault, fix SQL injection, add authorization to unprotected endpoints, extract business logic from controllers, add tests to untested code, install a DevSecOps pipeline, modernize infrastructure with Private Endpoints or Managed Identity, or perform any incremental security hardening of existing .NET \u002F React \u002F Blazor \u002F Cosmos DB \u002F PostgreSQL \u002F Databricks code on Azure. This skill governs the migration path; the security-first-scrum skill governs the destination. The three laws still apply, but the sequencing and tactics are different: you are a surgeon operating on a live patient, not building from scratch.","the-vibey-project\u002Fvibey","the-vibey-project","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F329298758?v=4","01M7AJHGZ9722CTJ4JNQZVRH0Q","the vibey project","01M7AJHGZVMG2K7TGXQ6XFHVG3",5,"MIT","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fsecurity-first-dev\u002Fskills\u002Fcodebase-modernization\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: codebase-modernization\ndescription: >\n  Use this skill whenever you are working on an EXISTING codebase that needs to be modernized,\n  migrated, or brought up to the Security-First Scrum standard. Trigger when asked to: fix\n  security issues in legacy code, migrate authentication to MSAL\u002FEntra ID, replace hardcoded\n  secrets with Key Vault, fix SQL injection, add authorization to unprotected endpoints, extract\n  business logic from controllers, add tests to untested code, install a DevSecOps pipeline,\n  modernize infrastructure with Private Endpoints or Managed Identity, or perform any incremental\n  security hardening of existing .NET \u002F React \u002F Blazor \u002F Cosmos DB \u002F PostgreSQL \u002F Databricks\n  code on Azure. This skill governs the migration path; the security-first-scrum skill governs\n  the destination. The three laws still apply, but the sequencing and tactics are different:\n  you are a surgeon operating on a live patient, not building from scratch.\n---\n\n# Security-First Scrum: Codebase Modernization\n\nYou are modernizing an existing codebase toward the Security-First Scrum standard. The rules are\ndifferent from greenfield work. Read this document in full before touching any file.\n\n---\n\n## PART 1: THREE LAWS (UNCHANGED — ALWAYS IN THIS ORDER)\n\n**Law 1 — Security First.** Never introduce a new vulnerability while fixing an old one. Never\nleave a surface more exposed than you found it.\n\n**Law 2 — People First.** The humans own the migration strategy and the risk decisions. You\nexecute the technical steps they have scoped. Do not attempt autonomous infrastructure changes,\nsecret rotation, or scope expansion without confirmation.\n\n**Law 3 — Incremental \u002F Agile.** Every PR must leave the codebase in a better and working state.\nNo big-bang rewrites. No broken builds between steps.\n\n---\n\n## PART 2: MODERNIZATION PRIME DIRECTIVE\n\nBefore touching any file:\n\n1. Run the Phase 0 assessment protocol. Understand what you are walking into.\n2. Confirm the scope of this specific task with the human. Scope creep during migration breaks\n   things.\n3. Identify whether the change is security-critical (Phase 1-3), architectural (Phase 4-5), or\n   operational (Phase 6-8). Do not mix phases in a single PR.\n4. Verify existing tests pass before you start. You own the baseline. If they were already broken,\n   surface that immediately — do not inherit a broken build silently.\n5. Make your change. Re-run tests. The codebase must be passing when you are done.\n\n**The iron rule of modernization:** every PR leaves the codebase more secure and working than\nbefore. A PR that improves architecture but introduces a regression is not acceptable. A PR that\nremoves a vulnerability but breaks auth is not acceptable.\n\n**Stop and surface to the human when:**\n- You discover a vulnerability outside the scope of the current task (log it; do not fix it\n  unilaterally)\n- The existing code has no tests and adding the security control requires refactoring untested code\n- A dependency is so outdated that upgrading it would require cascading changes beyond sprint scope\n- You find hardcoded credentials — rotate them before doing anything else (Phase 1)\n\n---\n\n## PART 3: TRIAGE PRIORITY SYSTEM\n\nWhen a codebase has multiple issues, address them in this order. Do not reorder based on what\nseems more interesting or architectural.\n\n| Priority | Category | Rationale |\n|---|---|---|\n| **P0 — Immediate** | Hardcoded secrets \u002F credentials in source code | Active exposure. Every minute counts. |\n| **P0 — Immediate** | Broken or missing authentication on production endpoints | Active exploitation surface. |\n| **P1 — This Sprint** | SQL injection \u002F non-parameterized queries | High CVSS; straightforward fix. |\n| **P1 — This Sprint** | `localStorage` token storage in React | XSS + token theft = full account compromise. |\n| **P1 — This Sprint** | Missing or permissive CORS (`AllowAnyOrigin`) | Cross-origin attack surface on production. |\n| **P2 — Next Sprint** | Implicit Grant auth flow still in use | Deprecated; migration is planned work. |\n| **P2 — Next Sprint** | Connection strings with keys (replace with Managed Identity) | High value; requires infra coordination. |\n| **P2 — Next Sprint** | Missing rate limiting on public endpoints | Abuse surface; not currently exploited. |\n| **P3 — Backlog** | Architecture violations (business logic in controllers, etc.) | Quality debt; not an active security risk. |\n| **P3 — Backlog** | Missing test coverage on non-security paths | Quality debt; address incrementally. |\n| **P3 — Backlog** | Missing XML doc comments \u002F docstrings | Documentation debt. |\n\n---\n\n## PART 4: PHASE 0 — CODEBASE ASSESSMENT (RUN BEFORE TOUCHING ANYTHING)\n\nRun this assessment on every codebase you are asked to modernize. Produce a written finding\nsummary before writing a single line of migration code.\n\n### 4.1 Secrets Scan — Run First, No Exceptions\n\n```bash\n# Full history scan — not just HEAD\ngitleaks detect --source . --log-opts \"--all\" --report-format json --report-path gitleaks-report.json\n# Current working tree\ngitleaks detect --source . --report-format json --report-path gitleaks-current.json\n# npm \u002F pip dependency secrets\ntrufflehog filesystem . --json > trufflehog-report.json\n```\n\nIf secrets are found: Stop. Do not proceed with any other migration work. Report to the human\nimmediately. Credentials must be rotated before the codebase is touched further.\n\n### 4.2 Dependency Vulnerability Scan\n\n```bash\ndotnet list package --vulnerable --include-transitive > dotnet-vulns.txt\nnpm audit --json > npm-audit.json\npip install safety && safety check --json > safety-report.json\npip install bandit && bandit -r src\u002F -f json -o bandit-report.json\n```\n\nCategorize: CRITICAL (this sprint), HIGH (next sprint), MEDIUM\u002FLOW (backlog).\n\n### 4.3 Authentication Surface Map\n\nFor every .NET controller and every React\u002FBlazor route, record:\n```\nEndpoint \u002F Route | Auth required? | Current mechanism | Auth flow | Token storage | Notes\n```\n\nFlag any endpoint that:\n- Has no `[Authorize]` decorator and serves non-public data\n- Uses Implicit Grant flow\n- Stores tokens in `localStorage`\n- Uses a shared app registration across environments\n- Has hardcoded `ClientSecret` in configuration\n\n### 4.4 Authorization \u002F BOLA Check\n\nFor every endpoint that returns or modifies user-owned data:\n```\nEndpoint | Returns user-owned data? | Ownership check present? | Where? (controller\u002Fservice\u002Fnone)\n```\n\n### 4.5 Database Query Safety Audit\n\n```bash\n# .NET — find raw SQL with string interpolation\ngrep -rn \"FromSqlRaw\\|ExecuteSqlRaw\\|FromSqlInterpolated\" src\u002F --include=\"*.cs\"\ngrep -rn '\"\\s*SELECT\\|\"\\s*INSERT\\|\"\\s*UPDATE\\|\"\\s*DELETE' src\u002F --include=\"*.cs\"\n# Python\ngrep -rn 'execute.*f\"SELECT\\|execute.*%.*SELECT' src\u002F --include=\"*.py\"\n```\n\n### 4.6 Secrets in Configuration Files\n\n```bash\ngrep -rn \"Password=\\|pwd=\\|AccountKey=\\|SharedAccessKey=\" . \\\n  --include=\"*.json\" --include=\"*.yaml\" --include=\"*.yml\" --include=\"*.env\" \\\n  --exclude-dir=node_modules --exclude-dir=.git\n```\n\n### 4.7 Architecture Layer Violations (.NET)\n\n```bash\n# Business logic \u002F DB in controllers\ngrep -rn \"DbContext\\|CosmosClient\\|NpgsqlConnection\" src\u002F --include=\"*.cs\" | grep -i \"controller\"\n# Repository calls from controllers\ngrep -rn \"IRepository\\|Repository\" src\u002F --include=\"*.cs\" | grep -i \"controller\"\n```\n\n### 4.8 Frontend Security Audit\n\n```bash\ngrep -rn \"localStorage\" src\u002F --include=\"*.ts\" --include=\"*.tsx\" | grep -i \"token\\|auth\\|jwt\"\ngrep -rn \"dangerouslySetInnerHTML\" src\u002F --include=\"*.tsx\" --include=\"*.jsx\"\ngrep -rn \"AllowAnyOrigin\\|origin.*\\*\" . --include=\"*.ts\" --include=\"*.json\"\n```\n\n### 4.9 Assessment Report Template\n\n```markdown\n## Codebase Assessment — [Date] — [Repo Name]\n\n### P0 Findings (Immediate)\n- [ ] [Finding] — [File:Line] — [Impact]\n\n### P1 Findings (This Sprint)\n### P2 Findings (Next Sprint)\n### P3 Findings (Backlog)\n\n### Existing Test Coverage\n- Overall: X%\n- Security test coverage: X% (estimate)\n- Integration tests present: yes\u002Fno\n\n### Architecture Health\n- Layer violations found: X\n- Missing interfaces: X\n- Controllers with direct DB access: X\n```\n\nHand this to the human before writing any migration code. They scope the sprints; you execute.\n\n---\n\n## PART 5: PHASE 1 — SECRETS AND CREDENTIALS (HIGHEST PRIORITY)\n\n### 5.1 When You Find a Hardcoded Secret\n\n1. Do not commit the file with the secret still present. Never.\n2. Report to the human immediately — they must rotate it before you make the replacement commit.\n3. After rotation is confirmed, replace with Key Vault reference pattern (§5.2).\n4. After the replacement PR is merged, clean git history using `git filter-repo` (NOT\n   `git filter-branch` — deprecated).\n\n### 5.2 Replacing Connection Strings with Key Vault References\n\n**Before (dangerous — never leave in place):**\n```json\n{\n  \"ConnectionStrings\": {\n    \"CosmosDb\": \"AccountEndpoint=https:\u002F\u002Faccount.documents.azure.com:443\u002F;AccountKey=ACTUAL_KEY;\"\n  }\n}\n```\n\n**Step 1 — Add Key Vault to configuration bootstrap:**\n```csharp\n\u002F\u002F Program.cs\nvar kvName = builder.Configuration[\"KeyVaultName\"]; \u002F\u002F non-secret; safe in appsettings\nif (!string.IsNullOrEmpty(kvName))\n{\n    var kvUri = new Uri($\"https:\u002F\u002F{kvName}.vault.azure.net\u002F\");\n    builder.Configuration.AddAzureKeyVault(\n        kvUri, new DefaultAzureCredential(),\n        new AzureKeyVaultConfigurationOptions { ReloadInterval = TimeSpan.FromMinutes(5) });\n}\n```\n\n**Step 2 — Replace Cosmos DB connection string with Managed Identity:**\n```csharp\n\u002F\u002F BEFORE (delete this)\nvar cosmosClient = new CosmosClient(configuration[\"ConnectionStrings:CosmosDb\"]);\n\u002F\u002F AFTER\nvar credential = builder.Environment.IsDevelopment()\n    ? new DefaultAzureCredential()\n    : new ManagedIdentityCredential();\nservices.AddSingleton(_ => new CosmosClient(\n    configuration[\"CosmosDb:Endpoint\"], credential,\n    new CosmosClientOptions { ConnectionMode = ConnectionMode.Direct }));\n```\n\n**Step 3 — Replace PostgreSQL connection string with Managed Identity token:**\n```csharp\n\u002F\u002F BEFORE (delete this)\nservices.AddNpgsqlDataSource(configuration[\"ConnectionStrings:PostgreSQL\"]);\n\u002F\u002F AFTER\nvar connStringWithoutPassword = configuration[\"PostgreSQL:ConnectionStringNoPassword\"];\nservices.AddSingleton(_ =>\n{\n    var credential = builder.Environment.IsDevelopment()\n        ? new DefaultAzureCredential()\n        : new ManagedIdentityCredential();\n    var dataSourceBuilder = new NpgsqlDataSourceBuilder(connStringWithoutPassword);\n    dataSourceBuilder.UsePeriodicPasswordProvider(async (_, ct) =>\n    {\n        var token = await credential.GetTokenAsync(new TokenRequestContext(\n            new[] { \"https:\u002F\u002Fossrdbms-aad.database.windows.net\u002F.default\" }), ct);\n        return token.Token;\n    }, TimeSpan.FromHours(4), TimeSpan.FromSeconds(10));\n    return dataSourceBuilder.Build();\n});\n```\n\n### 5.3 .gitignore — Verify Completeness\n\n```\n.env\n.env.*\n!.env.example\nappsettings.Development.json\nappsettings.Production.json\nappsettings.Staging.json\nlocal.settings.json\nlaunchSettings.json\n*.pem\n*.key\n*.pfx\nsecrets\u002F\n.azure\u002F\n.aws\u002F\n.ssh\u002F\n```\n\n---\n\n## PART 6: PHASE 2 — AUTHENTICATION AND AUTHORIZATION MIGRATION\n\n### 6.1 Find Unprotected Controllers\n\n```bash\ngrep -rn \"public class.*Controller\" src\u002F --include=\"*.cs\" -l | while read f; do\n  if ! grep -q \"\\[Authorize\" \"$f\"; then\n    echo \"No [Authorize] found: $f\"\n  fi\ndone\ngrep -rn \"\\[AllowAnonymous\\]\" src\u002F --include=\"*.cs\"  # each needs a documented reason\n```\n\n### 6.2 Migrating to Microsoft.Identity.Web\n\n**Before (legacy JWT):**\n```csharp\nservices.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)\n    .AddJwtBearer(options => {\n        options.TokenValidationParameters = new TokenValidationParameters {\n            ValidIssuer = \"https:\u002F\u002Fsts.windows.net\u002FYOUR-TENANT\u002F\",\n            ValidAudience = \"api:\u002F\u002FYOUR-APP-ID\",\n            \u002F\u002F Common legacy mistake: ClockSkew left at default 5 minutes\n        };\n    });\n```\n\n**After (Microsoft.Identity.Web):**\n```csharp\nbuilder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)\n    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection(\"AzureAd\"));\nbuilder.Services.AddAuthorizationBuilder()\n    .AddPolicy(\"AdminOnly\",     p => p.RequireRole(\"Admin\"))\n    .AddPolicy(\"ReaderOrAdmin\", p => p.RequireRole(\"Reader\", \"Admin\"))\n    .AddPolicy(\"WriterOrAdmin\", p => p.RequireRole(\"Writer\", \"Admin\"));\n```\n\nRequired packages:\n```bash\ndotnet add package Microsoft.Identity.Web\ndotnet add package Azure.Identity\n# Remove any hand-rolled JWT validation packages\n```\n\n### 6.3 Adding [Authorize] — Controller by Controller\n\nDo this controller-by-controller, not as a mass change. Each controller = its own PR:\n\n```csharp\n[ApiController]\n[Route(\"api\u002Fv1\u002F[controller]\")]\n[Authorize]  \u002F\u002F minimum: authenticated caller required\npublic class DocumentsController : ControllerBase { }\n\n[HttpGet(\"{id}\")]\n[Authorize(Policy = \"ReaderOrAdmin\")]\npublic async Task\u003CActionResult\u003CDocumentResponse>> GetByIdAsync(string id, CancellationToken ct) { }\n\n[HttpGet(\"health\")]\n[AllowAnonymous] \u002F\u002F REASON: Public health check — no data returned\npublic IActionResult Health() => Ok(\"healthy\");\n```\n\n### 6.4 Adding BOLA Protection to Existing Endpoints\n\nBOLA is the most common API vulnerability and is usually completely absent. Add it to the\nservice layer — not the controller:\n\n```csharp\n\u002F\u002F BEFORE: No ownership check\npublic async Task\u003CDocumentModel> GetDocumentAsync(string documentId, CancellationToken ct)\n{\n    return await _repository.FindByIdAsync(documentId, ct);\n}\n\n\u002F\u002F AFTER: Ownership enforced before data is returned\npublic async Task\u003CDocumentModel> GetDocumentAsync(\n    string documentId, string requestingUserId, CancellationToken ct)\n{\n    var document = await _repository.FindByIdAsync(documentId, ct);\n    if (document.OwnerId != requestingUserId)\n        throw new ResourceOwnershipException(\n            $\"User {requestingUserId} does not own document {documentId}\");\n    return document;\n}\n```\n\nController side — extract userId from JWT:\n```csharp\nvar userId = User.GetObjectId()  \u002F\u002F Microsoft.Identity.Web extension method\n    ?? throw new UnauthorizedAccessException(\"UserId claim missing from token\");\nvar document = await _documentService.GetDocumentAsync(id, userId, ct);\n```\n\n### 6.5 Migrating React from localStorage to sessionStorage\n\n```typescript\n\u002F\u002F BEFORE — delete this\ncache: { cacheLocation: \"localStorage\" }\n\u002F\u002F AFTER\ncache: { cacheLocation: \"sessionStorage\", storeAuthStateInCookie: false }\n```\n\n### 6.6 Migrating from Implicit Grant to Authorization Code + PKCE\n\n**What you do (code):** Verify MSAL.js v3 is installed.\n```bash\nnpm install @azure\u002Fmsal-browser@latest @azure\u002Fmsal-react@latest\n```\n\n**What the human does (Azure portal):**\n- App registration → Authentication → Remove checkboxes for \"Access tokens\" and \"ID tokens\"\n  under Implicit grant.\n- Verify redirect URIs are correct.\n\n### 6.7 Middleware Pipeline Order — Fix If Wrong\n\nThis is the single most common .NET security misconfiguration:\n\n```csharp\n\u002F\u002F CORRECT ORDER\napp.UseHsts();\napp.UseHttpsRedirection();\napp.UseSerilogRequestLogging();\napp.UseRouting();\napp.UseRateLimiter();\napp.UseCors(\"SpaPolicy\");\napp.UseAuthentication();  \u002F\u002F WHO are you? — MUST come before UseAuthorization\napp.UseAuthorization();   \u002F\u002F WHAT can you do?\napp.MapControllers();\n```\n\nIf `UseAuthorization` appears before `UseAuthentication` in existing code: this is a P0 finding.\nThe middleware silently treats all requests as unauthenticated. Fix immediately.\n\n---\n\n## PART 7: PHASE 3 — INPUT VALIDATION AND QUERY SAFETY\n\n### 7.1 Replacing String-Interpolated SQL Queries\n\n**.NET \u002F Npgsql:**\n```csharp\n\u002F\u002F BEFORE — SQL injection vulnerable\nvar users = await _conn.QueryAsync\u003CUser>(\n    $\"SELECT * FROM users WHERE email = '{email}' AND tenant_id = '{tenantId}'\");\n\u002F\u002F AFTER — parameterized\nvar users = await _conn.QueryAsync\u003CUser>(\n    \"SELECT * FROM users WHERE email = @email AND tenant_id = @tenantId\",\n    new { email, tenantId });\n```\n\n**.NET \u002F Cosmos DB:**\n```csharp\n\u002F\u002F BEFORE — string interpolation in Cosmos query\nvar query = new QueryDefinition(\n    $\"SELECT * FROM c WHERE c.userId = '{userId}' AND c.type = '{docType}'\");\n\u002F\u002F AFTER — parameterized\nvar query = new QueryDefinition(\n    \"SELECT * FROM c WHERE c.userId = @userId AND c.type = @docType\")\n    .WithParameter(\"@userId\", userId)\n    .WithParameter(\"@docType\", docType);\n```\n\n**EF Core:**\n```csharp\n\u002F\u002F BEFORE — vulnerable\nvar results = _context.Users.FromSqlRaw($\"SELECT * FROM Users WHERE Id = {userId}\");\n\u002F\u002F AFTER — prefer LINQ (EF generates safe SQL)\nvar results = _context.Users.Where(u => u.Id == userId);\n```\n\n### 7.2 Adding FluentValidation\n\n```bash\ndotnet add package FluentValidation\ndotnet add package FluentValidation.DependencyInjectionExtensions\n# Do NOT install FluentValidation.AspNetCore — it is deprecated\n```\n\n```csharp\npublic class CreateUserRequestValidator : AbstractValidator\u003CCreateUserRequest>\n{\n    public CreateUserRequestValidator()\n    {\n        RuleFor(x => x.Name).NotEmpty().MaximumLength(100)\n            .Matches(@\"^[\\w\\s\\-'\\.]+$\").WithMessage(\"Name contains invalid characters.\");\n        RuleFor(x => x.Email).NotEmpty().EmailAddress().MaximumLength(254);\n    }\n}\nbuilder.Services.AddValidatorsFromAssemblyContaining\u003CCreateUserRequestValidator>();\n```\n\n### 7.3 Fixing dangerouslySetInnerHTML\n\n```bash\ngrep -rn \"dangerouslySetInnerHTML\" src\u002F --include=\"*.tsx\" --include=\"*.jsx\"\n```\n\nFor each hit with user-controlled content:\n```tsx\n\u002F\u002F BEFORE — XSS vulnerability\n\u003Cdiv dangerouslySetInnerHTML={{ __html: userProfile.bio }} \u002F>\n\u002F\u002F AFTER — DOMPurify sanitization\nimport DOMPurify from 'dompurify';\n\u003Cdiv dangerouslySetInnerHTML={{\n  __html: DOMPurify.sanitize(userProfile.bio, {\n    ALLOWED_TAGS: ['p', 'br', 'strong', 'em', 'a'],\n    FORBID_TAGS: ['script', 'style', 'iframe'],\n    FORBID_ATTR: ['onerror', 'onload', 'onclick'],\n  })\n}} \u002F>\n```\n\n### 7.4 Tightening CORS\n\n```csharp\n\u002F\u002F BEFORE — never acceptable in production\napp.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());\n\u002F\u002F AFTER — exact allowed origins from configuration\nvar allowedOrigins = builder.Configuration\n    .GetSection(\"Cors:AllowedOrigins\").Get\u003Cstring[]>()\n    ?? throw new InvalidOperationException(\"Cors:AllowedOrigins must be configured\");\nbuilder.Services.AddCors(options =>\n{\n    options.AddPolicy(\"SpaPolicy\", policy => policy\n        .WithOrigins(allowedOrigins)\n        .AllowAnyHeader().AllowAnyMethod().AllowCredentials());\n});\n```\n\n### 7.5 Adding Rate Limiting\n\n```csharp\nbuilder.Services.AddRateLimiter(options =>\n{\n    options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;\n    options.GlobalLimiter = PartitionedRateLimiter.Create\u003CHttpContext, string>(\n        httpContext => RateLimitPartition.GetFixedWindowLimiter(\n            partitionKey: httpContext.User.Identity?.Name\n                ?? httpContext.Connection.RemoteIpAddress?.ToString() ?? \"anon\",\n            factory: _ => new FixedWindowRateLimiterOptions\n            {\n                PermitLimit = 60, Window = TimeSpan.FromMinutes(1), QueueLimit = 0,\n            }));\n});\n\u002F\u002F In middleware pipeline — MUST be after UseRouting, before UseAuthentication\napp.UseRateLimiter();\n```\n\n---\n\n## PART 8: PHASE 4 — ARCHITECTURE REFACTORING (P3 PRIORITY)\n\n**Do not start Phase 4 if P0–P2 work is outstanding. Architecture refactoring carries the most\nrisk of regressions. Every change must be covered by tests before and after.**\n\n### 8.1 Extracting Business Logic from Controllers\n\nUse the extract → interface → test → delete approach (never all at once):\n\n```csharp\n\u002F\u002F BEFORE: Controller doing direct DB work and business logic\n[HttpPost]\npublic async Task\u003CIActionResult> CreateOrder(CreateOrderRequest request)\n{\n    if (request.Quantity > 100) return BadRequest(\"Quantity exceeds limit\");  \u002F\u002F business logic\n    var order = new Order { ... };\n    await _dbContext.Orders.AddAsync(order);   \u002F\u002F direct DB — wrong layer\n    await _dbContext.SaveChangesAsync();\n    return CreatedAtAction(...);\n}\n\n\u002F\u002F AFTER STEP 1: Interface first\npublic interface IOrderService\n{\n    Task\u003COrderModel> CreateOrderAsync(\n        CreateOrderRequest request, string requestingUserId, CancellationToken ct);\n}\n\n\u002F\u002F AFTER STEP 2: Implement the service (write test first)\npublic class OrderService : IOrderService\n{\n    private readonly IOrderRepository _repository;\n    public async Task\u003COrderModel> CreateOrderAsync(\n        CreateOrderRequest request, string requestingUserId, CancellationToken ct)\n    {\n        if (request.Quantity > 100)\n            throw new ValidationException(\"Quantity exceeds the maximum of 100.\");\n        var order = new Order { OwnerId = requestingUserId, ... };\n        return await _repository.SaveAsync(order, ct);\n    }\n}\n\n\u002F\u002F AFTER STEP 3: Controller becomes thin\n[HttpPost]\n[Authorize(Policy = \"WriterOrAdmin\")]\npublic async Task\u003CActionResult\u003COrderResponse>> CreateAsync(\n    CreateOrderRequest request, CancellationToken ct)\n{\n    var userId = User.GetObjectId()\n        ?? throw new UnauthorizedAccessException(\"UserId missing from token\");\n    var order = await _orderService.CreateOrderAsync(request, userId, ct);\n    return CreatedAtAction(nameof(GetByIdAsync), new { id = order.Id },\n        _mapper.Map\u003COrderResponse>(order));\n}\n```\n\n### 8.2 Extracting Repositories from Services\n\n```csharp\n\u002F\u002F Interface in Infrastructure\u002FRepositories\u002FInterfaces\u002F\npublic interface IOrderRepository\n{\n    Task\u003COrderModel> FindByIdAsync(string id, CancellationToken ct);\n    Task\u003COrderModel> SaveAsync(OrderModel order, CancellationToken ct);\n    Task DeleteAsync(string id, CancellationToken ct);\n}\n\n\u002F\u002F Fake for unit tests (in Mocks\u002F)\npublic class FakeOrderRepository : IOrderRepository\n{\n    private readonly Dictionary\u003Cstring, OrderModel> _store = new();\n    public Task\u003COrderModel> FindByIdAsync(string id, CancellationToken ct)\n    {\n        if (!_store.TryGetValue(id, out var order))\n            throw new NotFoundException($\"Order {id} not found.\");\n        return Task.FromResult(order);\n    }\n    public Task\u003COrderModel> SaveAsync(OrderModel order, CancellationToken ct)\n    {\n        _store[order.Id] = order; return Task.FromResult(order);\n    }\n    public Task DeleteAsync(string id, CancellationToken ct)\n    {\n        if (!_store.Remove(id)) throw new NotFoundException($\"Order {id} not found.\");\n        return Task.CompletedTask;\n    }\n    public IReadOnlyList\u003COrderModel> GetAll() => _store.Values.ToList();\n    public int Count => _store.Count;\n    public void Clear() => _store.Clear();\n}\n```\n\n### 8.3 Typed Exception Hierarchy\n\n```csharp\n\u002F\u002F Domain layer\npublic abstract class AppException : Exception { ... }\npublic sealed class ValidationException : AppException { ... }\npublic sealed class NotFoundException : AppException { ... }\npublic sealed class AuthException : AppException { ... }          \u002F\u002F never retry\npublic sealed class ResourceOwnershipException : AppException { ... } \u002F\u002F never retry\npublic sealed class TransientException : AppException { ... }    \u002F\u002F retry with backoff\n\n\u002F\u002F Global exception handler — maps to RFC 7807 ProblemDetails\npublic class GlobalExceptionHandler : IExceptionHandler\n{\n    public async ValueTask\u003Cbool> TryHandleAsync(HttpContext ctx, Exception ex, CancellationToken ct)\n    {\n        var (statusCode, title) = ex switch\n        {\n            ValidationException         => (400, \"Validation failed\"),\n            NotFoundException           => (404, \"Resource not found\"),\n            AuthException               => (401, \"Authentication required\"),\n            ResourceOwnershipException  => (403, \"Access denied\"),\n            TransientException          => (503, \"Service temporarily unavailable\"),\n            _                           => (500, \"An unexpected error occurred\"),\n        };\n        \u002F\u002F Never leak internal details to clients\n        var problem = new ProblemDetails\n        {\n            Status = statusCode, Title = title,\n            Extensions = { [\"correlationId\"] = ctx.TraceIdentifier }\n        };\n        _logger.LogError(ex, \"Request failed: {StatusCode} {Title} (CorrelationId: {CorrelationId})\",\n            statusCode, title, ctx.TraceIdentifier);\n        ctx.Response.StatusCode = statusCode;\n        await ctx.Response.WriteAsJsonAsync(problem, ct);\n        return true;\n    }\n}\n```\n\n---\n\n## PART 9: PHASE 5 — TEST COVERAGE AND SECURITY TESTS\n\nWhen inheriting a codebase with low coverage, do not try to achieve 80% in one sprint. Add\ntests in this priority order:\n\n1. Security tests first — auth bypass, BOLA, injection (even for code not being changed)\n2. Tests for code you are about to change — write characterization tests before refactoring\n3. Critical business logic — paths that, if broken, cause financial loss or data corruption\n4. Error paths — 4xx and 5xx responses\n5. Happy path coverage — fill in remaining gaps\n\n### 9.1 Characterization Tests (Before Refactoring Untested Code)\n\n```csharp\n[Fact]\n[Trait(\"Type\", \"Characterization\")]\npublic async Task CreateOrder_ExistingBehavior_ReturnsCreatedWithCurrentLogic()\n{\n    \u002F\u002F Documents what the code CURRENTLY does before you change it\n    \u002F\u002F TODO: [TICKET-123] Replace with proper TDD test after service extraction\n}\n```\n\n### 9.2 Security Test Template for Existing Endpoints\n\n```csharp\n[Fact]\npublic async Task GetById_NoAuthToken_Returns401() { ... }\n[Fact]\npublic async Task GetById_ExpiredToken_Returns401() { ... }\n[Fact]\npublic async Task GetById_WrongRole_Returns403() { ... }\n[Fact]\npublic async Task GetById_ValidTokenButNotOwner_Returns403() { \u002F* BOLA test *\u002F }\n[Theory]\n[InlineData(\"'; DROP TABLE orders; --\")]\n[InlineData(\"\u003Cscript>alert('xss')\u003C\u002Fscript>\")]\n[InlineData(\"..\u002F..\u002F..\u002Fetc\u002Fpasswd\")]\npublic async Task CreateOrder_AdversarialInput_Returns400(string maliciousInput) { ... }\n```\n\n### 9.3 Coverage Gates — Introduce Incrementally\n\nDo not set coverage gates to 80% on a codebase with 20% coverage. Set it at current + 5%,\nratchet up each sprint. The coverage gate should **never decrease**.\n\n```xml\n\u003C!-- .runsettings — adjust minimum to current actual coverage -->\n\u003CCoverageThreshold>\n  \u003CLineCoverage minimum=\"35\" \u002F>  \u003C!-- start at actual; increase 5% each sprint -->\n\u003C\u002FCoverageThreshold>\n```\n\n---\n\n## PART 10: PHASE 6 — LOGGING AND OBSERVABILITY\n\n### 10.1 Migrating from Console.WriteLine to Structured Logging\n\n```csharp\n\u002F\u002F BEFORE: unstructured, not searchable\nConsole.WriteLine($\"Processing order {orderId} for user {userId}\");\n\u002F\u002F AFTER: structured, searchable in Application Insights\n_logger.LogInformation(\"Processing order {OrderId} for {UserId}\", orderId, userId);\n```\n\n### 10.2 Adding Correlation ID Propagation\n\n```csharp\npublic class CorrelationIdMiddleware\n{\n    private const string HeaderName = \"x-correlation-id\";\n    public async Task InvokeAsync(HttpContext context)\n    {\n        var correlationId = context.Request.Headers[HeaderName].FirstOrDefault()\n            ?? Guid.NewGuid().ToString(\"N\");\n        context.Response.Headers[HeaderName] = correlationId;\n        using var scope = _logger.BeginScope(\n            new Dictionary\u003Cstring, object> { [\"CorrelationId\"] = correlationId });\n        context.TraceIdentifier = correlationId;\n        await _next(context);\n    }\n}\napp.UseMiddleware\u003CCorrelationIdMiddleware>(); \u002F\u002F before UseRouting\n```\n\n### 10.3 Removing PII from Existing Logs\n\n```bash\ngrep -rn \"_logger\\.\\|Log\\.\\|Console\\.\" src\u002F --include=\"*.cs\" | \\\n  grep -i \"email\\|password\\|token\\|ssn\\|credit\\|phone\\|address\"\n```\n\nReplace actual values with anonymized identifiers:\n```csharp\n\u002F\u002F BEFORE — logs actual email address\n_logger.LogInformation(\"User {Email} logged in\", user.Email);\n\u002F\u002F AFTER — logs only anonymized ID\n_logger.LogInformation(\"User {UserId} logged in\", user.Id);\n```\n\n---\n\n## PART 11: PHASE 7 — DEVSECOPS PIPELINE INSTALLATION\n\nInstall the pipeline on every repository, even before other phases are complete. A pipeline\nthat catches some issues on day one is better than a perfect pipeline on day ninety.\n\n### 11.1 Minimal Viable Security Pipeline (Install First)\n\n```yaml\n# .github\u002Fworkflows\u002Fsecurity.yml\nname: Security Gates\non:\n  push: { branches: [main, develop] }\n  pull_request: { branches: [main] }\npermissions:\n  security-events: write\n  contents: read\n\njobs:\n  secrets-scan:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n        with: { fetch-depth: 0 }  # full history required for Gitleaks\n      - uses: gitleaks\u002Fgitleaks-action@v2\n        env: { GITHUB_TOKEN: '${{ secrets.GITHUB_TOKEN }}' }\n\n  sast-semgrep:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: returntocorp\u002Fsemgrep-action@v1\n        with:\n          config: 'p\u002Fsecrets p\u002Fowasp-top-ten p\u002Fcsharp p\u002Ftypescript'\n          generateSarif: true\n      - uses: github\u002Fcodeql-action\u002Fupload-sarif@v3\n        with: { sarif_file: semgrep.sarif }\n        if: always()\n```\n\n### 11.2 Adding Gates Progressively (One Job Per Sprint)\n\n```yaml\n# Sprint 2 — add when dependency audit is clean enough to gate on\n  sca:\n    uses: snyk\u002Factions\u002Fdotnet@master\n    with: { args: '--severity-threshold=high' }\n\n# Sprint 2 — add when Docker images are in use\n  container-scan:\n    if: hashFiles('Dockerfile') != ''\n    # trivy CRITICAL,HIGH exit-code 1\n\n# Sprint 3 — add when IaC exists\n  iac-scan:\n    if: hashFiles('infra\u002F**\u002F*.bicep') != ''\n    # checkov bicep soft_fail false\n\n# Sprint 3 — add when coverage gate is established\n  build-and-test:\n    # dotnet test with coverage threshold\n```\n\n### 11.3 Pre-Commit Hook\n\n```bash\npip install pre-commit\n# .pre-commit-config.yaml\nrepos:\n  - repo: https:\u002F\u002Fgithub.com\u002Fgitleaks\u002Fgitleaks\n    rev: v8.18.0\n    hooks: [{ id: gitleaks }]\n  - repo: https:\u002F\u002Fgithub.com\u002Freturntocorp\u002Fsemgrep\n    rev: v1.45.0\n    hooks:\n      - id: semgrep\n        args: ['--config', 'p\u002Fsecrets', '--config', 'p\u002Fowasp-top-ten', '--error']\n  - repo: https:\u002F\u002Fgithub.com\u002Fpre-commit\u002Fpre-commit-hooks\n    rev: v4.5.0\n    hooks: [{ id: detect-private-key }, { id: detect-aws-credentials }]\n\n# Each developer runs once after cloning:\npre-commit install\n```\n\n---\n\n## PART 12: PHASE 8 — INFRASTRUCTURE MODERNIZATION\n\nThis phase requires coordination with the Azure admin. You produce the Bicep; the human reviews\nand applies it. Do not provision infrastructure autonomously.\n\n### 12.1 Key Vault Hardening\n\n```bash\naz keyvault show --name \u003Cvault-name> --query '{\n  rbacEnabled: properties.enableRbacAuthorization,\n  softDelete: properties.enableSoftDelete,\n  purgeProtection: properties.enablePurgeProtection,\n  publicAccess: properties.publicNetworkAccess\n}'\n```\n\n```bicep\nresource vault 'Microsoft.KeyVault\u002Fvaults@2023-07-01' = {\n  properties: {\n    enableRbacAuthorization: true\n    enableSoftDelete: true\n    softDeleteRetentionInDays: 90\n    enablePurgeProtection: true      \u002F\u002F IRREVERSIBLE — confirm with human before applying\n    publicNetworkAccess: 'Disabled'\n    networkAcls: { defaultAction: 'Deny', bypass: 'AzureServices' }\n  }\n}\n```\n\n### 12.2 Private Endpoint — Sequence Matters\n\n**The sequence matters.** Disabling public network access before the Private Endpoint is\nconfigured will break all connectivity. Always:\n\n1. Add the Private Endpoint\n2. Verify connectivity via the private endpoint\n3. Then disable public network access\n\n### 12.3 Managed Identity Role Assignment — Add Before Switching Code\n\nAlways assign the Managed Identity role **before** switching the connection code:\n\n1. Assign the role in Azure\n2. Verify the assignment propagates (can take 2-5 minutes)\n3. Deploy the code change\n4. Remove the old connection string from Key Vault (not before)\n\n```bicep\n\u002F\u002F Cosmos DB Built-in Data Contributor assignment\nresource cosmosRoleAssignment 'Microsoft.DocumentDB\u002FdatabaseAccounts\u002FsqlRoleAssignments@2024-05-15' = {\n  parent: cosmosAccount\n  name: guid(cosmosAccount.id, apiManagedIdentityPrincipalId, 'data-contributor')\n  properties: {\n    roleDefinitionId: '${cosmosAccount.id}\u002FsqlRoleDefinitions\u002F00000000-0000-0000-0000-000000000002'\n    principalId: apiManagedIdentityPrincipalId\n    scope: cosmosAccount.id\n  }\n}\n```\n\n---\n\n## PART 13: MIGRATION EXECUTION PROTOCOL (9 STEPS)\n\nFor every migration task, follow this sequence. The codebase must be passing after every step.\n\n```\nSTEP 1 — BASELINE\n  Run existing tests. Record the pass\u002Ffail count.\n  If tests were already failing: report to human before proceeding.\n  Run the Phase 0 assessment grep commands relevant to this component.\n\nSTEP 2 — SCOPE CONFIRMATION\n  State exactly what you are changing in this PR.\n  State what you are NOT changing.\n  If you discover P0 findings outside scope: log them; do not fix unilaterally.\n\nSTEP 3 — CHARACTERIZATION (if refactoring untested code)\n  Write characterization tests that capture current behavior before changing anything.\n  Run them. They must pass before you proceed.\n\nSTEP 4 — MAKE THE CHANGE\n  Apply the migration change (one logical change per PR).\n  Do not mix phases in a single PR.\n\nSTEP 5 — SECURITY TEST\n  Write the adversarial test that proves the attack is now blocked.\n  Write the positive test that proves the legitimate path still works.\n  Run both. Both must pass.\n\nSTEP 6 — QUALITY GATE\n  Run: format check → lint → type check → full test suite.\n  Coverage must not decrease from baseline recorded in Step 1.\n\nSTEP 7 — SEMGREP SCAN\n  semgrep scan --config p\u002Fsecrets --config p\u002Fowasp-top-ten \u003Cchanged_files>\n  Zero medium+ findings. Fix any before committing.\n\nSTEP 8 — COMMIT\n  Conventional Commits format. Use 'security' type for security fixes.\n  One logical change per commit.\n  No secrets: verify with: git diff --cached | grep -i \"password\\|secret\\|key\"\n\nSTEP 9 — DOCUMENT THE FINDING\n  Update the migration log: what was found, what was fixed, what remains outstanding.\n```\n\n### Commit Message Conventions for Migration Work\n\n```\n# Security fixes\nsecurity(api): add BOLA ownership check to document retrieval\nsecurity(auth): migrate JWT validation to Microsoft.Identity.Web\nsecurity(config): replace Cosmos DB connection string with Managed Identity\nsecurity(react): migrate MSAL token storage from localStorage to sessionStorage\n\n# Architecture migration\nrefactor(service): extract order business logic from OrdersController\nrefactor(repo): introduce IOrderRepository and Fake implementation\nrefactor(domain): define typed exception hierarchy\n\n# Pipeline installation\nci: add Gitleaks secrets scan to PR gate\nci: add Semgrep OWASP SAST to PR gate\n```\n\n---\n\n## PART 14: THE STRANGLER FIG PATTERN\n\nDo not rewrite existing code wholesale. Use the strangler fig:\n\n- New code is written to the full Security-First Scrum standard.\n- Old code is migrated one component at a time, each PR fully tested.\n- The old implementation is removed only after the new one is verified in production.\n- Feature flags decouple migration from release — the new auth flow can be deployed but not\n  activated until validated.\n\nEvery migration PR has a clear before and after state. The old code is removed in the same PR\nthat confirms the new code works. Never leave both old and new implementation in the codebase\nsimultaneously with unclear which one is authoritative.\n\n---\n\n## PART 15: THINGS TO NEVER DO DURING MODERNIZATION\n\n### Never — They Make the Codebase Less Safe\n\n- Disable or soft-fail a security gate to unblock a migration PR. Fix the finding.\n- Remove `[Authorize]` from an endpoint to make a test pass. Fix the test infrastructure.\n- Commit a \"temporary\" hardcoded secret while working out Key Vault integration. There is no\n  temporary credential in git history.\n- Rewrite authentication from scratch without testing every endpoint in the system.\n- Mix architectural refactoring (Phase 4) with security fixes (Phase 1-3) in the same PR.\n- Use `AllowAnyOrigin()` temporarily with a plan to tighten later. \"Later\" does not happen.\n- Switch to `ManagedIdentityCredential` before the role assignment is confirmed in Azure.\n- Disable public network access on a PaaS resource before a Private Endpoint is configured.\n- Delete old authentication code before the new flow is verified working in staging.\n- Set coverage gates at 80% on a 20% codebase. Set at current + 5%.\n- Fix a vulnerability in a different component than the one tasked. Log it. Surface it.\n\n### Never — They Violate People First\n\n- Make infrastructure changes (Bicep, role assignments, network rules) without human confirmation.\n- Rotate credentials autonomously. Credential rotation has organizational consequences.\n- Scope-creep silently. Surface immediately when the task is larger than expected.\n- Leave the human with a broken build. Stop, restore last working state, report what you found.\n\n---\n\n## PART 16: MIGRATION ANTI-PATTERNS\n\n**The \"big bang\" anti-pattern:** Attempting to migrate all authentication, fix all SQL injection,\nrestructure all layers, add the DevSecOps pipeline, and write all missing tests in a single\nsprint. Produces a PR nobody can safely review.\n*Correct approach: One phase per sprint. One component per PR.*\n\n**The \"fix it forward\" anti-pattern:** Encountering a broken test and \"fixing\" it to make the\nnew code pass, without understanding why it was failing.\n*Correct approach: Understand the failure. If your change is correct and the test was wrong,\nupdate the test and document why.*\n\n**The \"security theater\" anti-pattern:** Adding `[Authorize]` attributes while leaving the\nmiddleware pipeline in the wrong order. The decorators exist; the authorization does nothing.\n*Correct approach: Verify the middleware pipeline order before declaring auth migration complete.*\n\n**The \"abandoned strangler\" anti-pattern:** Starting a component migration but not completing it\n— leaving both old and new implementation with unclear authority.\n*Correct approach: Remove old code in the same PR that verifies the new code works.*\n\n**The \"coverage inflation\" anti-pattern:** Writing tests with no assertions to achieve coverage\nnumbers.\n*Correct approach: Coverage is a signal. A test without meaningful assertions is worse than no\ntest — it creates false confidence.*\n","# Security-First Scrum: Codebase Modernization\n\nYou are modernizing an existing codebase toward the Security-First Scrum standard. The rules are\ndifferent from greenfield work. Read this document in full before touching any file.\n\n---\n\n## PART 1: THREE LAWS (UNCHANGED — ALWAYS IN THIS ORDER)\n\n**Law 1 — Security First.** Never introduce a new vulnerability while fixing an old one. Never\nleave a surface more exposed than you found it.\n\n**Law 2 — People First.** The humans own the migration strategy and the risk decisions. You\nexecute the technical steps they have scoped. Do not attempt autonomous infrastructure changes,\nsecret rotation, or scope expansion without confirmation.\n\n**Law 3 — Incremental \u002F Agile.** Every PR must leave the codebase in a better and working state.\nNo big-bang rewrites. No broken builds between steps.\n\n---\n\n## PART 2: MODERNIZATION PRIME DIRECTIVE\n\nBefore touching any file:\n\n1. Run the Phase 0 assessment protocol. Understand what you are walking into.\n2. Confirm the scope of this specific task with the human. Scope creep during migration breaks\n   things.\n3. Identify whether the change is security-critical (Phase 1-3), architectural (Phase 4-5), or\n   operational (Phase 6-8). Do not mix phases in a single PR.\n4. Verify existing tests pass before you start. You own the baseline. If they were already broken,\n   surface that immediately — do not inherit a broken build silently.\n5. Make your change. Re-run tests. The codebase must be passing when you are done.\n\n**The iron rule of modernization:** every PR leaves the codebase more secure and working than\nbefore. A PR that improves architecture but introduces a regression is not acceptable. A PR that\nremoves a vulnerability but breaks auth is not acceptable.\n\n**Stop and surface to the human when:**\n- You discover a vulnerability outside the scope of the current task (log it; do not fix it\n  unilaterally)\n- The existing code has no tests and adding the security control requires refactoring untested code\n- A dependency is so outdated that upgrading it would require cascading changes beyond sprint scope\n- You find hardcoded credentials — rotate them before doing anything else (Phase 1)\n\n---\n\n## PART 3: TRIAGE PRIORITY SYSTEM\n\nWhen a codebase has multiple issues, address them in this order. Do not reorder based on what\nseems more interesting or architectural.\n\n| Priority | Category | Rationale |\n|---|---|---|\n| **P0 — Immediate** | Hardcoded secrets \u002F credentials in source code | Active exposure. Every minute counts. |\n| **P0 — Immediate** | Broken or missing authentication on production endpoints | Active exploitation surface. |\n| **P1 — This Sprint** | SQL injection \u002F non-parameterized queries | High CVSS; straightforward fix. |\n| **P1 — This Sprint** | `localStorage` token storage in React | XSS + token theft = full account compromise. |\n| **P1 — This Sprint** | Missing or permissive CORS (`AllowAnyOrigin`) | Cross-origin attack surface on production. |\n| **P2 — Next Sprint** | Implicit Grant auth flow still in use | Deprecated; migration is planned work. |\n| **P2 — Next Sprint** | Connection strings with keys (replace with Managed Identity) | High value; requires infra coordination. |\n| **P2 — Next Sprint** | Missing rate limiting on public endpoints | Abuse surface; not currently exploited. |\n| **P3 — Backlog** | Architecture violations (business logic in controllers, etc.) | Quality debt; not an active security risk. |\n| **P3 — Backlog** | Missing test coverage on non-security paths | Quality debt; address incrementally. |\n| **P3 — Backlog** | Missing XML doc comments \u002F docstrings | Documentation debt. |\n\n---\n\n## PART 4: PHASE 0 — CODEBASE ASSESSMENT (RUN BEFORE TOUCHING ANYTHING)\n\nRun this assessment on every codebase you are asked to modernize. Produce a written finding\nsummary before writing a single line of migration code.\n\n### 4.1 Secrets Scan — Run First, No Exceptions\n\n```bash\n# Full history scan — not just HEAD\ngitleaks detect --source . --log-opts \"--all\" --report-format json --report-path gitleaks-report.json\n# Current working tree\ngitleaks detect --source . --report-format json --report-path gitleaks-current.json\n# npm \u002F pip dependency secrets\ntrufflehog filesystem . --json > trufflehog-report.json\n```\n\nIf secrets are found: Stop. Do not proceed with any other migration work. Report to the human\nimmediately. Credentials must be rotated before the codebase is touched further.\n\n### 4.2 Dependency Vulnerability Scan\n\n```bash\ndotnet list package --vulnerable --include-transitive > dotnet-vulns.txt\nnpm audit --json > npm-audit.json\npip install safety && safety check --json > safety-report.json\npip install bandit && bandit -r src\u002F -f json -o bandit-report.json\n```\n\nCategorize: CRITICAL (this sprint), HIGH (next sprint), MEDIUM\u002FLOW (backlog).\n\n### 4.3 Authentication Surface Map\n\nFor every .NET controller and every React\u002FBlazor route, record:\n```\nEndpoint \u002F Route | Auth required? | Current mechanism | Auth flow | Token storage | Notes\n```\n\nFlag any endpoint that:\n- Has no `[Authorize]` decorator and serves non-public data\n- Uses Implicit Grant flow\n- Stores tokens in `localStorage`\n- Uses a shared app registration across environments\n- Has hardcoded `ClientSecret` in configuration\n\n### 4.4 Authorization \u002F BOLA Check\n\nFor every endpoint that returns or modifies user-owned data:\n```\nEndpoint | Returns user-owned data? | Ownership check present? | Where? (controller\u002Fservice\u002Fnone)\n```\n\n### 4.5 Database Query Safety Audit\n\n```bash\n# .NET — find raw SQL with string interpolation\ngrep -rn \"FromSqlRaw\\|ExecuteSqlRaw\\|FromSqlInterpolated\" src\u002F --include=\"*.cs\"\ngrep -rn '\"\\s*SELECT\\|\"\\s*INSERT\\|\"\\s*UPDATE\\|\"\\s*DELETE' src\u002F --include=\"*.cs\"\n# Python\ngrep -rn 'execute.*f\"SELECT\\|execute.*%.*SELECT' src\u002F --include=\"*.py\"\n```\n\n### 4.6 Secrets in Configuration Files\n\n```bash\ngrep -rn \"Password=\\|pwd=\\|AccountKey=\\|SharedAccessKey=\" . \\\n  --include=\"*.json\" --include=\"*.yaml\" --include=\"*.yml\" --include=\"*.env\" \\\n  --exclude-dir=node_modules --exclude-dir=.git\n```\n\n### 4.7 Architecture Layer Violations (.NET)\n\n```bash\n# Business logic \u002F DB in controllers\ngrep -rn \"DbContext\\|CosmosClient\\|NpgsqlConnection\" src\u002F --include=\"*.cs\" | grep -i \"controller\"\n# Repository calls from controllers\ngrep -rn \"IRepository\\|Repository\" src\u002F --include=\"*.cs\" | grep -i \"controller\"\n```\n\n### 4.8 Frontend Security Audit\n\n```bash\ngrep -rn \"localStorage\" src\u002F --include=\"*.ts\" --include=\"*.tsx\" | grep -i \"token\\|auth\\|jwt\"\ngrep -rn \"dangerouslySetInnerHTML\" src\u002F --include=\"*.tsx\" --include=\"*.jsx\"\ngrep -rn \"AllowAnyOrigin\\|origin.*\\*\" . --include=\"*.ts\" --include=\"*.json\"\n```\n\n### 4.9 Assessment Report Template\n\n```markdown\n## Codebase Assessment — [Date] — [Repo Name]\n\n### P0 Findings (Immediate)\n- [ ] [Finding] — [File:Line] — [Impact]\n\n### P1 Findings (This Sprint)\n### P2 Findings (Next Sprint)\n### P3 Findings (Backlog)\n\n### Existing Test Coverage\n- Overall: X%\n- Security test coverage: X% (estimate)\n- Integration tests present: yes\u002Fno\n\n### Architecture Health\n- Layer violations found: X\n- Missing interfaces: X\n- Controllers with direct DB access: X\n```\n\nHand this to the human before writing any migration code. They scope the sprints; you execute.\n\n---\n\n## PART 5: PHASE 1 — SECRETS AND CREDENTIALS (HIGHEST PRIORITY)\n\n### 5.1 When You Find a Hardcoded Secret\n\n1. Do not commit the file with the secret still present. Never.\n2. Report to the human immediately — they must rotate it before you make the replacement commit.\n3. After rotation is confirmed, replace with Key Vault reference pattern (§5.2).\n4. After the replacement PR is merged, clean git history using `git filter-repo` (NOT\n   `git filter-branch` — deprecated).\n\n### 5.2 Replacing Connection Strings with Key Vault References\n\n**Before (dangerous — never leave in place):**\n```json\n{\n  \"ConnectionStrings\": {\n    \"CosmosDb\": \"AccountEndpoint=https:\u002F\u002Faccount.documents.azure.com:443\u002F;AccountKey=ACTUAL_KEY;\"\n  }\n}\n```\n\n**Step 1 — Add Key Vault to configuration bootstrap:**\n```csharp\n\u002F\u002F Program.cs\nvar kvName = builder.Configuration[\"KeyVaultName\"]; \u002F\u002F non-secret; safe in appsettings\nif (!string.IsNullOrEmpty(kvName))\n{\n    var kvUri = new Uri($\"https:\u002F\u002F{kvName}.vault.azure.net\u002F\");\n    builder.Configuration.AddAzureKeyVault(\n        kvUri, new DefaultAzureCredential(),\n        new AzureKeyVaultConfigurationOptions { ReloadInterval = TimeSpan.FromMinutes(5) });\n}\n```\n\n**Step 2 — Replace Cosmos DB connection string with Managed Identity:**\n```csharp\n\u002F\u002F BEFORE (delete this)\nvar cosmosClient = new CosmosClient(configuration[\"ConnectionStrings:CosmosDb\"]);\n\u002F\u002F AFTER\nvar credential = builder.Environment.IsDevelopment()\n    ? new DefaultAzureCredential()\n    : new ManagedIdentityCredential();\nservices.AddSingleton(_ => new CosmosClient(\n    configuration[\"CosmosDb:Endpoint\"], credential,\n    new CosmosClientOptions { ConnectionMode = ConnectionMode.Direct }));\n```\n\n**Step 3 — Replace PostgreSQL connection string with Managed Identity token:**\n```csharp\n\u002F\u002F BEFORE (delete this)\nservices.AddNpgsqlDataSource(configuration[\"ConnectionStrings:PostgreSQL\"]);\n\u002F\u002F AFTER\nvar connStringWithoutPassword = configuration[\"PostgreSQL:ConnectionStringNoPassword\"];\nservices.AddSingleton(_ =>\n{\n    var credential = builder.Environment.IsDevelopment()\n        ? new DefaultAzureCredential()\n        : new ManagedIdentityCredential();\n    var dataSourceBuilder = new NpgsqlDataSourceBuilder(connStringWithoutPassword);\n    dataSourceBuilder.UsePeriodicPasswordProvider(async (_, ct) =>\n    {\n        var token = await credential.GetTokenAsync(new TokenRequestContext(\n            new[] { \"https:\u002F\u002Fossrdbms-aad.database.windows.net\u002F.default\" }), ct);\n        return token.Token;\n    }, TimeSpan.FromHours(4), TimeSpan.FromSeconds(10));\n    return dataSourceBuilder.Build();\n});\n```\n\n### 5.3 .gitignore — Verify Completeness\n\n```\n.env\n.env.*\n!.env.example\nappsettings.Development.json\nappsettings.Production.json\nappsettings.Staging.json\nlocal.settings.json\nlaunchSettings.json\n*.pem\n*.key\n*.pfx\nsecrets\u002F\n.azure\u002F\n.aws\u002F\n.ssh\u002F\n```\n\n---\n\n## PART 6: PHASE 2 — AUTHENTICATION AND AUTHORIZATION MIGRATION\n\n### 6.1 Find Unprotected Controllers\n\n```bash\ngrep -rn \"public class.*Controller\" src\u002F --include=\"*.cs\" -l | while read f; do\n  if ! grep -q \"\\[Authorize\" \"$f\"; then\n    echo \"No [Authorize] found: $f\"\n  fi\ndone\ngrep -rn \"\\[AllowAnonymous\\]\" src\u002F --include=\"*.cs\"  # each needs a documented reason\n```\n\n### 6.2 Migrating to Microsoft.Identity.Web\n\n**Before (legacy JWT):**\n```csharp\nservices.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)\n    .AddJwtBearer(options => {\n        options.TokenValidationParameters = new TokenValidationParameters {\n            ValidIssuer = \"https:\u002F\u002Fsts.windows.net\u002FYOUR-TENANT\u002F\",\n            ValidAudience = \"api:\u002F\u002FYOUR-APP-ID\",\n            \u002F\u002F Common legacy mistake: ClockSkew left at default 5 minutes\n        };\n    });\n```\n\n**After (Microsoft.Identity.Web):**\n```csharp\nbuilder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)\n    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection(\"AzureAd\"));\nbuilder.Services.AddAuthorizationBuilder()\n    .AddPolicy(\"AdminOnly\",     p => p.RequireRole(\"Admin\"))\n    .AddPolicy(\"ReaderOrAdmin\", p => p.RequireRole(\"Reader\", \"Admin\"))\n    .AddPolicy(\"WriterOrAdmin\", p => p.RequireRole(\"Writer\", \"Admin\"));\n```\n\nRequired packages:\n```bash\ndotnet add package Microsoft.Identity.Web\ndotnet add package Azure.Identity\n# Remove any hand-rolled JWT validation packages\n```\n\n### 6.3 Adding [Authorize] — Controller by Controller\n\nDo this controller-by-controller, not as a mass change. Each controller = its own PR:\n\n```csharp\n[ApiController]\n[Route(\"api\u002Fv1\u002F[controller]\")]\n[Authorize]  \u002F\u002F minimum: authenticated caller required\npublic class DocumentsController : ControllerBase { }\n\n[HttpGet(\"{id}\")]\n[Authorize(Policy = \"ReaderOrAdmin\")]\npublic async Task\u003CActionResult\u003CDocumentResponse>> GetByIdAsync(string id, CancellationToken ct) { }\n\n[HttpGet(\"health\")]\n[AllowAnonymous] \u002F\u002F REASON: Public health check — no data returned\npublic IActionResult Health() => Ok(\"healthy\");\n```\n\n### 6.4 Adding BOLA Protection to Existing Endpoints\n\nBOLA is the most common API vulnerability and is usually completely absent. Add it to the\nservice layer — not the controller:\n\n```csharp\n\u002F\u002F BEFORE: No ownership check\npublic async Task\u003CDocumentModel> GetDocumentAsync(string documentId, CancellationToken ct)\n{\n    return await _repository.FindByIdAsync(documentId, ct);\n}\n\n\u002F\u002F AFTER: Ownership enforced before data is returned\npublic async Task\u003CDocumentModel> GetDocumentAsync(\n    string documentId, string requestingUserId, CancellationToken ct)\n{\n    var document = await _repository.FindByIdAsync(documentId, ct);\n    if (document.OwnerId != requestingUserId)\n        throw new ResourceOwnershipException(\n            $\"User {requestingUserId} does not own document {documentId}\");\n    return document;\n}\n```\n\nController side — extract userId from JWT:\n```csharp\nvar userId = User.GetObjectId()  \u002F\u002F Microsoft.Identity.Web extension method\n    ?? throw new UnauthorizedAccessException(\"UserId claim missing from token\");\nvar document = await _documentService.GetDocumentAsync(id, userId, ct);\n```\n\n### 6.5 Migrating React from localStorage to sessionStorage\n\n```typescript\n\u002F\u002F BEFORE — delete this\ncache: { cacheLocation: \"localStorage\" }\n\u002F\u002F AFTER\ncache: { cacheLocation: \"sessionStorage\", storeAuthStateInCookie: false }\n```\n\n### 6.6 Migrating from Implicit Grant to Authorization Code + PKCE\n\n**What you do (code):** Verify MSAL.js v3 is installed.\n```bash\nnpm install @azure\u002Fmsal-browser@latest @azure\u002Fmsal-react@latest\n```\n\n**What the human does (Azure portal):**\n- App registration → Authentication → Remove checkboxes for \"Access tokens\" and \"ID tokens\"\n  under Implicit grant.\n- Verify redirect URIs are correct.\n\n### 6.7 Middleware Pipeline Order — Fix If Wrong\n\nThis is the single most common .NET security misconfiguration:\n\n```csharp\n\u002F\u002F CORRECT ORDER\napp.UseHsts();\napp.UseHttpsRedirection();\napp.UseSerilogRequestLogging();\napp.UseRouting();\napp.UseRateLimiter();\napp.UseCors(\"SpaPolicy\");\napp.UseAuthentication();  \u002F\u002F WHO are you? — MUST come before UseAuthorization\napp.UseAuthorization();   \u002F\u002F WHAT can you do?\napp.MapControllers();\n```\n\nIf `UseAuthorization` appears before `UseAuthentication` in existing code: this is a P0 finding.\nThe middleware silently treats all requests as unauthenticated. Fix immediately.\n\n---\n\n## PART 7: PHASE 3 — INPUT VALIDATION AND QUERY SAFETY\n\n### 7.1 Replacing String-Interpolated SQL Queries\n\n**.NET \u002F Npgsql:**\n```csharp\n\u002F\u002F BEFORE — SQL injection vulnerable\nvar users = await _conn.QueryAsync\u003CUser>(\n    $\"SELECT * FROM users WHERE email = '{email}' AND tenant_id = '{tenantId}'\");\n\u002F\u002F AFTER — parameterized\nvar users = await _conn.QueryAsync\u003CUser>(\n    \"SELECT * FROM users WHERE email = @email AND tenant_id = @tenantId\",\n    new { email, tenantId });\n```\n\n**.NET \u002F Cosmos DB:**\n```csharp\n\u002F\u002F BEFORE — string interpolation in Cosmos query\nvar query = new QueryDefinition(\n    $\"SELECT * FROM c WHERE c.userId = '{userId}' AND c.type = '{docType}'\");\n\u002F\u002F AFTER — parameterized\nvar query = new QueryDefinition(\n    \"SELECT * FROM c WHERE c.userId = @userId AND c.type = @docType\")\n    .WithParameter(\"@userId\", userId)\n    .WithParameter(\"@docType\", docType);\n```\n\n**EF Core:**\n```csharp\n\u002F\u002F BEFORE — vulnerable\nvar results = _context.Users.FromSqlRaw($\"SELECT * FROM Users WHERE Id = {userId}\");\n\u002F\u002F AFTER — prefer LINQ (EF generates safe SQL)\nvar results = _context.Users.Where(u => u.Id == userId);\n```\n\n### 7.2 Adding FluentValidation\n\n```bash\ndotnet add package FluentValidation\ndotnet add package FluentValidation.DependencyInjectionExtensions\n# Do NOT install FluentValidation.AspNetCore — it is deprecated\n```\n\n```csharp\npublic class CreateUserRequestValidator : AbstractValidator\u003CCreateUserRequest>\n{\n    public CreateUserRequestValidator()\n    {\n        RuleFor(x => x.Name).NotEmpty().MaximumLength(100)\n            .Matches(@\"^[\\w\\s\\-'\\.]+$\").WithMessage(\"Name contains invalid characters.\");\n        RuleFor(x => x.Email).NotEmpty().EmailAddress().MaximumLength(254);\n    }\n}\nbuilder.Services.AddValidatorsFromAssemblyContaining\u003CCreateUserRequestValidator>();\n```\n\n### 7.3 Fixing dangerouslySetInnerHTML\n\n```bash\ngrep -rn \"dangerouslySetInnerHTML\" src\u002F --include=\"*.tsx\" --include=\"*.jsx\"\n```\n\nFor each hit with user-controlled content:\n```tsx\n\u002F\u002F BEFORE — XSS vulnerability\n\u003Cdiv dangerouslySetInnerHTML={{ __html: userProfile.bio }} \u002F>\n\u002F\u002F AFTER — DOMPurify sanitization\nimport DOMPurify from 'dompurify';\n\u003Cdiv dangerouslySetInnerHTML={{\n  __html: DOMPurify.sanitize(userProfile.bio, {\n    ALLOWED_TAGS: ['p', 'br', 'strong', 'em', 'a'],\n    FORBID_TAGS: ['script', 'style', 'iframe'],\n    FORBID_ATTR: ['onerror', 'onload', 'onclick'],\n  })\n}} \u002F>\n```\n\n### 7.4 Tightening CORS\n\n```csharp\n\u002F\u002F BEFORE — never acceptable in production\napp.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());\n\u002F\u002F AFTER — exact allowed origins from configuration\nvar allowedOrigins = builder.Configuration\n    .GetSection(\"Cors:AllowedOrigins\").Get\u003Cstring[]>()\n    ?? throw new InvalidOperationException(\"Cors:AllowedOrigins must be configured\");\nbuilder.Services.AddCors(options =>\n{\n    options.AddPolicy(\"SpaPolicy\", policy => policy\n        .WithOrigins(allowedOrigins)\n        .AllowAnyHeader().AllowAnyMethod().AllowCredentials());\n});\n```\n\n### 7.5 Adding Rate Limiting\n\n```csharp\nbuilder.Services.AddRateLimiter(options =>\n{\n    options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;\n    options.GlobalLimiter = PartitionedRateLimiter.Create\u003CHttpContext, string>(\n        httpContext => RateLimitPartition.GetFixedWindowLimiter(\n            partitionKey: httpContext.User.Identity?.Name\n                ?? httpContext.Connection.RemoteIpAddress?.ToString() ?? \"anon\",\n            factory: _ => new FixedWindowRateLimiterOptions\n            {\n                PermitLimit = 60, Window = TimeSpan.FromMinutes(1), QueueLimit = 0,\n            }));\n});\n\u002F\u002F In middleware pipeline — MUST be after UseRouting, before UseAuthentication\napp.UseRateLimiter();\n```\n\n---\n\n## PART 8: PHASE 4 — ARCHITECTURE REFACTORING (P3 PRIORITY)\n\n**Do not start Phase 4 if P0–P2 work is outstanding. Architecture refactoring carries the most\nrisk of regressions. Every change must be covered by tests before and after.**\n\n### 8.1 Extracting Business Logic from Controllers\n\nUse the extract → interface → test → delete approach (never all at once):\n\n```csharp\n\u002F\u002F BEFORE: Controller doing direct DB work and business logic\n[HttpPost]\npublic async Task\u003CIActionResult> CreateOrder(CreateOrderRequest request)\n{\n    if (request.Quantity > 100) return BadRequest(\"Quantity exceeds limit\");  \u002F\u002F business logic\n    var order = new Order { ... };\n    await _dbContext.Orders.AddAsync(order);   \u002F\u002F direct DB — wrong layer\n    await _dbContext.SaveChangesAsync();\n    return CreatedAtAction(...);\n}\n\n\u002F\u002F AFTER STEP 1: Interface first\npublic interface IOrderService\n{\n    Task\u003COrderModel> CreateOrderAsync(\n        CreateOrderRequest request, string requestingUserId, CancellationToken ct);\n}\n\n\u002F\u002F AFTER STEP 2: Implement the service (write test first)\npublic class OrderService : IOrderService\n{\n    private readonly IOrderRepository _repository;\n    public async Task\u003COrderModel> CreateOrderAsync(\n        CreateOrderRequest request, string requestingUserId, CancellationToken ct)\n    {\n        if (request.Quantity > 100)\n            throw new ValidationException(\"Quantity exceeds the maximum of 100.\");\n        var order = new Order { OwnerId = requestingUserId, ... };\n        return await _repository.SaveAsync(order, ct);\n    }\n}\n\n\u002F\u002F AFTER STEP 3: Controller becomes thin\n[HttpPost]\n[Authorize(Policy = \"WriterOrAdmin\")]\npublic async Task\u003CActionResult\u003COrderResponse>> CreateAsync(\n    CreateOrderRequest request, CancellationToken ct)\n{\n    var userId = User.GetObjectId()\n        ?? throw new UnauthorizedAccessException(\"UserId missing from token\");\n    var order = await _orderService.CreateOrderAsync(request, userId, ct);\n    return CreatedAtAction(nameof(GetByIdAsync), new { id = order.Id },\n        _mapper.Map\u003COrderResponse>(order));\n}\n```\n\n### 8.2 Extracting Repositories from Services\n\n```csharp\n\u002F\u002F Interface in Infrastructure\u002FRepositories\u002FInterfaces\u002F\npublic interface IOrderRepository\n{\n    Task\u003COrderModel> FindByIdAsync(string id, CancellationToken ct);\n    Task\u003COrderModel> SaveAsync(OrderModel order, CancellationToken ct);\n    Task DeleteAsync(string id, CancellationToken ct);\n}\n\n\u002F\u002F Fake for unit tests (in Mocks\u002F)\npublic class FakeOrderRepository : IOrderRepository\n{\n    private readonly Dictionary\u003Cstring, OrderModel> _store = new();\n    public Task\u003COrderModel> FindByIdAsync(string id, CancellationToken ct)\n    {\n        if (!_store.TryGetValue(id, out var order))\n            throw new NotFoundException($\"Order {id} not found.\");\n        return Task.FromResult(order);\n    }\n    public Task\u003COrderModel> SaveAsync(OrderModel order, CancellationToken ct)\n    {\n        _store[order.Id] = order; return Task.FromResult(order);\n    }\n    public Task DeleteAsync(string id, CancellationToken ct)\n    {\n        if (!_store.Remove(id)) throw new NotFoundException($\"Order {id} not found.\");\n        return Task.CompletedTask;\n    }\n    public IReadOnlyList\u003COrderModel> GetAll() => _store.Values.ToList();\n    public int Count => _store.Count;\n    public void Clear() => _store.Clear();\n}\n```\n\n### 8.3 Typed Exception Hierarchy\n\n```csharp\n\u002F\u002F Domain layer\npublic abstract class AppException : Exception { ... }\npublic sealed class ValidationException : AppException { ... }\npublic sealed class NotFoundException : AppException { ... }\npublic sealed class AuthException : AppException { ... }          \u002F\u002F never retry\npublic sealed class ResourceOwnershipException : AppException { ... } \u002F\u002F never retry\npublic sealed class TransientException : AppException { ... }    \u002F\u002F retry with backoff\n\n\u002F\u002F Global exception handler — maps to RFC 7807 ProblemDetails\npublic class GlobalExceptionHandler : IExceptionHandler\n{\n    public async ValueTask\u003Cbool> TryHandleAsync(HttpContext ctx, Exception ex, CancellationToken ct)\n    {\n        var (statusCode, title) = ex switch\n        {\n            ValidationException         => (400, \"Validation failed\"),\n            NotFoundException           => (404, \"Resource not found\"),\n            AuthException               => (401, \"Authentication required\"),\n            ResourceOwnershipException  => (403, \"Access denied\"),\n            TransientException          => (503, \"Service temporarily unavailable\"),\n            _                           => (500, \"An unexpected error occurred\"),\n        };\n        \u002F\u002F Never leak internal details to clients\n        var problem = new ProblemDetails\n        {\n            Status = statusCode, Title = title,\n            Extensions = { [\"correlationId\"] = ctx.TraceIdentifier }\n        };\n        _logger.LogError(ex, \"Request failed: {StatusCode} {Title} (CorrelationId: {CorrelationId})\",\n            statusCode, title, ctx.TraceIdentifier);\n        ctx.Response.StatusCode = statusCode;\n        await ctx.Response.WriteAsJsonAsync(problem, ct);\n        return true;\n    }\n}\n```\n\n---\n\n## PART 9: PHASE 5 — TEST COVERAGE AND SECURITY TESTS\n\nWhen inheriting a codebase with low coverage, do not try to achieve 80% in one sprint. Add\ntests in this priority order:\n\n1. Security tests first — auth bypass, BOLA, injection (even for code not being changed)\n2. Tests for code you are about to change — write characterization tests before refactoring\n3. Critical business logic — paths that, if broken, cause financial loss or data corruption\n4. Error paths — 4xx and 5xx responses\n5. Happy path coverage — fill in remaining gaps\n\n### 9.1 Characterization Tests (Before Refactoring Untested Code)\n\n```csharp\n[Fact]\n[Trait(\"Type\", \"Characterization\")]\npublic async Task CreateOrder_ExistingBehavior_ReturnsCreatedWithCurrentLogic()\n{\n    \u002F\u002F Documents what the code CURRENTLY does before you change it\n    \u002F\u002F TODO: [TICKET-123] Replace with proper TDD test after service extraction\n}\n```\n\n### 9.2 Security Test Template for Existing Endpoints\n\n```csharp\n[Fact]\npublic async Task GetById_NoAuthToken_Returns401() { ... }\n[Fact]\npublic async Task GetById_ExpiredToken_Returns401() { ... }\n[Fact]\npublic async Task GetById_WrongRole_Returns403() { ... }\n[Fact]\npublic async Task GetById_ValidTokenButNotOwner_Returns403() { \u002F* BOLA test *\u002F }\n[Theory]\n[InlineData(\"'; DROP TABLE orders; --\")]\n[InlineData(\"\u003Cscript>alert('xss')\u003C\u002Fscript>\")]\n[InlineData(\"..\u002F..\u002F..\u002Fetc\u002Fpasswd\")]\npublic async Task CreateOrder_AdversarialInput_Returns400(string maliciousInput) { ... }\n```\n\n### 9.3 Coverage Gates — Introduce Incrementally\n\nDo not set coverage gates to 80% on a codebase with 20% coverage. Set it at current + 5%,\nratchet up each sprint. The coverage gate should **never decrease**.\n\n```xml\n\u003C!-- .runsettings — adjust minimum to current actual coverage -->\n\u003CCoverageThreshold>\n  \u003CLineCoverage minimum=\"35\" \u002F>  \u003C!-- start at actual; increase 5% each sprint -->\n\u003C\u002FCoverageThreshold>\n```\n\n---\n\n## PART 10: PHASE 6 — LOGGING AND OBSERVABILITY\n\n### 10.1 Migrating from Console.WriteLine to Structured Logging\n\n```csharp\n\u002F\u002F BEFORE: unstructured, not searchable\nConsole.WriteLine($\"Processing order {orderId} for user {userId}\");\n\u002F\u002F AFTER: structured, searchable in Application Insights\n_logger.LogInformation(\"Processing order {OrderId} for {UserId}\", orderId, userId);\n```\n\n### 10.2 Adding Correlation ID Propagation\n\n```csharp\npublic class CorrelationIdMiddleware\n{\n    private const string HeaderName = \"x-correlation-id\";\n    public async Task InvokeAsync(HttpContext context)\n    {\n        var correlationId = context.Request.Headers[HeaderName].FirstOrDefault()\n            ?? Guid.NewGuid().ToString(\"N\");\n        context.Response.Headers[HeaderName] = correlationId;\n        using var scope = _logger.BeginScope(\n            new Dictionary\u003Cstring, object> { [\"CorrelationId\"] = correlationId });\n        context.TraceIdentifier = correlationId;\n        await _next(context);\n    }\n}\napp.UseMiddleware\u003CCorrelationIdMiddleware>(); \u002F\u002F before UseRouting\n```\n\n### 10.3 Removing PII from Existing Logs\n\n```bash\ngrep -rn \"_logger\\.\\|Log\\.\\|Console\\.\" src\u002F --include=\"*.cs\" | \\\n  grep -i \"email\\|password\\|token\\|ssn\\|credit\\|phone\\|address\"\n```\n\nReplace actual values with anonymized identifiers:\n```csharp\n\u002F\u002F BEFORE — logs actual email address\n_logger.LogInformation(\"User {Email} logged in\", user.Email);\n\u002F\u002F AFTER — logs only anonymized ID\n_logger.LogInformation(\"User {UserId} logged in\", user.Id);\n```\n\n---\n\n## PART 11: PHASE 7 — DEVSECOPS PIPELINE INSTALLATION\n\nInstall the pipeline on every repository, even before other phases are complete. A pipeline\nthat catches some issues on day one is better than a perfect pipeline on day ninety.\n\n### 11.1 Minimal Viable Security Pipeline (Install First)\n\n```yaml\n# .github\u002Fworkflows\u002Fsecurity.yml\nname: Security Gates\non:\n  push: { branches: [main, develop] }\n  pull_request: { branches: [main] }\npermissions:\n  security-events: write\n  contents: read\n\njobs:\n  secrets-scan:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n        with: { fetch-depth: 0 }  # full history required for Gitleaks\n      - uses: gitleaks\u002Fgitleaks-action@v2\n        env: { GITHUB_TOKEN: '${{ secrets.GITHUB_TOKEN }}' }\n\n  sast-semgrep:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: returntocorp\u002Fsemgrep-action@v1\n        with:\n          config: 'p\u002Fsecrets p\u002Fowasp-top-ten p\u002Fcsharp p\u002Ftypescript'\n          generateSarif: true\n      - uses: github\u002Fcodeql-action\u002Fupload-sarif@v3\n        with: { sarif_file: semgrep.sarif }\n        if: always()\n```\n\n### 11.2 Adding Gates Progressively (One Job Per Sprint)\n\n```yaml\n# Sprint 2 — add when dependency audit is clean enough to gate on\n  sca:\n    uses: snyk\u002Factions\u002Fdotnet@master\n    with: { args: '--severity-threshold=high' }\n\n# Sprint 2 — add when Docker images are in use\n  container-scan:\n    if: hashFiles('Dockerfile') != ''\n    # trivy CRITICAL,HIGH exit-code 1\n\n# Sprint 3 — add when IaC exists\n  iac-scan:\n    if: hashFiles('infra\u002F**\u002F*.bicep') != ''\n    # checkov bicep soft_fail false\n\n# Sprint 3 — add when coverage gate is established\n  build-and-test:\n    # dotnet test with coverage threshold\n```\n\n### 11.3 Pre-Commit Hook\n\n```bash\npip install pre-commit\n# .pre-commit-config.yaml\nrepos:\n  - repo: https:\u002F\u002Fgithub.com\u002Fgitleaks\u002Fgitleaks\n    rev: v8.18.0\n    hooks: [{ id: gitleaks }]\n  - repo: https:\u002F\u002Fgithub.com\u002Freturntocorp\u002Fsemgrep\n    rev: v1.45.0\n    hooks:\n      - id: semgrep\n        args: ['--config', 'p\u002Fsecrets', '--config', 'p\u002Fowasp-top-ten', '--error']\n  - repo: https:\u002F\u002Fgithub.com\u002Fpre-commit\u002Fpre-commit-hooks\n    rev: v4.5.0\n    hooks: [{ id: detect-private-key }, { id: detect-aws-credentials }]\n\n# Each developer runs once after cloning:\npre-commit install\n```\n\n---\n\n## PART 12: PHASE 8 — INFRASTRUCTURE MODERNIZATION\n\nThis phase requires coordination with the Azure admin. You produce the Bicep; the human reviews\nand applies it. Do not provision infrastructure autonomously.\n\n### 12.1 Key Vault Hardening\n\n```bash\naz keyvault show --name \u003Cvault-name> --query '{\n  rbacEnabled: properties.enableRbacAuthorization,\n  softDelete: properties.enableSoftDelete,\n  purgeProtection: properties.enablePurgeProtection,\n  publicAccess: properties.publicNetworkAccess\n}'\n```\n\n```bicep\nresource vault 'Microsoft.KeyVault\u002Fvaults@2023-07-01' = {\n  properties: {\n    enableRbacAuthorization: true\n    enableSoftDelete: true\n    softDeleteRetentionInDays: 90\n    enablePurgeProtection: true      \u002F\u002F IRREVERSIBLE — confirm with human before applying\n    publicNetworkAccess: 'Disabled'\n    networkAcls: { defaultAction: 'Deny', bypass: 'AzureServices' }\n  }\n}\n```\n\n### 12.2 Private Endpoint — Sequence Matters\n\n**The sequence matters.** Disabling public network access before the Private Endpoint is\nconfigured will break all connectivity. Always:\n\n1. Add the Private Endpoint\n2. Verify connectivity via the private endpoint\n3. Then disable public network access\n\n### 12.3 Managed Identity Role Assignment — Add Before Switching Code\n\nAlways assign the Managed Identity role **before** switching the connection code:\n\n1. Assign the role in Azure\n2. Verify the assignment propagates (can take 2-5 minutes)\n3. Deploy the code change\n4. Remove the old connection string from Key Vault (not before)\n\n```bicep\n\u002F\u002F Cosmos DB Built-in Data Contributor assignment\nresource cosmosRoleAssignment 'Microsoft.DocumentDB\u002FdatabaseAccounts\u002FsqlRoleAssignments@2024-05-15' = {\n  parent: cosmosAccount\n  name: guid(cosmosAccount.id, apiManagedIdentityPrincipalId, 'data-contributor')\n  properties: {\n    roleDefinitionId: '${cosmosAccount.id}\u002FsqlRoleDefinitions\u002F00000000-0000-0000-0000-000000000002'\n    principalId: apiManagedIdentityPrincipalId\n    scope: cosmosAccount.id\n  }\n}\n```\n\n---\n\n## PART 13: MIGRATION EXECUTION PROTOCOL (9 STEPS)\n\nFor every migration task, follow this sequence. The codebase must be passing after every step.\n\n```\nSTEP 1 — BASELINE\n  Run existing tests. Record the pass\u002Ffail count.\n  If tests were already failing: report to human before proceeding.\n  Run the Phase 0 assessment grep commands relevant to this component.\n\nSTEP 2 — SCOPE CONFIRMATION\n  State exactly what you are changing in this PR.\n  State what you are NOT changing.\n  If you discover P0 findings outside scope: log them; do not fix unilaterally.\n\nSTEP 3 — CHARACTERIZATION (if refactoring untested code)\n  Write characterization tests that capture current behavior before changing anything.\n  Run them. They must pass before you proceed.\n\nSTEP 4 — MAKE THE CHANGE\n  Apply the migration change (one logical change per PR).\n  Do not mix phases in a single PR.\n\nSTEP 5 — SECURITY TEST\n  Write the adversarial test that proves the attack is now blocked.\n  Write the positive test that proves the legitimate path still works.\n  Run both. Both must pass.\n\nSTEP 6 — QUALITY GATE\n  Run: format check → lint → type check → full test suite.\n  Coverage must not decrease from baseline recorded in Step 1.\n\nSTEP 7 — SEMGREP SCAN\n  semgrep scan --config p\u002Fsecrets --config p\u002Fowasp-top-ten \u003Cchanged_files>\n  Zero medium+ findings. Fix any before committing.\n\nSTEP 8 — COMMIT\n  Conventional Commits format. Use 'security' type for security fixes.\n  One logical change per commit.\n  No secrets: verify with: git diff --cached | grep -i \"password\\|secret\\|key\"\n\nSTEP 9 — DOCUMENT THE FINDING\n  Update the migration log: what was found, what was fixed, what remains outstanding.\n```\n\n### Commit Message Conventions for Migration Work\n\n```\n# Security fixes\nsecurity(api): add BOLA ownership check to document retrieval\nsecurity(auth): migrate JWT validation to Microsoft.Identity.Web\nsecurity(config): replace Cosmos DB connection string with Managed Identity\nsecurity(react): migrate MSAL token storage from localStorage to sessionStorage\n\n# Architecture migration\nrefactor(service): extract order business logic from OrdersController\nrefactor(repo): introduce IOrderRepository and Fake implementation\nrefactor(domain): define typed exception hierarchy\n\n# Pipeline installation\nci: add Gitleaks secrets scan to PR gate\nci: add Semgrep OWASP SAST to PR gate\n```\n\n---\n\n## PART 14: THE STRANGLER FIG PATTERN\n\nDo not rewrite existing code wholesale. Use the strangler fig:\n\n- New code is written to the full Security-First Scrum standard.\n- Old code is migrated one component at a time, each PR fully tested.\n- The old implementation is removed only after the new one is verified in production.\n- Feature flags decouple migration from release — the new auth flow can be deployed but not\n  activated until validated.\n\nEvery migration PR has a clear before and after state. The old code is removed in the same PR\nthat confirms the new code works. Never leave both old and new implementation in the codebase\nsimultaneously with unclear which one is authoritative.\n\n---\n\n## PART 15: THINGS TO NEVER DO DURING MODERNIZATION\n\n### Never — They Make the Codebase Less Safe\n\n- Disable or soft-fail a security gate to unblock a migration PR. Fix the finding.\n- Remove `[Authorize]` from an endpoint to make a test pass. Fix the test infrastructure.\n- Commit a \"temporary\" hardcoded secret while working out Key Vault integration. There is no\n  temporary credential in git history.\n- Rewrite authentication from scratch without testing every endpoint in the system.\n- Mix architectural refactoring (Phase 4) with security fixes (Phase 1-3) in the same PR.\n- Use `AllowAnyOrigin()` temporarily with a plan to tighten later. \"Later\" does not happen.\n- Switch to `ManagedIdentityCredential` before the role assignment is confirmed in Azure.\n- Disable public network access on a PaaS resource before a Private Endpoint is configured.\n- Delete old authentication code before the new flow is verified working in staging.\n- Set coverage gates at 80% on a 20% codebase. Set at current + 5%.\n- Fix a vulnerability in a different component than the one tasked. Log it. Surface it.\n\n### Never — They Violate People First\n\n- Make infrastructure changes (Bicep, role assignments, network rules) without human confirmation.\n- Rotate credentials autonomously. Credential rotation has organizational consequences.\n- Scope-creep silently. Surface immediately when the task is larger than expected.\n- Leave the human with a broken build. Stop, restore last working state, report what you found.\n\n---\n\n## PART 16: MIGRATION ANTI-PATTERNS\n\n**The \"big bang\" anti-pattern:** Attempting to migrate all authentication, fix all SQL injection,\nrestructure all layers, add the DevSecOps pipeline, and write all missing tests in a single\nsprint. Produces a PR nobody can safely review.\n*Correct approach: One phase per sprint. One component per PR.*\n\n**The \"fix it forward\" anti-pattern:** Encountering a broken test and \"fixing\" it to make the\nnew code pass, without understanding why it was failing.\n*Correct approach: Understand the failure. If your change is correct and the test was wrong,\nupdate the test and document why.*\n\n**The \"security theater\" anti-pattern:** Adding `[Authorize]` attributes while leaving the\nmiddleware pipeline in the wrong order. The decorators exist; the authorization does nothing.\n*Correct approach: Verify the middleware pipeline order before declaring auth migration complete.*\n\n**The \"abandoned strangler\" anti-pattern:** Starting a component migration but not completing it\n— leaving both old and new implementation with unclear authority.\n*Correct approach: Remove old code in the same PR that verifies the new code works.*\n\n**The \"coverage inflation\" anti-pattern:** Writing tests with no assertions to achieve coverage\nnumbers.\n*Correct approach: Coverage is a signal. A test without meaningful assertions is worse than no\ntest — it creates false confidence.*\n",{"name":5,"description":7},"develop","ae32736a1aabddabca5d2c96d665aa0ebc7d8700","src\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fsecurity-first-dev\u002Fskills\u002Fcodebase-modernization",3,"https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey","https:\u002F\u002Fthe-vibey-project.github.io\u002Fvibey\u002F","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project","https:\u002F\u002Fvibewithadam.matthewsteinberger.com","freedom for software engineers","2026-11-15 05:47:42",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add the-vibey-project\u002Fvibey --skill codebase-modernization",{"tool":40,"command":41},"bunx","bunx skills add the-vibey-project\u002Fvibey --skill codebase-modernization",{"tool":43,"command":44},"pnpm","pnpm dlx skills add the-vibey-project\u002Fvibey --skill codebase-modernization","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fsecurity-first-dev\u002Fskills\u002Fcodebase-modernization\u002FSKILL.md",true,[],[49,56,63,70,77,84],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":19},"01M7AT1FQJAE1FQYAMDTF490Y4","white-paper-writing","Use when writing white papers, technical reports, policy documents, thought leadership pieces, or any long-form authoritative document. Triggers on requests to write, structure, outline, or review white papers, technical reports, position papers, policy briefs, or evidence-driven arguments. Also use for B2B content marketing strategy, technical documentation requiring authority, academic-style reports, or any document that must educate while persuading. Use when someone asks \"how should I structure this\" for a long-form document.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Fwhite-paper-writing\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":59,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":60,"categories":61,"keywords":62,"publishedAt":19},"01M7AT16BJRJJKK2MASXRZS76G","prose-technical-mechanics","Use when editing or writing prose at a technical\u002Fmechanical level: choosing between Anglo-Saxon and Latinate diction, placing information in topic vs stress positions, writing periodic vs cumulative sentences, handling sentence rhythm, punctuation as logic, transitions, paragraph structure, or phonesthetics. Use when someone wants to understand WHY prose works or doesn't, not just surface-level style advice. Triggers on word choice, sentence structure, emphasis, rhythm, diction, or any deep writing mechanics question.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Fprose-technical-mechanics\u002FSKILL.md",[],[],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":19},"01M7AT0W9HT0ZZ9Y287NW99MR3","prose-mechanics","Use when writing, editing, or analyzing prose style; when trying to avoid generic AI-sounding writing; when applying specific prose styles such as journalistic, academic, narrative, KJV biblical, Hemingway plain, Latinate\u002FJamesian, Orwellian, Augustan, Victorian, Early Modern (Bacon, Browne, Milton), or free indirect discourse; or when coaching someone on writing voice and mechanics. Triggers on any request to improve, analyze, or write in a specific prose style, to fix \"AI-sounding\" writing, to make prose more vivid or concrete, to vary sentence rhythm, or to understand how a particular writer achieves their effects.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Fprose-mechanics\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M7AT0KR635JX66X2X6F3E2CP","narrative-structure","Use when structuring stories, pitches, presentations, white papers, or any persuasive narrative; analyzing the hero's journey in fiction or non-fiction; applying StoryBrand for business communication; designing narrative arcs for thought leadership; or understanding Vogler, Snyder, Propp, or Campbell frameworks. Triggers on any narrative structure, storytelling, pitch structure, StoryBrand, hero's journey, three-act structure, Freytag, Save the Cat, narrative arc, or \"how should I structure this story\u002Fpitch\u002Fpresentation\" request.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Fnarrative-structure\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":19},"01M7AT0AKGW09NKKZDYBT8VRDE","legal-brief-writing","Use when writing legal briefs, motions, or any court filing; when analyzing judicial cognition and persuasion; when applying elite brief-writing techniques from Roberts, Clement, Kagan, Garner; or when structuring legal arguments for maximum persuasion. Also use for autistic\u002Fneurodivergent advocates who need to understand how their natural communication style maps to elite legal advocacy. Triggers on any legal writing, brief drafting, motion preparation, or legal argument structuring request.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Flegal-brief-writing\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M7AT00VWPS4Q8B5VEMXX9NQT","journal-publishability-criteria","Use whenever a research paper, article or preprint is being written, revised, reviewed or published, and specifically before every publication of docs\u002Fpaper.md. Covers what legitimate journals actually gate on, in order of gating — the editor's desk screen (scope, novelty, package problems), what reviewers judge (methodological soundness, claims the evidence can carry, statistical and qualitative reporting), EQUATOR reporting guidelines, the ICMJE authorship criteria, COPE's view of text recycling, the near-universal generative-AI policy (no AI author, disclosure, author responsibility), TOP 2025 transparency standards, how to verify a journal is legitimate, submitting without an institution, and a pre-submission checklist. Triggers on requests to evaluate, review, prepare or submit a paper, to judge publishability, to write a declarations or data-availability section, to disclose AI use, or to check a journal.","https:\u002F\u002Fgithub.com\u002Fthe-vibey-project\u002Fvibey\u002Fblob\u002Fdevelop\u002Fsrc\u002Fvibey_tools\u002Fskills\u002Fplugins\u002Fwriting-craft\u002Fskills\u002Fjournal-publishability-criteria\u002FSKILL.md",[],[]]