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 🙏

© 2025 – Pkg Stats / Ryan Hefner

vitepress-plugin-coze-oauth

v1.0.0

Published

Coze OAuth插件,为Vitepress提供OAuth认证功能

Readme

Coze OAuth Plugin for Vitepress

这是一个为Vitepress提供Coze OAuth认证功能的插件,支持PKCE流程。

工作原理

1、当用户访问需要授权的页面时,getAccessTokenInternal 会检查是否有有效的 token 2、如果没有有效 token,会重定向到授权页面,并将当前页面 URL 作为 redirect_uri 参数传递 3、用户完成授权后,回调处理会将用户重定向到 /coze/get-token 路由,并携带 token 信息 4、/coze/get-token 路由会更新全局 OAuth 状态,然后直接重定向回原始页面,并在 URL 中携带 token 信息 5、当原始页面重新加载时,getAccessTokenInternal 函数会从 URL 参数中读取 token 信息,更新 oauthState,并清除 URL 中的 token 参数 6、宿主项目可以将 token 保存到 localStorage

特性

  • 完整的TypeScript支持,提供类型定义
  • 同时支持CommonJS和ES Module两种模块格式
  • 自动处理OAuth认证流程
  • 支持令牌自动刷新
  • 内置中间件处理认证路由

安装

npm install vitepress-plugin-coze-oauth

使用方法

方法一:作为Vitepress插件使用

在Vitepress中配置

// .vitepress/config.ts
import { defineConfig } from 'vitepress'
import { createCozeOAuthPlugin } from 'vitepress-plugin-coze-oauth'

// 创建Coze OAuth插件实例
const cozeOAuthPlugin = createCozeOAuthPlugin({
  client_type: 'web',
  client_id: 'your-client-id',
  coze_www_base: 'https://www.coze.com',
  coze_api_base: 'https://api.coze.com',
  redirectUri: 'http://localhost:3000/coze/callback'
})

export default defineConfig({
  // 其他Vitepress配置...
  
  // 添加插件到vite配置
  vite: {
    plugins: [cozeOAuthPlugin]
  },
  
  // 将插件实例添加到主题配置中,以便在组件中访问
  themeConfig: {
    // 其他主题配置...
    cozeOAuthPlugin: cozeOAuthPlugin
  }
})

在组件中使用

<script setup>
import { useData } from 'vitepress'
import { ref, onMounted } from 'vue'

const { theme } = useData()
const accessToken = ref(null)

onMounted(async () => {
  // 直接通过theme访问插件实例
  accessToken.value = await theme.value.cozeOAuthPlugin.getAccessToken(true, true)
})

// 刷新令牌
async function refreshToken() {
  try {
    accessToken.value = await theme.value.cozeOAuthPlugin.refreshToken()
  } catch (error) {
    console.error('刷新令牌失败:', error)
  }
}
</script>

<template>
  <div>
    <p v-if="accessToken">已登录</p>
    <p v-else>未登录</p>
    <button @click="refreshToken">刷新令牌</button>
  </div>
</template>

方法二:在VitePress中注册插件但直接使用导出的函数

您可以在VitePress配置中注册插件以启用OAuth路由处理,但在组件中直接使用导出的函数,而不是通过themeConfig访问插件实例:

// .vitepress/config.ts
import { defineConfig } from 'vitepress'
import { createCozeOAuthPlugin } from 'vitepress-plugin-coze-oauth'

// 创建Coze OAuth插件实例
const cozeOAuthPlugin = createCozeOAuthPlugin({
  client_type: 'web',
  client_id: 'your-client-id',
  coze_www_base: 'https://www.coze.com',
  coze_api_base: 'https://api.coze.com',
  redirectUri: 'http://localhost:3000/coze/callback'
})

export default defineConfig({
  // 其他Vitepress配置...
  
  // 添加插件到vite配置,但不添加到themeConfig
  vite: {
    plugins: [cozeOAuthPlugin]
  }
})

然后在组件中直接使用导出的函数:

<script setup>
import { ref, onMounted } from 'vue'
import { getAccessToken, refreshToken } from 'vitepress-plugin-coze-oauth'

const accessToken = ref(null)
const config = {
  client_type: 'web',
  client_id: 'your-client-id',
  coze_www_base: 'https://www.coze.com',
  coze_api_base: 'https://api.coze.com',
  redirectUri: 'http://localhost:3000/coze/callback'
}

onMounted(async () => {
  // 直接使用导出的函数,不依赖theme.cozeOAuthPlugin
  accessToken.value = await getAccessToken(config, true, true)
})

// 刷新令牌
async function refreshAccessToken() {
  try {
    // refreshToken会自动更新内部的accessToken
    await refreshToken(config)
    
    // 由于refreshToken已经更新了内部的accessToken
    // 我们可以直接获取最新的值
    accessToken.value = await getAccessToken(config, false, false)
  } catch (error) {
    console.error('刷新令牌失败:', error)
  }
}
</script>

方法三:在任何JavaScript/TypeScript项目中使用

除了在VitePress中使用外,本库还提供了直接使用的函数,可以在任何JavaScript/TypeScript项目中使用:

// 导入函数和类型
import { getAccessToken, refreshToken } from 'vitepress-plugin-coze-oauth'
import type { CozeOAuthPluginConfig } from 'vitepress-plugin-coze-oauth'

// 定义配置
const config: CozeOAuthPluginConfig = {
  client_type: 'web',
  client_id: 'your-client-id',
  coze_www_base: 'https://www.coze.com',
  coze_api_base: 'https://api.coze.com',
  redirectUri: 'http://localhost:3000/coze/callback'
}

// 异步函数中使用
async function authenticate() {
  try {
    // 获取访问令牌(支持自动刷新和重定向)
    const token = await getAccessToken(config, true, false)
    
    // 手动刷新令牌
    const newToken = await refreshToken(config)
    console.log('刷新后的令牌:', newToken)
  } catch (error) {
    console.error('认证失败:', error)
  }
}

authenticate()

类型定义

本库提供完整的TypeScript类型定义,可以通过导入获取:

import type {
  CozeOAuthPluginConfig,  // 插件配置类型
  OAuthToken,             // OAuth令牌类型
  OAuthState              // OAuth状态类型
} from 'vitepress-plugin-coze-oauth'

与Coze WebChatClient集成

本库可以与Coze WebChatClient SDK无缝集成,提供OAuth认证和令牌刷新功能:

<script setup>
import { ref, onMounted } from "vue";
import { useData } from "vitepress";
import { getAccessToken, refreshToken } from "vitepress-plugin-coze-oauth";

// 从VitePress主题配置中获取OAuth配置
const { theme } = useData();
const accessToken = ref(null);
const config = {
  client_type: "web",
  client_id: "your-client-id", // 替换为您的client_id
  coze_www_base: "https://www.coze.com",
  coze_api_base: "https://api.coze.com",
  redirectUri: "http://localhost:3000/coze/callback"
};

// 初始化时获取访问令牌
onMounted(async () => {
  try {
    // 方法1: 如果使用了VitePress插件配置,可以直接从theme中获取
    if (theme.value.cozeOAuthPlugin) {
      accessToken.value = await theme.value.cozeOAuthPlugin.getAccessToken(true, true);
    } 
    // 方法2: 或者直接使用导出的函数
    else {
      accessToken.value = await getAccessToken(config, true, true);
    }
    
    // 加载Coze WebChatClient SDK
    loadCozeWebSDK();
  } catch (error) {
    console.error("获取访问令牌失败:", error);
  }
});

// 加载Coze WebChatClient SDK
function loadCozeWebSDK() {
  const sdkUrl = "https://sf-cdn.coze.com/obj/unpkg-va/flow-platform/chat-app-sdk/1.2.0-beta.6/libs/oversea/index.js"; 
  const externalScript = document.createElement("script");
  externalScript.src = sdkUrl;
  externalScript.type = "text/javascript";

  externalScript.onload = () => {
    if (window.CozeWebSDK && window.CozeWebSDK.WebChatClient) {
      initCozeWebChatClient();
    }
  };

  document.body.appendChild(externalScript);
}

// 初始化Coze WebChatClient
function initCozeWebChatClient() {
  new window.CozeWebSDK.WebChatClient({
    config: {
      bot_id: "your-bot-id", // 替换为您的bot_id
    },
    auth: {
      type: "token",
      token: accessToken.value, // 使用OAuth获取的访问令牌
      onRefreshToken: async () => {
        try {
          // 方法1: 如果使用了VitePress插件配置
          if (theme.value.cozeOAuthPlugin) {
            // 刷新令牌时,内部已经更新了accessToken
            // 直接获取最新的访问令牌
            return theme.value.cozeOAuthPlugin.access_token;
          } 
          // 方法2: 或者直接使用导出的函数
          else {
            // 刷新令牌后,需要重新获取访问令牌
            await refreshToken(config);
            // 获取最新的访问令牌
            accessToken.value = await getAccessToken(config, false, false);
            return accessToken.value;
          }
        } catch (error) {
          console.error("刷新令牌失败:", error);
          // 如果刷新失败,可以重定向到授权页面
          window.location.href = "/coze/auth";
          return null;
        }
      },
    },
    ui: {
      chatBot: {
        title: "博客问答助手",
        // 其他UI配置...
      }
    }
  });
}
</script>

完整示例请参考 src/examples/CozeWebChatIntegration.vue 文件。

开发

构建

npm run build

这将使用tsup构建CommonJS和ES Module两种格式的输出,并生成类型声明文件。

开发模式

npm run dev

这将启动监视模式,在文件更改时自动重新构建。

许可证

MIT