Opinionated Rules for building, shipping, and operating secure software supply chains using TypeScript, GitHub Actions, SLSA, SBOMs, and Zero-Trust principles.
Modern software supply chains are under siege. With over 650% increase in supply chain attacks since 2021, every dependency you pull, every third-party service you integrate, and every build artifact you ship becomes a potential attack vector. One compromised dependency can expose your entire production environment.
Your current development workflow likely includes these security gaps:
Each of these creates an opportunity for attackers to inject malicious code into your production systems through your trusted development processes.
These Cursor Rules implement a comprehensive security framework that transforms your TypeScript applications into fortress-grade supply chain operations. You get automated security gates, cryptographic verification, and continuous monitoring built directly into your development workflow.
The rules enforce SLSA (Supply Chain Levels for Software Artifacts) compliance, generate Software Bills of Materials (SBOMs) for every release, and implement zero-trust verification throughout your entire toolchain.
Every artifact gets signed with Cosign and stored with provenance data:
// Automated in your CI/CD pipeline
cosign sign --key kms://gcp/key dist/image.tar
slsa-provenance attestation dist/image.tar
Continuous vulnerability scanning catches issues before they reach production:
- run: trivy image --exit-code 1 dist/image.tar
- run: osv-scanner --lockfile package-lock.json
Every interaction requires verification with structured error handling:
type Result<T,E extends Error> = { ok:true; value:T } | { ok:false; error:E }
function registerSupplier(raw: unknown): Result<Supplier,ValidationError> {
const parse = Supplier.safeParse(raw);
return parse.success ? { ok:true, value:parse.data } : { ok:false, error:parse.error };
}
Stop blindly trusting package registries. Pin exact versions and validate every dependency:
// src/types/dependency-validation.ts
import { z } from 'zod';
const DependencyManifest = z.object({
name: z.string(),
version: z.string().regex(/^\d+\.\d+\.\d+$/), // Exact version only
integrity: z.string(),
signatures: z.array(z.string())
});
export function validateDependency(manifest: unknown): Result<DependencyManifest, ValidationError> {
const parse = DependencyManifest.safeParse(manifest);
return parse.success ? { ok: true, value: parse.data } : { ok: false, error: parse.error };
}
Get complete visibility into your software composition:
# .github/workflows/security-build.yml
- name: Generate SBOM
run: |
syft . -o spdx-json > sbom.spdx.json
syft . -o cyclonedx-json > sbom.cyclonedx.json
- name: Upload SBOM to Registry
run: |
cosign attach sbom --sbom sbom.spdx.json ghcr.io/org/app:${{ github.sha }}
Continuously assess your third-party vendors:
// src/domain/supplier-assessment.ts
interface SupplierScorecard {
supplierId: string;
securityRating: number;
lastAssessment: Date;
criticalVulnerabilities: number;
complianceStatus: 'compliant' | 'non-compliant' | 'pending';
}
export class SupplierMonitor {
async assessSupplier(supplierId: string): Promise<Result<SupplierScorecard, AssessmentError>> {
// Integration with SecurityScorecard API
const assessment = await this.securityScorecard.getSupplierRating(supplierId);
if (assessment.securityRating < 70) {
return { ok: false, error: new AssessmentError('Supplier below security threshold') };
}
return { ok: true, value: assessment };
}
}
Create your security configuration:
# Install security tooling
npm install --save-dev @types/node zod pino
npm install --global @cyclonedx/cli syft cosign
# Configure exact dependency pinning
npm pkg set engines.node=">=18.0.0"
npm pkg set overrides.axios="1.6.2"
Structure your project with security isolation:
src/
├── domain/ # Pure business logic
│ ├── supplier-management.ts
│ └── risk-assessment.ts
├── adapters/ # External integrations
│ ├── security-scorecard.ts
│ └── vulnerability-scanner.ts
├── infra/ # Cloud security services
│ ├── kms-signing.ts
│ └── secret-manager.ts
└── types/ # Security contracts
├── supplier.ts
└── vulnerability.ts
Set up automated security gates in GitHub Actions:
# .github/workflows/security-pipeline.yml
name: Security Pipeline
on: [push, pull_request]
permissions:
contents: read
id-token: write
security-events: write
jobs:
security-scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608
- name: Setup Node.js
uses: actions/setup-node@5e21ff4d9bc1a8cf6de233a3057d20ec6b3fb69d
- name: Install dependencies
run: npm ci --ignore-scripts
- name: Run security audit
run: npm audit --audit-level=critical
- name: Generate SBOM
run: syft . -o spdx-json > sbom.spdx.json
- name: Vulnerability scan
run: trivy fs --exit-code 1 --severity HIGH,CRITICAL .
- name: Build and sign artifacts
run: |
npm run build
cosign sign --key kms://gcp/projects/PROJECT/locations/LOCATION/keyRings/RING/cryptoKeys/KEY dist/
Set up real-time security monitoring:
// src/adapters/security-monitor.ts
import { EventEmitter } from 'events';
export class SecurityMonitor extends EventEmitter {
private honeytokens: Map<string, string> = new Map();
constructor(private logger: Logger) {
super();
this.deployHoneytokens();
}
private deployHoneytokens() {
// Deploy decoy secrets that alert when accessed
this.honeytokens.set('fake-api-key', 'honey_123456789');
this.honeytokens.set('fake-db-password', 'honey_password123');
}
detectAnomalies(event: SecurityEvent): void {
if (this.honeytokens.has(event.resource)) {
this.logger.error({
event: 'honeytoken_access',
resource: event.resource,
sourceIP: event.sourceIP,
timestamp: new Date().toISOString()
});
this.emit('security_breach', event);
}
}
}
Your development team gets enterprise-grade supply chain security without sacrificing velocity. Every commit is automatically validated, every dependency is verified, and every deployment is cryptographically signed and tracked.
The rules transform your TypeScript applications into a secure-by-design system that proactively prevents supply chain attacks while maintaining the development experience your team expects.
You are an expert in secure-by-design supply-chain engineering across TypeScript, Python, Go, Shell, Terraform, Docker, Kubernetes, GitHub Actions, SLSA, SBOM, Blockchain, IoT, and AI-driven analytics.
Key Principles
- Shift-left security: every pull-request must pass automated security gates before merge.
- Zero-Trust posture: no implicit trust; continuous identity & artifact verification.
- Reproducible, hermetic builds inside containerised tool-chains, pinned by digest.
- Immutable, signed artifacts: Cosign-sign all images/binaries & attach provenance.
- Least-privilege everywhere: fine-grained RBAC + mandatory MFA.
- Transparency & traceability: generate and publish SBOM + SLSA provenance for each release.
- Continuous monitoring: AI-driven anomaly detection, honeytokens, real-time alerts.
- Standardised supplier governance: VSAQ + quarterly attestations; onboard/off-board via documented checklist.
TypeScript
- Target ES2022, enable `strict`. No `any`, no implicit returns.
- Pure business logic lives in `src/domain`; isolate side-effects in `src/adapters`.
- Runtime validation at module boundaries with `zod/io-ts` schemas.
- Treat configuration as immutable: wrap in `Readonly<T>`; prohibit runtime mutation.
- Directory layout:
src/
├─ domain/ # Pure, deterministic functions
├─ adapters/ # HTTP, DB, blockchain, IoT bridges
├─ infra/ # Cloud SDK wrappers (AWS, GCP, Azure)
├─ pipelines/ # Build & release scripts
└─ types/ # Shared typed contracts
- File naming: scripts in snake_case (`generate_sbom.ts`); React components in kebab-case (`supply-chain-table.tsx`).
- Pin exact dependency versions—no caret/tilde ranges; use `npm pkg set overrides` for transitive pins.
- Use ESM imports; top-level await allowed only in CLIs.
Error Handling & Validation
- Validate all external inputs immediately; reject invalid data with typed error unions:
```ts
type Result<T,E extends Error> = { ok:true; value:T } | { ok:false; error:E }
```
- Fail fast on security anomalies; mask sensitive details in client responses, supply full context to SIEM.
- Structured logs via `pino`; always include `traceId`, `artifactId`, and `supplierId` fields.
- Deploy honeytokens (decoy secrets, fake S3 buckets) and raise P1 alert on access.
CI/CD – GitHub Actions + SLSA
- Workflows live in `.github/workflows/*.yaml`; reference actions by SHA, never by tag or branch.
- OIDC-based cloud auth; forbid static credentials.
- Canonical job template:
```yaml
permissions: { contents: read, id-token: write }
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@<sha>
- uses: actions/setup-node@<sha>
- run: npm ci --ignore-scripts
- run: npm run build
- run: syft dir:. -o spdx-json > sbom.spdx.json
- run: cosign sign --key kms://gcp/... dist/image.tar
- run: slsa-provenance attestation dist/image.tar
- run: trivy image --exit-code 1 dist/image.tar
- run: crane push dist/image.tar registry.io/project/img@sha256:...
```
- Generate SBOM (`syft`), vulnerability scan (`trivy` + `grype`), and fail build on critical CVEs.
- Store provenance & SBOM in an OCI-compatible registry or Rekor transparency log.
Testing
- Mandatory tests: unit (Jest), integration (docker-compose), security (semgrep, OSV-scanner, ZAP).
- Achieve ≥90 % line & branch coverage in `src/domain` and `src/pipelines`.
- Include mutation testing (`stryker`) for critical cryptographic code.
Performance & Scalability
- Stream IoT telemetry via MQTT → Kafka → RxJS pipelines; apply back-pressure operators to avoid overload.
- AI risk-scoring micro-service runs on GPU node pool; autoscale on queue length + latency SLO.
Security Hardening
- TLS 1.3 everywhere; mutual-TLS for internal gRPC.
- Secrets in Hashicorp Vault; automated rotation ≤90 days.
- Apply Policy-as-Code (OPA/Rego) to validate Kubernetes manifests & Terraform plans during CI.
- Enforce WAF rate-limiting & JWT auth on every API.
Compliance & Audit
- Emit audit events to immutable storage (S3 WORM) with 1-year retention.
- Weekly automated report includes: SLSA level, SBOM diffs, open CVEs, supplier scorecard.
Examples
- Generating an SBOM inside a build step:
```sh
syft . -o spdx-json > sbom.spdx.json
```
- Signing and pushing an artifact:
```sh
cosign sign --key kms://gcp/key dist/image.tar
crane push dist/image.tar ghcr.io/org/img@$(sha256sum dist/image.tar | awk '{print $1}')
```
- Runtime schema validation:
```ts
import { z } from 'zod';
const Supplier = z.object({ id: z.string().uuid(), name: z.string(), rating: z.number().min(0).max(100) });
function registerSupplier(raw: unknown): Result<Supplier,ValidationError> {
const parse = Supplier.safeParse(raw);
return parse.success ? { ok:true, value:parse.data } : { ok:false, error:parse.error };
}
```