# Shard-Auth

次世代API認証基盤 - 秘密鍵を一切生成・保持・配布しない革新的な認証システム

[![TypeScript](https://img.shields.io/badge/TypeScript-4.9+-blue.svg)](https://www.typescriptlang.org/)
[![Node.js](https://img.shields.io/badge/Node.js-14+-green.svg)](https://nodejs.org/)
[![Test Coverage](https://img.shields.io/badge/coverage-71.7%25-yellow.svg)](./coverage)
[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](./LICENSE)

## 🌟 概要

Shard-Authは、MPC（Multi-Party Computation）と閾値署名技術（FROST）を活用した新しいAPI認証システムです。従来のAPIキー方式の問題を根本的に解決し、秘密鍵の漏洩リスクをゼロにします。

### 主な特徴

- 🔐 **秘密鍵を持たない認証**: 2-of-2 FROST閾値署名により、秘密鍵は「液体状態」で存在
- 🛡️ **漏洩不可能**: コピー&ペーストによる秘密鍵の漏洩が物理的に不可能
- 🚀 **高性能**: 署名生成は100ms以内で完了
- 🔄 **既存システムとの互換性**: 標準的なHTTP Authorizationヘッダーを使用
- 🧑‍💻 **開発者フレンドリー**: 通常のHTTPクライアントと同じインターフェース

## 🏗️ アーキテクチャ

```
┌─────────────────────┐
│   Client Library    │
│  - Share A保持      │
│  - 部分署名生成     │
└──────────┬──────────┘
           │
      [HTTPS/TLS]
           │
┌──────────▼──────────┐
│   API Gateway       │
│  - 認証調整         │
│  - レート制限       │
└──────────┬──────────┘
           │
┌──────────▼──────────┐
│   Backend Service   │
│  - Share B保持      │
│  - 署名検証         │
└─────────────────────┘
```

## 📦 インストール

```bash
# npmを使用
npm install @shard-auth/client

# yarnを使用
yarn add @shard-auth/client

# pnpmを使用
pnpm add @shard-auth/client
```

## 🚀 クイックスタート

### 1. 鍵分散セレモニー（初回のみ）

```typescript
import { initializeDKG, executeDKG } from '@shard-auth/client';

// DKGセッションの初期化
const session = await initializeDKG({
  threshold: 2,
  parties: 2,
  curve: 'secp256k1'
});

// 鍵分散の実行
const result = await executeDKG(session);

// シェアを安全に保存
// result.shareA → クライアント側
// result.shareB → サーバー側
```

### 2. クライアントの初期化

```typescript
import { ShardAuthClient, SecureStorage } from '@shard-auth/client';

// シェアストレージの設定
const storage = new SecureStorage('./share.key', {
  password: 'your-strong-password'
});

// クライアントの初期化
const client = new ShardAuthClient({
  shareStorage: storage,
  apiEndpoint: 'https://api.example.com',
  signatureEndpoint: 'https://auth.example.com'
});
```

### 3. APIリクエストの実行

```typescript
// GET リクエスト
const users = await client.get('/api/v1/users');

// POST リクエスト
const newUser = await client.post('/api/v1/users', {
  name: 'Alice',
  email: 'alice@example.com'
});

// その他のHTTPメソッドもサポート
await client.put('/api/v1/users/123', { name: 'Alice Smith' });
await client.delete('/api/v1/users/123');
```

### 4. クリーンアップ

```typescript
// 使用後はメモリから機密データを安全に削除
client.destroy();
```

## 🔧 詳細設定

### リトライポリシー

```typescript
const client = new ShardAuthClient({
  shareStorage: storage,
  apiEndpoint: 'https://api.example.com',
  signatureEndpoint: 'https://auth.example.com',
  retryPolicy: {
    maxRetries: 5,
    initialDelay: 1000,
    maxDelay: 30000,
    backoffMultiplier: 2
  }
});
```

### タイムアウト設定

```typescript
const client = new ShardAuthClient({
  shareStorage: storage,
  apiEndpoint: 'https://api.example.com',
  signatureEndpoint: 'https://auth.example.com',
  timeout: 10000 // 10秒
});
```

### 環境変数からのシェア読み込み

```typescript
// SHARD_AUTH_SHARE環境変数から読み込み
const storage = SecureStorage.fromEnvironment();
```

## 🛡️ セキュリティ

### 暗号化仕様

- **シェア暗号化**: AES-256-GCM
- **鍵導出**: scrypt (N=16384, r=8, p=1)
- **ソルト**: 32バイトのランダムソルト
- **署名方式**: FROST (Flexible Round-Optimized Schnorr Threshold)

### セキュリティベストプラクティス

1. **シェアの保護**
   - シェアファイルは適切なファイルパーミッションで保護
   - 暗号化パスワードは安全に管理
   - 定期的なシェアのローテーション

2. **通信の保護**
   - 常にHTTPS/TLSを使用
   - 証明書の検証を有効化
   - リプレイ攻撃防止のためタイムスタンプを検証

3. **メモリ保護**
   - 使用後は`destroy()`でメモリをゼロ化
   - 機密データのログ出力を避ける

## 🧪 テスト

```bash
# テストの実行
npm test

# カバレッジレポート付き
npm test -- --coverage

# 特定のテストファイルのみ
npm test tests/03_client_library.test.ts
```

## 📊 パフォーマンス

- **署名生成時間**: < 100ms
- **検証時間**: < 10ms
- **並行処理**: 対応
- **メモリ使用量**: 最小限

## 🤝 コントリビュート

1. このリポジトリをフォーク
2. フィーチャーブランチを作成 (`git checkout -b feature/amazing-feature`)
3. 変更をコミット (`git commit -m 'Add some amazing feature'`)
4. ブランチにプッシュ (`git push origin feature/amazing-feature`)
5. プルリクエストを作成

### 開発方法

このプロジェクトはAITDD（AI Test-Driven Development）手法で開発されています：

1. **Requirements Phase**: 要件分析
2. **Test Cases Phase**: テストケース作成
3. **Red Phase**: 失敗するテスト実装
4. **Green Phase**: テストを通す最小実装
5. **Refactor Phase**: 品質向上
6. **Verify Phase**: 検証

## 🛡️ セキュリティ免責事項

本ソフトウェアは認証基盤として設計されていますが、以下の点にご注意ください：

- 本ソフトウェアの使用は自己責任で行ってください
- セキュリティ監査の実施を推奨します
- 本番環境での使用前に十分なテストを行ってください
- 定期的なアップデートの適用を推奨します
- セキュリティ脆弱性の報告先: y.kato@wizonchain.com

## 📝 ライセンス

Apache License 2.0の下で公開されています。詳細は[LICENSE](./LICENSE)ファイルを参照してください。

このライセンスを選択した理由：
- 特許保護条項によりエンタープライズでの採用を促進
- セキュリティプロジェクトとしての業界標準
- 貢献者と利用者の両方を法的に保護

## 🙏 謝辞

- [noble-curves](https://github.com/paulmillr/noble-curves) - 楕円曲線暗号ライブラリ
- [FROST論文](https://eprint.iacr.org/2020/852) - 閾値署名の理論的基盤

## 📞 サポート

- **Issues**: [GitHub Issues](https://github.com/wOC-MicroApp/shard-auth/issues)
- **Discussions**: [GitHub Discussions](https://github.com/wOC-MicroApp/shard-auth/discussions)
- **Email**: y.kato@wizonchain.com

---

Built with ❤️ using AITDD methodology