pci-compliance by sickn33/antigravity-awesome-skills
npx skills add https://github.com/sickn33/antigravity-awesome-skills --skill pci-compliance掌握 PCI DSS(支付卡行业数据安全标准)合规性,以实现安全的支付处理和持卡人数据处理。
resources/implementation-playbook.md。广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
级别 1 : 年交易量 > 600 万笔(需要年度合规报告 ROC) 级别 2 : 年交易量 100 万至 600 万笔(需要年度自我评估问卷 SAQ) 级别 3 : 年电子商务交易量 2 万至 100 万笔 级别 4 : 年电子商务交易量 < 2 万笔 或 年总交易量 < 100 万笔
# 绝不存储这些数据
PROHIBITED_DATA = {
'full_track_data': '磁条数据',
'cvv': '卡验证码/值',
'pin': 'PIN 码或 PIN 块'
}
# 可以存储(如果已加密)
ALLOWED_DATA = {
'pan': '主账号(卡号)',
'cardholder_name': '持卡人姓名',
'expiration_date': '卡有效期',
'service_code': '服务代码'
}
class PaymentData:
"""安全的支付数据处理。"""
def __init__(self):
self.prohibited_fields = ['cvv', 'cvv2', 'cvc', 'pin']
def sanitize_log(self, data):
"""从日志中移除敏感数据。"""
sanitized = data.copy()
# 掩码处理 PAN
if 'card_number' in sanitized:
card = sanitized['card_number']
sanitized['card_number'] = f"{card[:6]}{'*' * (len(card) - 10)}{card[-4:]}"
# 移除禁止存储的数据
for field in self.prohibited_fields:
sanitized.pop(field, None)
return sanitized
def validate_no_prohibited_storage(self, data):
"""确保没有存储禁止的数据。"""
for field in self.prohibited_fields:
if field in data:
raise SecurityError(f"试图存储禁止的字段: {field}")
import stripe
class TokenizedPayment:
"""使用令牌处理支付(服务器上无卡数据)。"""
@staticmethod
def create_payment_method_token(card_details):
"""从卡信息创建令牌(仅在客户端)。"""
# 这应仅在使用 Stripe.js 的客户端完成
# 切勿将卡信息发送到您的服务器
"""
// 前端 JavaScript
const stripe = Stripe('pk_...');
const {token, error} = await stripe.createToken({
card: {
number: '4242424242424242',
exp_month: 12,
exp_year: 2024,
cvc: '123'
}
});
// 将 token.id 发送到服务器(不是卡信息)
"""
pass
@staticmethod
def charge_with_token(token_id, amount):
"""使用令牌扣款(服务器端)。"""
# 您的服务器只看到令牌,永远看不到卡号
stripe.api_key = "sk_..."
charge = stripe.Charge.create(
amount=amount,
currency="usd",
source=token_id, # 使用令牌而非卡信息
description="支付"
)
return charge
@staticmethod
def store_payment_method(customer_id, payment_method_token):
"""将支付方法存储为令牌以供将来使用。"""
stripe.Customer.modify(
customer_id,
source=payment_method_token
)
# 仅在数据库中存储 customer_id 和 payment_method_id
# 切勿存储实际的卡信息
return {
'customer_id': customer_id,
'has_payment_method': True
# 不要存储:卡号、CVV 等。
}
import secrets
from cryptography.fernet import Fernet
class TokenVault:
"""用于卡数据的安全令牌库(如果必须存储)。"""
def __init__(self, encryption_key):
self.cipher = Fernet(encryption_key)
self.vault = {} # 生产环境:使用加密数据库
def tokenize(self, card_data):
"""将卡数据转换为令牌。"""
# 生成安全的随机令牌
token = secrets.token_urlsafe(32)
# 加密卡数据
encrypted = self.cipher.encrypt(json.dumps(card_data).encode())
# 存储令牌 -> 加密数据的映射
self.vault[token] = encrypted
return token
def detokenize(self, token):
"""从令牌中检索卡数据。"""
encrypted = self.vault.get(token)
if not encrypted:
raise ValueError("未找到令牌")
# 解密
decrypted = self.cipher.decrypt(encrypted)
return json.loads(decrypted.decode())
def delete_token(self, token):
"""从库中移除令牌。"""
self.vault.pop(token, None)
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import os
class EncryptedStorage:
"""使用 AES-256-GCM 加密静态数据。"""
def __init__(self, encryption_key):
"""使用 256 位密钥初始化。"""
self.key = encryption_key # 必须为 32 字节
def encrypt(self, plaintext):
"""加密数据。"""
# 生成随机 nonce
nonce = os.urandom(12)
# 加密
aesgcm = AESGCM(self.key)
ciphertext = aesgcm.encrypt(nonce, plaintext.encode(), None)
# 返回 nonce + 密文
return nonce + ciphertext
def decrypt(self, encrypted_data):
"""解密数据。"""
# 提取 nonce 和密文
nonce = encrypted_data[:12]
ciphertext = encrypted_data[12:]
# 解密
aesgcm = AESGCM(self.key)
plaintext = aesgcm.decrypt(nonce, ciphertext, None)
return plaintext.decode()
# 用法示例
storage = EncryptedStorage(os.urandom(32))
encrypted_pan = storage.encrypt("4242424242424242")
# 将 encrypted_pan 存储在数据库中
# 始终使用 TLS 1.2 或更高版本
# Flask/Django 示例
app.config['SESSION_COOKIE_SECURE'] = True # 仅 HTTPS
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SAMESITE'] = 'Strict'
# 强制使用 HTTPS
from flask_talisman import Talisman
Talisman(app, force_https=True)
from functools import wraps
from flask import session
def require_pci_access(f):
"""限制对持卡人数据访问的装饰器。"""
@wraps(f)
def decorated_function(*args, **kwargs):
user = session.get('user')
# 检查用户是否具有 PCI 访问角色
if not user or 'pci_access' not in user.get('roles', []):
return {'error': '未经授权访问持卡人数据'}, 403
# 记录访问尝试
audit_log(
user=user['id'],
action='access_cardholder_data',
resource=f.__name__
)
return f(*args, **kwargs)
return decorated_function
@app.route('/api/payment-methods')
@require_pci_access
def get_payment_methods():
"""检索支付方法(受限访问)。"""
# 仅对具有 pci_access 角色的用户可访问
pass
import logging
from datetime import datetime
class PCIAuditLogger:
"""PCI 合规的审计日志记录。"""
def __init__(self):
self.logger = logging.getLogger('pci_audit')
# 配置为写入安全的、仅追加的日志
def log_access(self, user_id, resource, action, result):
"""记录对持卡人数据的访问。"""
entry = {
'timestamp': datetime.utcnow().isoformat(),
'user_id': user_id,
'resource': resource,
'action': action,
'result': result,
'ip_address': request.remote_addr
}
self.logger.info(json.dumps(entry))
def log_authentication(self, user_id, success, method):
"""记录身份验证尝试。"""
entry = {
'timestamp': datetime.utcnow().isoformat(),
'user_id': user_id,
'event': 'authentication',
'success': success,
'method': method,
'ip_address': request.remote_addr
}
self.logger.info(json.dumps(entry))
# 用法示例
audit = PCIAuditLogger()
audit.log_access(user_id=123, resource='payment_methods', action='read', result='success')
import re
def validate_card_number(card_number):
"""验证卡号格式(Luhn 算法)。"""
# 移除空格和破折号
card_number = re.sub(r'[\s-]', '', card_number)
# 检查是否全为数字
if not card_number.isdigit():
return False
# Luhn 算法
def luhn_checksum(card_num):
def digits_of(n):
return [int(d) for d in str(n)]
digits = digits_of(card_num)
odd_digits = digits[-1::-2]
even_digits = digits[-2::-2]
checksum = sum(odd_digits)
for d in even_digits:
checksum += sum(digits_of(d * 2))
return checksum % 10
return luhn_checksum(card_number) == 0
def sanitize_input(user_input):
"""清理用户输入以防止注入。"""
# 移除特殊字符
# 根据预期格式进行验证
# 转义数据库查询
pass
PCI_COMPLIANCE_CHECKLIST = {
'network_security': [
'防火墙已配置和维护',
'无供应商默认密码',
'已实施网络分段'
],
'data_protection': [
'未存储 CVV、磁道数据或 PIN',
'PAN 存储时已加密',
'PAN 显示时已掩码',
'加密密钥管理得当'
],
'vulnerability_management': [
'已安装并更新防病毒软件',
'安全的开发实践',
'定期安全补丁',
'已执行漏洞扫描'
],
'access_control': [
'按角色限制访问',
'所有用户具有唯一 ID',
'多因素身份验证',
'物理安全措施'
],
'monitoring': [
'已启用审计日志',
'日志审查流程',
'文件完整性监控',
'定期安全测试'
],
'policy': [
'安全策略已文档化',
'已执行风险评估',
'安全意识培训',
'事件响应计划'
]
}
通过最小化接触卡数据的系统,可以显著减轻合规负担。
每周安装量
89
代码仓库
GitHub 星标数
27.4K
首次出现
2026 年 1 月 28 日
安全审计
安装于
opencode86
gemini-cli85
cursor85
claude-code84
github-copilot82
codex82
Master PCI DSS (Payment Card Industry Data Security Standard) compliance for secure payment processing and handling of cardholder data.
resources/implementation-playbook.md.Level 1 : > 6 million transactions/year (annual ROC required) Level 2 : 1-6 million transactions/year (annual SAQ) Level 3 : 20,000-1 million e-commerce transactions/year Level 4 : < 20,000 e-commerce or < 1 million total transactions
# NEVER STORE THESE
PROHIBITED_DATA = {
'full_track_data': 'Magnetic stripe data',
'cvv': 'Card verification code/value',
'pin': 'PIN or PIN block'
}
# CAN STORE (if encrypted)
ALLOWED_DATA = {
'pan': 'Primary Account Number (card number)',
'cardholder_name': 'Name on card',
'expiration_date': 'Card expiration',
'service_code': 'Service code'
}
class PaymentData:
"""Safe payment data handling."""
def __init__(self):
self.prohibited_fields = ['cvv', 'cvv2', 'cvc', 'pin']
def sanitize_log(self, data):
"""Remove sensitive data from logs."""
sanitized = data.copy()
# Mask PAN
if 'card_number' in sanitized:
card = sanitized['card_number']
sanitized['card_number'] = f"{card[:6]}{'*' * (len(card) - 10)}{card[-4:]}"
# Remove prohibited data
for field in self.prohibited_fields:
sanitized.pop(field, None)
return sanitized
def validate_no_prohibited_storage(self, data):
"""Ensure no prohibited data is being stored."""
for field in self.prohibited_fields:
if field in data:
raise SecurityError(f"Attempting to store prohibited field: {field}")
import stripe
class TokenizedPayment:
"""Handle payments using tokens (no card data on server)."""
@staticmethod
def create_payment_method_token(card_details):
"""Create token from card details (client-side only)."""
# THIS SHOULD ONLY BE DONE CLIENT-SIDE WITH STRIPE.JS
# NEVER send card details to your server
"""
// Frontend JavaScript
const stripe = Stripe('pk_...');
const {token, error} = await stripe.createToken({
card: {
number: '4242424242424242',
exp_month: 12,
exp_year: 2024,
cvc: '123'
}
});
// Send token.id to server (NOT card details)
"""
pass
@staticmethod
def charge_with_token(token_id, amount):
"""Charge using token (server-side)."""
# Your server only sees the token, never the card number
stripe.api_key = "sk_..."
charge = stripe.Charge.create(
amount=amount,
currency="usd",
source=token_id, # Token instead of card details
description="Payment"
)
return charge
@staticmethod
def store_payment_method(customer_id, payment_method_token):
"""Store payment method as token for future use."""
stripe.Customer.modify(
customer_id,
source=payment_method_token
)
# Store only customer_id and payment_method_id in your database
# NEVER store actual card details
return {
'customer_id': customer_id,
'has_payment_method': True
# DO NOT store: card number, CVV, etc.
}
import secrets
from cryptography.fernet import Fernet
class TokenVault:
"""Secure token vault for card data (if you must store it)."""
def __init__(self, encryption_key):
self.cipher = Fernet(encryption_key)
self.vault = {} # In production: use encrypted database
def tokenize(self, card_data):
"""Convert card data to token."""
# Generate secure random token
token = secrets.token_urlsafe(32)
# Encrypt card data
encrypted = self.cipher.encrypt(json.dumps(card_data).encode())
# Store token -> encrypted data mapping
self.vault[token] = encrypted
return token
def detokenize(self, token):
"""Retrieve card data from token."""
encrypted = self.vault.get(token)
if not encrypted:
raise ValueError("Token not found")
# Decrypt
decrypted = self.cipher.decrypt(encrypted)
return json.loads(decrypted.decode())
def delete_token(self, token):
"""Remove token from vault."""
self.vault.pop(token, None)
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import os
class EncryptedStorage:
"""Encrypt data at rest using AES-256-GCM."""
def __init__(self, encryption_key):
"""Initialize with 256-bit key."""
self.key = encryption_key # Must be 32 bytes
def encrypt(self, plaintext):
"""Encrypt data."""
# Generate random nonce
nonce = os.urandom(12)
# Encrypt
aesgcm = AESGCM(self.key)
ciphertext = aesgcm.encrypt(nonce, plaintext.encode(), None)
# Return nonce + ciphertext
return nonce + ciphertext
def decrypt(self, encrypted_data):
"""Decrypt data."""
# Extract nonce and ciphertext
nonce = encrypted_data[:12]
ciphertext = encrypted_data[12:]
# Decrypt
aesgcm = AESGCM(self.key)
plaintext = aesgcm.decrypt(nonce, ciphertext, None)
return plaintext.decode()
# Usage
storage = EncryptedStorage(os.urandom(32))
encrypted_pan = storage.encrypt("4242424242424242")
# Store encrypted_pan in database
# Always use TLS 1.2 or higher
# Flask/Django example
app.config['SESSION_COOKIE_SECURE'] = True # HTTPS only
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SAMESITE'] = 'Strict'
# Enforce HTTPS
from flask_talisman import Talisman
Talisman(app, force_https=True)
from functools import wraps
from flask import session
def require_pci_access(f):
"""Decorator to restrict access to cardholder data."""
@wraps(f)
def decorated_function(*args, **kwargs):
user = session.get('user')
# Check if user has PCI access role
if not user or 'pci_access' not in user.get('roles', []):
return {'error': 'Unauthorized access to cardholder data'}, 403
# Log access attempt
audit_log(
user=user['id'],
action='access_cardholder_data',
resource=f.__name__
)
return f(*args, **kwargs)
return decorated_function
@app.route('/api/payment-methods')
@require_pci_access
def get_payment_methods():
"""Retrieve payment methods (restricted access)."""
# Only accessible to users with pci_access role
pass
import logging
from datetime import datetime
class PCIAuditLogger:
"""PCI-compliant audit logging."""
def __init__(self):
self.logger = logging.getLogger('pci_audit')
# Configure to write to secure, append-only log
def log_access(self, user_id, resource, action, result):
"""Log access to cardholder data."""
entry = {
'timestamp': datetime.utcnow().isoformat(),
'user_id': user_id,
'resource': resource,
'action': action,
'result': result,
'ip_address': request.remote_addr
}
self.logger.info(json.dumps(entry))
def log_authentication(self, user_id, success, method):
"""Log authentication attempt."""
entry = {
'timestamp': datetime.utcnow().isoformat(),
'user_id': user_id,
'event': 'authentication',
'success': success,
'method': method,
'ip_address': request.remote_addr
}
self.logger.info(json.dumps(entry))
# Usage
audit = PCIAuditLogger()
audit.log_access(user_id=123, resource='payment_methods', action='read', result='success')
import re
def validate_card_number(card_number):
"""Validate card number format (Luhn algorithm)."""
# Remove spaces and dashes
card_number = re.sub(r'[\s-]', '', card_number)
# Check if all digits
if not card_number.isdigit():
return False
# Luhn algorithm
def luhn_checksum(card_num):
def digits_of(n):
return [int(d) for d in str(n)]
digits = digits_of(card_num)
odd_digits = digits[-1::-2]
even_digits = digits[-2::-2]
checksum = sum(odd_digits)
for d in even_digits:
checksum += sum(digits_of(d * 2))
return checksum % 10
return luhn_checksum(card_number) == 0
def sanitize_input(user_input):
"""Sanitize user input to prevent injection."""
# Remove special characters
# Validate against expected format
# Escape for database queries
pass
PCI_COMPLIANCE_CHECKLIST = {
'network_security': [
'Firewall configured and maintained',
'No vendor default passwords',
'Network segmentation implemented'
],
'data_protection': [
'No storage of CVV, track data, or PIN',
'PAN encrypted when stored',
'PAN masked when displayed',
'Encryption keys properly managed'
],
'vulnerability_management': [
'Anti-virus installed and updated',
'Secure development practices',
'Regular security patches',
'Vulnerability scanning performed'
],
'access_control': [
'Access restricted by role',
'Unique IDs for all users',
'Multi-factor authentication',
'Physical security measures'
],
'monitoring': [
'Audit logs enabled',
'Log review process',
'File integrity monitoring',
'Regular security testing'
],
'policy': [
'Security policy documented',
'Risk assessment performed',
'Security awareness training',
'Incident response plan'
]
}
By minimizing systems that touch card data, you reduce compliance burden significantly.
Weekly Installs
89
Repository
GitHub Stars
27.4K
First Seen
Jan 28, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykWarn
Installed on
opencode86
gemini-cli85
cursor85
claude-code84
github-copilot82
codex82
Lark Mail CLI 使用指南:邮件管理、安全规则与自动化工作流
37,000 周安装
GitHub Copilot 技能模板制作指南 - 创建自定义 Agent Skills 分步教程
8,200 周安装
ImageMagick图像处理技能:批量调整大小、格式转换与元数据提取
8,200 周安装
GitHub Actions 工作流规范创建指南:AI优化模板与CI/CD流程设计
8,200 周安装
GitHub Copilot SDK 官方开发包 - 在应用中嵌入AI智能体工作流(Python/TypeScript/Go/.NET)
8,200 周安装
AI提示工程安全审查与改进指南 - 负责任AI开发、偏见检测与提示优化
8,200 周安装
GitHub Copilot 提示词构建器 - 专业提示工程工具,提升AI编程效率
8,300 周安装