AgentSkillsCN

distribution-security

为分布式软件构建纵深防御体系,强化 PII 保护、敏感信息扫描,以及安全打包机制。

SKILL.md
--- frontmatter
name: "distribution-security"
description: "Defense-in-depth, PII protection, secrets scanning, and secure packaging for distributed software"
metadata:
  inheritance: inheritable

Distribution Security

Multi-layer security for software that ships to users — secrets scanning, permission minimization, and secure UI patterns.

Scope: Inheritable skill. Covers defense-in-depth architecture, PII protection, secrets scanning, permission minimization, CSP patterns, and secure WebView communication.

Defense-in-Depth Architecture

4-Layer Security Model

Every distributed application needs four independent security layers:

LayerFunctionFailure Mode
1. AuthenticationVerify identity (OAuth, MSAL, API keys)Unauthorized access
2. AuthorizationRole-based access control (RBAC)Privilege escalation
3. Secrets ScanningDetect leaked credentials in sourceData breach
4. Audit LoggingRecord all security-relevant eventsUndetected compromise

Rule: Each layer must work independently. A failure in Layer 1 should not cascade — Layer 2 still blocks unauthorized actions, Layer 3 still catches leaked keys, Layer 4 still records the attempt.

PII Protection

3-Layer Exclusion Model

For projects that package and distribute source files:

LayerImplementationCatches
1. .gitignoreExclude from version controlPersonal config, local data
2. .vscodeignore / build exclusionsExclude from packageDev-only files, test data
3. Build pipeline scanRegex validation gateAnything layers 1-2 missed

Personal Data Rules

LocationAllowed?Alternative
Source code headersNoUse team/org name
package.json authorOrg name only"author": "Team Name"
README creditsGeneric unless opted in"Created by the team"
Error messagesNo PII everUse error codes
TelemetryNo PII without consentAnonymized identifiers

Rationale: Users installing software see package.json and source headers. Personal names create trust concerns and privacy issues.

Secrets Scanning

Detection Patterns

PatternRegexSeverity
API keys/[A-Za-z0-9_\-]{32,}/High
Connection strings/Server=.*;[P]assword=.*/iCritical
JWT tokens/eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+/Critical
Private keys/-----BEGIN.*PRIVATE KEY-----/Critical
Azure keys/[A-Za-z0-9+/]{86}==/High

False Positive Reduction

Naive regex scanning floods developers with noise. Filter these contexts:

ContextExampleAction
Import statementsimport { KEY_LENGTH } from...Skip
Comments explaining patterns// API keys look like: abc123...Skip
Env variable definitionsconst API_KEY = process.env.KEYSkip (value is reference)
Test fixtures with dummy dataconst testKey = "test-key-1234"Skip if in test folder
Actual hardcoded secretsconst key = "sk-live-abc123..."ALERT

Rule: Only alert on literal string values that match secret patterns outside of comments, imports, and environment variable references.

Priority Matrix for Findings

When security audits surface findings, triage with this matrix:

PriorityCriteriaSLA
P0Active secret exposure, data breachImmediate (hours)
P1Vulnerability in auth/authz layer24 hours
P2Missing security control (no CSP, etc.)Sprint
P3Best practice gap (logging format, etc.)Backlog

Permission Minimization

The Less-Is-More Principle

Request ONLY the permissions your software actually uses:

Anti-patternProblemFix
Request Mail.Send for reading contactsUsers fear email spamRequest Contacts.Read only
Request admin scopes "for future use"Over-privileged from day oneRequest when feature ships
Broad * scopesNo granular controlRequest specific sub-scopes

Rule: Users evaluate trust based on the scariest permission requested. One unnecessary permission can tank adoption.

Permission Audit Checklist

For every capability that requires a permission:

  1. Is this the minimum scope that enables the feature?
  2. Can this be a delegated permission (user context) instead of application?
  3. Can this be requested just-in-time instead of at install?
  4. Does the permission description match what users expect?
  5. Can we function without this permission (graceful degradation)?

Content Security Policy (CSP)

Secure UI Patterns

For WebViews, panels, and embedded web content:

Anti-patternProblemSecure Alternative
onclick="handler()"Inline scripts violate CSPdata-cmd attribute + delegated listener
eval()Code injection vectorPre-compiled templates
innerHTML = userInputXSS vulnerabilitytextContent or sanitized HTML
<script src="cdn">External dependency riskBundle locally

Data-Cmd Pattern

Replace inline event handlers with data attributes:

html
<!-- Anti-pattern: inline handler (blocked by CSP) -->
<button onclick="doThing()">Click</button>

<!-- Secure: data-cmd + delegated listener -->
<button data-cmd="do-thing">Click</button>

<script>
  document.addEventListener('click', (e) => {
    const cmd = e.target.closest('[data-cmd]')?.dataset.cmd;
    if (cmd) handleCommand(cmd);
  });
</script>

WebView Security

Communication Pattern

WebViews run in sandboxed iframes. Communication must use message passing:

DirectionMethodExample
Extension → WebViewwebview.postMessage(data)Send state updates
WebView → Extensionvscode.postMessage(data)Report user actions
WebView → External URLBLOCKEDwindow.open() silently fails
WebView → Local filesVia extension onlyRequest through message

Critical: window.open() silently fails in WebViews. Links that need to open externally must send a message to the extension, which calls vscode.env.openExternal().

Message Validation

Always validate messages on both sides:

typescript
// Extension side - validate WebView messages
panel.webview.onDidReceiveMessage((msg) => {
  if (!msg.type || typeof msg.type !== 'string') return;
  switch (msg.type) {
    case 'save': handleSave(msg.data); break;
    case 'navigate': handleNavigate(msg.url); break;
    // Ignore unknown message types
  }
});

Kill Switch Pattern

Multi-Layer Protection for Destructive Operations

For operations that could cause irreversible damage:

LayerImplementationPurpose
1. Marker filePresence of protection file blocks operationStatic guard
2. Confirmation dialog"Are you sure?" promptUser intent validation
3. Typed confirmationUser must type exact phrasePrevent accidental clicks
4. Cooldown timerWait N seconds before enabling actionPrevent impulse actions
5. Audit logRecord who triggered what and whenPost-incident analysis

Rule: The confirmation dialog ("I Understand" button) must STILL block the destructive action even if earlier layers fail. Each layer is independent.

Security Testing

Test Priority Order

When adding test coverage to security-critical code:

TierCoverage TargetWhat to Test
1. Auth/AuthZ80%+ firstToken validation, role checks, permission gates
2. Input validation80%+ nextSanitization, bounds, injection prevention
3. Secrets handlingFull coverageNo secrets in logs, proper encryption
4. UI/cosmeticAfter securityLayout, theming, preferences

Rule: Achieve 80%+ coverage on Tier 1 before touching Tier 4. In a resource-constrained sprint, security tests win over UI tests every time.

SFI Compliance (Azure/Microsoft)

Audit Scope

Security audits must scan the full subscription, not just infrastructure-as-code:

MethodCoversMisses
IaC scanning (Bicep/Terraform)Declared resourcesManually created resources
az resource list --subscription XAll resourcesConfig drift within resources
Azure Policy + DefenderCompliance postureApplication-level vulns

Rule: Always combine IaC scanning with live subscription scanning. Manual portal clicks create resources that IaC scans will never find.