UNPKG

@shard-auth/client

Version:

Next-generation API authentication without secret keys - MPC-based authentication with FROST threshold signatures

163 lines 6.4 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.ShardAuthClient = void 0; const errors_1 = require("./errors"); const signature_client_1 = require("../api/signature-client"); const utils_1 = require("./utils"); const crypto = __importStar(require("crypto")); // HttpResponseはtypes.tsからインポート済み /** * Shard-Auth認証を使用するHTTPクライアント * * @example * ```typescript * const client = new ShardAuthClient({ * shareStorage: new SecureStorage('./share.key'), * apiEndpoint: 'https://api.example.com', * signatureEndpoint: 'https://auth.example.com' * }); * * const response = await client.get('/api/v1/users'); * ``` */ class ShardAuthClient { shareStorage; apiEndpoint; signatureEndpoint; timeout; httpClient; retryPolicy; signatureClient; share; destroyed = false; constructor(options) { this.shareStorage = options.shareStorage; this.apiEndpoint = options.apiEndpoint; this.signatureEndpoint = options.signatureEndpoint; this.timeout = options.timeout || 30000; this.httpClient = options.httpClient || require('axios').create(); this.retryPolicy = options.retryPolicy || { maxRetries: 3, initialDelay: 1000, maxDelay: 30000, backoffMultiplier: 2 }; } async ensureInitialized() { if (!this.share) { this.share = await this.shareStorage.loadShare(); this.signatureClient = new signature_client_1.SignatureAPIClient(this.share, this.httpClient); } } async signRequest(method, path, body) { await this.ensureInitialized(); const requestDetails = { method: method.toUpperCase(), path, bodyHash: body ? Buffer.from(crypto.createHash('sha256').update(JSON.stringify(body)).digest('hex'), 'hex') : Buffer.alloc(0), timestamp: new Date().toISOString() }; // リトライロジック let lastError; for (let attempt = 0; attempt <= this.retryPolicy.maxRetries; attempt++) { try { // 署名セッション開始(タイムアウト付き) const sessionResponse = await (0, utils_1.withTimeout)(this.signatureClient.startSignatureSession(requestDetails, this.signatureEndpoint), this.timeout, new errors_1.SignatureSessionError('Signature session timeout')); // 署名完了(タイムアウト付き) const completeResponse = await (0, utils_1.withTimeout)(this.signatureClient.completeSignature(sessionResponse.sessionId, requestDetails, Buffer.from('dummy_public_key'), // 最小実装のためダミー this.signatureEndpoint), this.timeout, new errors_1.SignatureSessionError('Signature completion timeout')); return completeResponse.authorizationHeader; } catch (error) { lastError = error; // リトライ可能なエラーかチェック if (attempt < this.retryPolicy.maxRetries) { const delay = (0, utils_1.calculateBackoff)(attempt, this.retryPolicy.initialDelay, this.retryPolicy.maxDelay, this.retryPolicy.backoffMultiplier); await new Promise(resolve => setTimeout(resolve, delay)); continue; } } } throw new errors_1.SignatureSessionError(`Failed to sign request after ${this.retryPolicy.maxRetries} retries: ${lastError?.message}`); } async makeRequest(method, path, body) { const authHeader = await this.signRequest(method, path, body); const response = { data: {}, headers: { 'Authorization': authHeader } }; return response; } async get(path) { return this.makeRequest('GET', path); } async post(path, body) { return this.makeRequest('POST', path, body); } async put(path, body) { return this.makeRequest('PUT', path, body); } async delete(path) { return this.makeRequest('DELETE', path); } async patch(path, body) { return this.makeRequest('PATCH', path, body); } async head(path) { return this.makeRequest('HEAD', path); } async options(path) { return this.makeRequest('OPTIONS', path); } destroy() { // メモリ上のシェアをゼロ化 if (this.share) { (0, utils_1.secureZeroMemory)(this.share.share); (0, utils_1.secureZeroMemory)(this.share.publicKeyShare); (0, utils_1.secureZeroMemory)(this.share.commitment); } this.share = undefined; this.signatureClient = undefined; this.destroyed = true; } isDestroyed() { return this.destroyed; } } exports.ShardAuthClient = ShardAuthClient; //# sourceMappingURL=shard-auth-client.js.map