尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

在 Corsair 中接入 BunnyCDN:`@corsair-dev/bunnycdn` 插件完整指南

在 Corsair 中接入 BunnyCDN:`@corsair-dev/bunnycdn` 插件完整指南 在 Corsair 中接入 BunnyCDNcorsair-dev/bunnycdn插件完整指南【免费下载链接】corsairConnect your users to their apps项目地址: https://gitcode.com/GitHub_Trending/corsa/corsaircorsair-dev/bunnycdn是 Corsair 官方的 BunnyCDN 插件它把 BunnyCDN 的 CDN、存储、DNS、Shield 安全与 Magic Containers 等数百个 API 操作封装为带类型定义、输入校验与权限风险标注的标准化端点。通过本文你将掌握该插件的安装方式、认证模型、96 个可调用端点的完整清单与分组用法并深入理解其底层请求封装、错误处理与重试语义——可以直接在自己的多租户应用中接入并管理用户的 BunnyCDN 资源。插件是什么Corsair 生态中的 BunnyCDN 连接器Corsair 的核心定位是「Connect your users to their apps」——让 SaaS 应用安全地连接用户的第三方账号并代表用户调用其 API。每个外部服务对应一个独立的官方插件包corsair-dev/bunnycdn就是其中负责 BunnyCDN 的插件仓库目录为 packages/bunnycdn。插件在 package.json 中声明了自身约束以corsair 0.1.0与zod ^4.1.13作为 peerDependencies输出 ESM 构建产物./dist/index.js并提供dev-source入口便于开发期直接读取 TypeScript 源码。整体采用 Apache-2.0 许可。从 schema/index.ts 可以看到插件声明了version: 1.0.0且未定义任何持久化实体entities: {}——说明这是一个纯 API 代理型插件不依赖数据库实体建模所有状态都保存在 BunnyCDN 服务端。安装在已初始化 Corsair 的项目中使用 pnpm 安装pnpm add corsair-dev/bunnycdn安装完成后即可在代码中导入bunnycdn插件工厂函数并将其注册到 Corsair 应用。注册插件与配置项插件通过 index.ts 导出的bunnycdn()工厂函数创建调用时传入可选的BunnycdnPluginOptionsimport { bunnycdn } from corsair-dev/bunnycdn; const app createApp({ plugins: [ bunnycdn({ // 可选配置 }), ], });BunnycdnPluginOptions的完整字段如下对应 index.ts#L42-L48配置项类型说明authTypePickAuthapi_key认证类型默认且仅支持api_key见defaultAuthTypeindex.ts#L656keystring显式指定的 BunnyCDN API Key一旦提供端点调用时优先使用它而非租户存储的密钥hooks内部插件 hooks生命周期钩子透传给插件实例errorHandlersCorsairErrorHandler自定义错误处理器会与插件内置处理器合并同名键覆盖内置实现permissionsPluginPermissionsConfig按端点名配置的权限规则工厂函数内部会把authType缺省值补齐为api_key并组装出完整的插件对象包含id: bunnycdn、认证配置、端点注册表、端点元数据风险等级与描述、Zod 输入输出 schema、Webhook 表与错误处理器index.ts#L1071-L1105。API Key 的解析优先级插件通过keyBuilder决定每次调用使用哪个密钥index.ts#L1093-L1104优先级为插件选项中的显式options.key源码注释明确说明端点调用绝不能打到错误的 BunnyCDN 账号见 endpoints/helpers.ts#L20-L22当前租户存储的 API Key通过ctx.keys.get_api_key()读取兜底返回空字符串。这种「显式 Key 优先于租户 Key」的设计使得多租户场景下管理员可以固定使用服务商账号同时允许终端用户用自己的账号。认证机制API Key 与首次使用引导插件的认证类型只有一种API Key。README 明确说明Auth: API key. Corsair prompts your tenant for credentials on first use.即当租户终端用户第一次使用某个端点时Corsair 会引导该租户提供自己的 BunnyCDN API Key之后密钥被安全存储并自动用于后续调用。这与 Corsair 的 docs/concepts/api-key.mdx 所描述的通用 API Key 认证流程一致。从底层实现看插件在bunnycdnAuthConfig中把 API Key 的归属账号绑定到tenant_external_idindex.ts#L1051-L1055保证「谁的 Key 就代表谁」的租户隔离。实际的 HTTP 认证方式在 client.ts#L36-L47 中实现BunnyCDN 仅通过AccessKey请求头鉴权代码注释特别说明有意不发送Authorization: Bearer头避免混用协议导致鉴权失败。每个请求都携带AccessKey: api-key Content-Type: application/json端点全景96 个操作与风险分级README 的 Endpoints 章节列出了插件支持的全部 96 个操作。每个操作都有唯一的Operation ID格式为bunnycdn.api.分组.操作与三级风险标记read只读、write写入、destructive破坏性。这些风险级别同样定义在 index.ts#L658-L1049 的bunnycdnEndpointMeta中Corsair 会据此生成权限控制与操作确认策略。Pull ZoneCDN 加速域21 个操作Pull Zone 是 BunnyCDN 的核心概念——一个从源站拉取内容并缓存分发的 CDN 配置单元。Operation IDRiskDescriptionpullZone.listreadList pull zones with pagination and searchpullZone.getreadGet details of a specific pull zone by IDpullZone.createwriteCreate a new pull zonepullZone.updatewriteUpdate settings for a specific pull zonepullZone.removedestructiveDelete a specific pull zone by IDpullZone.purgeCachewritePurge cached content for a pull zone, optionally by cache tagpullZone.checkAvailabilityreadCheck whether a pull zone name is availablepullZone.addAllowedReferrerwriteAdd a hostname to the allowed referer listpullZone.removeAllowedReferrerwriteRemove a hostname from the allowed referer listpullZone.addBlockedIpwriteAdd an IP address to the blocked listpullZone.removeBlockedIpwriteRemove an IP address from the blocked listpullZone.addBlockedReferrerwriteAdd a blocked referer to a pull zonepullZone.removeBlockedReferrerwriteRemove a blocked referer from a pull zonepullZone.resetSecurityKeywriteReset the URL token security key for a pull zonepullZone.setForceSSLwriteEnable or disable Force SSL on a pull zone hostnamepullZone.edgeRuleUpsertwriteAdd or update an edge rule on a pull zonepullZone.edgeRuleDeletedestructiveDelete an edge rule from a pull zonepullZone.edgeRuleSetEnabledwriteEnable or disable an edge rule without deleting itpullZone.optimizerStatisticsreadRetrieve optimizer statistics for a pull zonepullZone.originShieldQueueStatisticsreadRetrieve origin shield queue statistics for a pull zonepullZone.safeHopStatisticsreadRetrieve SafeHop statistics for a pull zone源码层面的关键细节见 endpoints/pull-zone.ts 与 endpoints/types.ts分页与搜索pullZone.list支持page、perPageZod 约束为整数min(5)且max(1000)见 types.ts#L49-L54、search与includeCertificate查询参数输出兼容「数组」与「分页对象」Items/CurrentPage/TotalItems/HasMoreItems两种形态types.ts#L58-L68。创建时的字段优先级pullZone.create将Name、OriginUrl、Type作为显式字段与settings展开合并且显式字段永远覆盖settings中的同名属性防止误传pull-zone.ts#L53-L63。缓存清理pullZone.purgeCache允许通过可选cacheTag按缓存标签定向清理不传则全量清空pull-zone.ts#L85-L92。Edge RulesedgeRuleUpsert走/pullzone/{id}/edgerules/addOrUpdate实现「存在即更新、不存在即新增」edgeRuleSetEnabled可在不删除规则的前提下启停规则。安全控制resetSecurityKey可选传入新securityKey不传则由 BunnyCDN 生成setForceSSL针对单个主机名启用/禁用强制 HTTPS。统计optimizerStatistics、originShieldQueueStatistics、safeHopStatistics均接受dateFrom、dateTo、hourly时间范围参数。Shield安全防护域39 个操作Shield 是 BunnyCDN 的安全产品线覆盖 WAF、限流、Bot 检测、上传扫描、访问控制列表与安全指标。插件为此提供了 39 个操作是端点数量最多的分组Operation IDRiskDescriptionshield.zonesListreadList all shield zonesshield.zoneGetreadGet a shield zone configuration by IDshield.zoneGetByPullZonereadGet the shield zone configuration for a pull zoneshield.zonesPullZoneMappingreadGet the mapping between shield zones and pull zonesshield.zoneUpdatewriteUpdate a shield zone configurationshield.rateLimitsListreadList rate limit rules for a shield zoneshield.rateLimitGetreadGet a shield rate limit rule by IDshield.rateLimitCreatewriteCreate a shield rate limit ruleshield.rateLimitUpdatewriteUpdate a shield rate limit ruleshield.rateLimitDeletedestructiveDelete a shield rate limit ruleshield.metricsOverviewreadGet the security metrics overview for a shield zoneshield.metricsOverviewDetailedreadGet detailed security metrics for a shield zone over a time rangeshield.metricsRateLimitreadGet metrics for a specific shield rate limitshield.metricsRateLimitsreadGet aggregated rate limit metrics for a shield zoneshield.metricsBotDetectionreadGet bot detection metrics for a shield zoneshield.metricsUploadScanningreadGet upload scanning metrics for a shield zoneshield.metricsWafRulereadGet metrics for a specific WAF ruleshield.eventLogsreadGet shield event logs for a zone and date with continuation tokenshield.promoStatereadGet the shield promotional state for the accountshield.ddosEnumsreadList available Shield DDoS configuration valuesshield.botDetectionGetreadGet the bot detection configuration for a shield zoneshield.botDetectionUpdatewriteUpdate the bot detection configuration for a shield zoneshield.uploadScanningGetreadGet the upload scanning configuration for a shield zoneshield.uploadScanningUpdatewriteUpdate the upload scanning configuration for a shield zoneshield.accessListsListreadList access lists for a shield zoneshield.accessListGetreadGet a custom access list by IDshield.accessListCreatewriteCreate a custom access list in a shield zoneshield.accessListUpdatewriteUpdate a custom access list in a shield zoneshield.accessListConfigUpdatewriteUpdate an access list configuration action or enabled stateshield.accessListEnumsreadList available access list configuration valuesshield.wafCustomRulesListreadList custom WAF rules for a shield zoneshield.wafCustomRuleGetreadGet a custom WAF rule by IDshield.wafEngineConfigreadGet the Shield WAF engine configurationshield.wafEnumsreadList available Shield WAF configuration valuesshield.wafProfilesreadList available WAF security profilesshield.wafRulesPlanSegmentationreadList WAF rules segmented by subscription planshield.wafRulesReviewTriggeredreadList triggered WAF rules awaiting reviewshield.wafRulesByZonereadList WAF rules for a shield zoneshield.wafRulesReviewTriggeredPostwriteApply an action to a triggered WAF rule实现提示shield.metrics*、shield.botDetectionGet、shield.uploadScanningGet、shield.accessListsList、shield.accessListEnums等多个端点复用shieldZoneId作为输入、以shieldMetricsDetailed作为输出 schema见 index.ts#L488-L566意味着它们都以 Shield Zone ID 为入口而wafEngineConfig、wafEnums、wafProfiles、wafRulesPlanSegmentation、ddosEnums、promoState、zonesPullZoneMapping等为无输入端点emptyInput。Storage Zone对象存储6 个操作Operation IDRiskDescriptionstorageZone.listreadList all storage zonesstorageZone.getreadGet details of a specific storage zonestorageZone.createwriteCreate a new storage zonestorageZone.updatewriteUpdate settings for a specific storage zonestorageZone.removedestructiveDelete a storage zone and all of its datastorageZone.checkAvailabilityreadCheck whether a storage zone name is available在 endpoints/storage-zone.ts 中可以看到storageZone.list额外支持includeDeleted与search参数storage-zone.ts#L13-L25storageZone.remove可通过deleteLinkedPullZones查询参数选择是否级联删除关联的 Pull Zonestorage-zone.ts#L53-L60。特别注意storageZone.remove在元数据中被标记为irreversible: trueindex.ts#L764-L768删除将销毁存储区内的全部数据Corsair 会对这类操作施加额外确认。DNS Zone域名解析6 个操作Operation IDRiskDescriptiondnsZone.listreadList all DNS zonesdnsZone.getreadGet details of a specific DNS zonednsZone.createRecordwriteCreate a new DNS record in a DNS zonednsZone.updateRecordwriteUpdate an existing DNS recorddnsZone.deleteRecorddestructiveDelete a DNS recorddnsZone.checkAvailabilityreadCheck whether a DNS zone name is available该分组聚焦于 DNS Zone 及其记录的增删改查适合与 Pull Zone 搭配使用——为 CDN 域添加解析记录时可用dnsZone.createRecord完成。ContainersMagic Containers12 个操作Operation IDRiskDescriptioncontainers.applicationsListreadList Magic Container applicationscontainers.nodesListreadList Magic Container nodescontainers.regionsListreadList Magic Container regionscontainers.optimalBaseRegionreadGet the optimal base region for Magic Containerscontainers.userLimitsreadGet Magic Container limits for the accountcontainers.registriesListreadList container registriescontainers.registryDeletedestructiveDelete a container registrycontainers.imageTagsreadList tags for a container imagecontainers.imageDigestreadGet the digest of a container imagecontainers.configSuggestionsreadGet deployment configuration suggestions for a container imagecontainers.publicImagesSearchreadSearch public container images by prefixcontainers.volumesListreadList volumes for a Magic Container applicationapplicationsList、nodesList、regionsList三个列表端点复用containersCursor输入输出 schemaindex.ts#L604-L615从命名推断支持游标分页imageTags、imageDigest、configSuggestions都以容器镜像引用containerImageRef为输入服务于镜像部署前的探查与配置建议。平台与其余分组11 个操作Operation IDRiskDescriptionbilling.summaryreadRetrieve the billing summary for the accountstatistics.getreadRetrieve CDN bandwidth and request statisticsstatistics.countriesreadList countries supported by BunnyCDNstatistics.regionsreadList BunnyCDN regions with pricing infosearch.globalreadGlobal search across pull zones, storage zones, DNS zones and moreapiKeys.listreadList API keys on the accountuser.auditLogreadRetrieve user audit log entries for a datevideoLibrary.listreadList all video librariesvideoLibrary.languagesreadList languages supported by video librariesedgeScripts.listreadList all edge scriptsstream.oembedreadRetrieve oEmbed metadata for a video embedpurge.urlwritePurge a single URL from cache across pull zonesstatistics.get可用于拉取 CDN 带宽与请求统计search.global提供跨 Pull Zone、Storage Zone、DNS Zone 的全局搜索purge.url则按单个 URL 跨所有 Pull Zone 清理缓存与pullZone.purgeCache按 Zone 清理形成互补。请求层五个 API Base 与统一封装插件把所有 HTTP 调用收敛到 client.ts 的makeBunnycdnRequest()并通过 endpoints/helpers.ts 的api()/apiVoid()暴露给各端点// helpers.ts 中的关键逻辑 const key ctx.options.key ?? (await ctx.keys?.get_api_key()) ?? ; return makeBunnycdnRequestT(path, key, { method, query, body, base });其中apiVoid适用于返回 204 No Content 的端点统一包装为{ success: true }helpers.ts#L31-L43。client.ts#L14-L20 定义了 BunnyCDN 官方的五个 API 基址base 名基址用途从端点使用推断corehttps://api.bunny.net默认基址Pull Zone / Storage Zone / DNS / 计费等核心 APIshieldhttps://api.bunny.net/shieldShield 安全类端点computehttps://api.bunny.net/compute计算类端点mchttps://api.bunny.net/mcMagic Containers 类端点streamhttps://video.bunnycdn.comStream 视频类端点如stream.oembed请求构造遵循 OpenAPI 客户端约定POST/PUT/PATCH 携带 JSON body查询参数支持string | number | boolean | string[] | undefined媒体类型固定为application/json; charsetutf-8。网络层错误会被包装为BunnycdnAPIError而带status的 HTTP 错误如 429/401/404会原样抛出交由错误处理器决策client.ts#L60-L70。错误处理与重试语义非幂等保护的精细设计error-handlers.ts 是插件中最值得关注的工程细节它针对四类错误提供了差异化策略错误类型匹配条件处理策略RATE_LIMIT_ERRORHTTP 429 或消息含rate_limited/429幂等操作最多重试 5 次并按响应头retryAfter退避非幂等写入一律不重试AUTH_ERRORHTTP 401 或消息含unauthorized/invalid_auth不重试重试也无法通过鉴权NOT_FOUND_ERRORHTTP 404 或消息含not_found/404不重试资源不存在重试无意义DEFAULT其余所有错误不重试为什么非幂等写入不重试代码注释给出了严谨的推理error-handlers.ts#L5-L19Corsair 在 handler 请求重试时会完整重放整个端点调用若 429 出现在 BunnyCDN 已经提交写入之后下一次重放就会造成重复写入。而 BunnyCDN 不提供幂等键服务端无法收敛重复请求因此必须放弃重试以避免数据重复。插件用显式集合维护非幂等操作清单error-handlers.ts#L21-L47涵盖pullZone.create/update、referrer/IP 黑白名单、resetSecurityKey、setForceSSL、edgeRuleUpsert/SetEnabled、storageZone.create/update、dnsZone.createRecord/updateRecord以及 Shield 的zoneUpdate、rateLimitCreate/Update、botDetectionUpdate、uploadScanningUpdate、accessListCreate/Update/ConfigUpdate、wafRulesReviewTriggeredPost。同时保持可重试的操作包括GET 读操作、删除类操作按收敛语义天然幂等、checkAvailability纯检查、缓存清理最终状态收敛以及仅查询数据的 POST如容器镜像查询——这一分类逻辑直接在源码注释中说明。值得强调的是选择「显式集合」而非「按 HTTP 方法推断」是为了防止未来新增操作时被静默纳入重试且 endpoints.test.ts 会断言集合中的每个条目都是已注册操作。测试与质量保障插件目录内提供了完整的 Jest 测试套件pnpm test见 package.json 的 scriptsendpoints.test.ts通过 Proxy 追踪每个被调用的端点最后做「覆盖扫描」断言被测试触发的操作集合与注册的操作集合完全一致源码注释assert the exercised set is exactly the registered set防止端点注册后缺少测试client.test.ts验证makeBunnycdnRequest的请求构造与错误包装error-handlers.test.ts验证 429/401/404 与默认处理器的匹配与重试决策schema.test.ts验证 Zod 输入输出 schema 的校验行为api.test.ts端到端层面的 API 行为验证。构建脚本为tsc --build --force tsup先做完整类型检查再用 tsup 打包typecheck提供tsc --noEmit独立校验。Webhooks 与最终说明README 明确该插件不提供任何 WebhookNo webhooks。这与 index.ts#L1085 中webhooks: {}与pluginWebhookMatcher: undefined的实现一致——BunnyCDN 的推送事件目前不会进入 Corsair 的 Webhook 体系。因此如果你的应用需要监听缓存清理完成、Shield 事件等异步通知需要另行在 Corsair 中配置 Webhook 源可参考 docs/concepts/webhooks.mdx 的通用机制而不是依赖本插件。关于完整文档插件的 package.json 的homepage字段指向官方插件文档页docs.corsair.dev/plugins/bunnycdnREADME 的 Reference 章节同样声明「Full docs, types, and examples」即完整文档、全部类型定义与可运行示例均可从官方文档站点获取本仓库内则可以直接阅读 packages/bunnycdn 下的源码、schema 与测试作为权威实现参考。小结corsair-dev/bunnycdn通过「标准化端点注册 Zod 输入输出校验 风险分级元数据 API Key 租户认证 幂等感知的错误重试」五层设计把 BunnyCDN 庞大的 API 面Pull Zone、Storage Zone、DNS、Shield、Containers、Stream 等 96 个操作安全地带入 Corsair 的多租户体系。无论是为用户提供 CDN 自服务、托管其 DNS 配置还是代为管理 Shield 安全策略都可以直接以bunnycdn()插件开始并借助其完整的测试套件与类型定义获得编译期保障。【免费下载链接】corsairConnect your users to their apps项目地址: https://gitcode.com/GitHub_Trending/corsa/corsair创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表