npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@cdkey-system/sdk

v2.0.2

Published

授权码系统客户端SDK - 用于解密和验证授权码,包含共享类型和工具函数

Readme

CdkeySDK

授权码系统客户端SDK,支持加密、解密和验证授权码。完全兼容浏览器、Node.js 和服务端渲染框架(如 Next.js)。

🚀 新版本特性 (v2.0.0)

  • 重构架构: 更清晰的代码结构和职责分离
  • 🔧 核心模块: 独立的验证器和客户端类
  • 📦 类型安全: 完整的TypeScript类型定义
  • 🌐 跨平台: 支持Node.js、浏览器、Next.js SSR
  • 性能优化: 异步处理和缓存机制
  • 🛡️ 向后兼容: 保留旧API接口

特性

  • 🌍 通用兼容: 支持 Node.js、浏览器、Next.js SSR、Web Workers
  • 📦 开箱即用: 内置所有必要的 polyfill,无需额外配置
  • 🔒 安全加密: 支持 RSA 加密和多种加密算法
  • 📱 设备识别: 内置设备指纹识别功能
  • 🎯 TypeScript: 完整的类型定义支持
  • 🚀 高性能: 优化的打包和压缩算法
  • 时间验证: 防止时间篡改攻击,确保验证安全性

📖 快速开始

安装

npm install @cdkey-system/sdk
# 或
yarn add @cdkey-system/sdk
# 或
pnpm add @cdkey-system/sdk

基础使用

import { CdkeyClient } from '@cdkey-system/sdk';

const client = new CdkeyClient({
  debug: true,
  whitelistUrls: ['/health', '/api/public/*']
});

// 验证授权码
const result = client.validate(code, deviceId);
if (result.valid) {
  console.log('验证成功:', result.data);
}

获取设备信息

// 异步获取设备信息
const deviceInfo = await client.getDeviceInfo();
console.log('设备ID:', deviceInfo.id);
console.log('设备类型:', deviceInfo.type);

时间验证

SDK 支持时间验证功能,防止客户端时间篡改攻击:

import { EnhancedCdkeyValidator } from '@cdkey-system/sdk';

const validator = new EnhancedCdkeyValidator({
  publicKeyPem: 'your-public-key',
  timeValidation: {
    serviceUrl: 'http://localhost:3001/api/v1',
    timeout: 5000,
    retryCount: 3
  },
  enforceTimeValidation: true, // 强制时间验证
  timeValidationFailure: 'reject' // 时间验证失败时拒绝
});

// 增强验证(包含时间验证)
const result = await validator.validateCdkeyEnhanced(code, deviceId);

if (result.valid) {
  console.log('验证成功:', result.data);
} else {
  console.error('验证失败:', result.message);
  if (result.warnings) {
    console.warn('警告:', result.warnings);
  }
}

重要: 当客户端时间与服务器时间差异超过5分钟时,SDK 会直接拒绝验证,无论配置如何,以确保安全性。

NestJS集成

import { CdkeyClient } from '@cdkey-system/sdk';

const client = new CdkeyClient(config);

const guard = client.createNestGuard(
  (req) => req.headers.authorization,
  (req) => req.headers['device-id']
);

// 在NestJS中使用
app.use(guard);

安装

npm install @cdkey-system/sdk
# 或
yarn add @cdkey-system/sdk
# 或
pnpm add @cdkey-system/sdk

快速开始

Node.js 环境

import { CdkeyClient } from '@cdkey-system/sdk';

const client = new CdkeyClient({
  baseURL: 'https://your-api-server.com/api',
  publicKey: 'your-rsa-public-key'
});

// 验证授权码
async function validateCdkey() {
  try {
    const result = await client.validate('your-cdkey-here');
    console.log('验证结果:', result);
  } catch (error) {
    console.error('验证失败:', error);
  }
}

浏览器环境

<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/@cdkey-system/sdk/dist/cdkey-sdk.umd.min.js"></script>
</head>
<body>
  <script>
    const client = new CdkeySDK.CdkeyClient({
      baseURL: 'https://your-api-server.com/api',
      publicKey: 'your-rsa-public-key'
    });
    
    client.validate('your-cdkey-here')
      .then(result => console.log('验证结果:', result))
      .catch(error => console.error('验证失败:', error));
  </script>
</body>
</html>

ES 模块 (现代浏览器)

import { CdkeyClient } from 'https://unpkg.com/@cdkey-system/sdk/dist/index.esm.js';

const client = new CdkeyClient({
  baseURL: 'https://your-api-server.com/api',
  publicKey: 'your-rsa-public-key'
});

Next.js 应用

// pages/api/validate-cdkey.ts (API 路由)
import { CdkeyClient } from '@cdkey-system/sdk';

const client = new CdkeyClient({
  baseURL: process.env.CDKEY_API_URL,
  publicKey: process.env.RSA_PUBLIC_KEY
});

export default async function handler(req, res) {
  if (req.method === 'POST') {
    try {
      const { cdkey } = req.body;
      const result = await client.validate(cdkey);
      res.status(200).json(result);
    } catch (error) {
      res.status(400).json({ error: error.message });
    }
  }
}
// components/CdkeyValidator.tsx (客户端组件)
'use client';

import { CdkeyClient } from '@cdkey-system/sdk';
import { useState } from 'react';

export default function CdkeyValidator() {
  const [cdkey, setCdkey] = useState('');
  const [result, setResult] = useState(null);

  const validateCdkey = async () => {
    try {
      // 通过API路由验证(推荐)
      const response = await fetch('/api/validate-cdkey', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ cdkey })
      });
      const result = await response.json();
      setResult(result);
    } catch (error) {
      console.error('验证失败:', error);
    }
  };

  return (
    <div>
      <input 
        value={cdkey} 
        onChange={(e) => setCdkey(e.target.value)}
        placeholder="输入授权码"
      />
      <button onClick={validateCdkey}>验证</button>
      {result && <pre>{JSON.stringify(result, null, 2)}</pre>}
    </div>
  );
}

Vue.js 应用

<template>
  <div>
    <input 
      v-model="cdkey" 
      placeholder="输入授权码"
    />
    <button @click="validateCdkey">验证</button>
    <pre v-if="result">{{ JSON.stringify(result, null, 2) }}</pre>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { CdkeyClient } from '@cdkey-system/sdk';

const cdkey = ref('');
const result = ref(null);

const client = new CdkeyClient({
  baseURL: 'https://your-api-server.com/api',
  publicKey: 'your-rsa-public-key'
});

const validateCdkey = async () => {
  try {
    result.value = await client.validate(cdkey.value);
  } catch (error) {
    console.error('验证失败:', error);
  }
};
</script>

API 参考

CdkeyClient

主要的 SDK 客户端类。

interface CdkeyClientConfig {
  baseURL: string;          // API 服务器地址
  publicKey: string;        // RSA 公钥
  timeout?: number;         // 请求超时时间(毫秒)
  headers?: Record<string, string>; // 自定义请求头
}

class CdkeyClient {
  constructor(config: CdkeyClientConfig);
  
  // 验证授权码
  async validate(cdkey: string): Promise<CdkeyValidationResult>;
  
  // 获取设备指纹
  getDeviceFingerprint(): string;
  
  // 获取环境信息
  getEnvironmentInfo(): EnvironmentInfo;
}

工具函数

// 设备工具
import { DeviceUtils } from '@cdkey-system/sdk';
const fingerprint = DeviceUtils.generateFingerprint();

// 加密工具
import { EncryptionUtils } from '@cdkey-system/sdk';
const encrypted = EncryptionUtils.encrypt(data, publicKey);

// 环境检测
import { EnvironmentUtils } from '@cdkey-system/sdk';
const isServer = EnvironmentUtils.isSSR();
const isBrowser = EnvironmentUtils.isBrowser();

环境兼容性

支持的环境

  • ✅ Node.js 16+
  • ✅ 现代浏览器 (Chrome 88+, Firefox 85+, Safari 14+)
  • ✅ Next.js (App Router 和 Pages Router)
  • ✅ Nuxt.js 3+
  • ✅ Vite
  • ✅ Webpack 5+
  • ✅ Web Workers
  • ✅ Electron

服务端渲染 (SSR)

SDK 完全支持服务端渲染,会自动检测环境并使用适当的 polyfill:

// 这在服务端和客户端都能正常工作
import { CdkeyClient } from '@cdkey-system/sdk';

const client = new CdkeyClient({
  baseURL: process.env.CDKEY_API_URL || 'https://api.example.com',
  publicKey: process.env.RSA_PUBLIC_KEY
});

Webpack 配置

SDK 内置了所有必要的 polyfill,但如果你遇到问题,可以在 next.config.js 中添加:

// next.config.js
module.exports = {
  webpack: (config) => {
    config.resolve.fallback = {
      ...config.resolve.fallback,
      fs: false,
      net: false,
      tls: false,
    };
    return config;
  },
};

错误处理

import { CdkeyClient, CdkeyValidationError } from '@cdkey-system/sdk';

try {
  const result = await client.validate(cdkey);
} catch (error) {
  if (error instanceof CdkeyValidationError) {
    console.error('验证错误:', error.message);
  } else {
    console.error('网络或系统错误:', error);
  }
}

最佳实践

1. 环境变量管理

// 使用环境变量存储敏感信息
const client = new CdkeyClient({
  baseURL: process.env.NEXT_PUBLIC_CDKEY_API_URL,
  publicKey: process.env.NEXT_PUBLIC_RSA_PUBLIC_KEY
});

2. 错误边界

// React 错误边界
class CdkeyErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    console.error('CdkeySDK Error:', error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return <h1>授权码验证服务暂时不可用</h1>;
    }

    return this.props.children;
  }
}

3. 性能优化

// 使用缓存避免重复验证
const validateCache = new Map();

async function validateWithCache(cdkey: string) {
  if (validateCache.has(cdkey)) {
    return validateCache.get(cdkey);
  }
  
  const result = await client.validate(cdkey);
  validateCache.set(cdkey, result);
  
  // 5分钟后清除缓存
  setTimeout(() => validateCache.delete(cdkey), 5 * 60 * 1000);
  
  return result;
}

许可证

MIT License

支持

如有问题或建议,请提交 Issue 或联系开发团队。