状态
Registry 状态:UNPUBLISHED。此 SDK 只能从仓库源码 checkout 安装;不要使用外部 package registry。
包状态为 当前包。Astro 集成、SSR middleware、服务端辅助工具和 island 客户端单例已实现。在真实生产基础设施上的 IdP 往返验证仍待人工核实。
集成配置
在 astro.config.mjs 中注册 xidIntegration。该 integration 通过 addMiddleware 以 pre 顺序注入 server middleware,将 verification material 保留在 server-side,并且只公开 client islands 所需的可序列化 browser mode configuration。
// astro.config.mjs
import { defineConfig } from 'astro/config'
import { xidIntegration } from '@xid-kit/astro'
import node from '@astrojs/node'
const jwtKeyJson = process.env.XID_JWKS_PUBLIC_KEY
if (!jwtKeyJson) throw new Error('Missing XID_JWKS_PUBLIC_KEY')
export default defineConfig({
output: 'server',
adapter: node({ mode: 'standalone' }),
integrations: [
xidIntegration({
// This combined SSR setup requires Core routes on the application's exact origin.
browser: { mode: 'same-origin' },
jwtKey: JSON.parse(jwtKeyJson),
issuer: 'https://app.example.com',
sessionTokenExchange: { endpoint: '/v1/sessions/token' },
protectedRoutes: ['/dashboard', '/account'],
signInUrl: '/sign-in',
}),
],
})手动 middleware(替代方案)
// src/middleware.ts
import { sequence } from 'astro:middleware'
import { createXidMiddleware } from '@xid-kit/astro'
export const onRequest = sequence(
createXidMiddleware({
jwtKey: JSON.parse(import.meta.env.XID_JWKS_PUBLIC_KEY),
issuer: 'https://xid.dev',
sessionTokenExchange: { endpoint: '/v1/sessions/token' },
protectedRoutes: ['/dashboard', '/account'],
signInUrl: '/sign-in',
}),
).astro 页面中的服务端认证
---
// src/pages/dashboard.astro
import { getAuth, currentUser } from '@xid-kit/astro/server'
const auth = getAuth(Astro.locals)
if (!auth.userId) return Astro.redirect('/sign-in')
const user = await currentUser(Astro.locals, {
secretKey: import.meta.env.XID_SECRET_KEY,
})
---
<h1>Welcome, {user?.primaryEmailAddress}</h1>客户端 island
// src/components/SignOutButton.tsx
import { getClient } from '@xid-kit/astro/client'
export default function SignOutButton() {
const client = getClient()
const handleSignOut = async () => {
const result = await client.signOut()
if (!result.ok) throw new Error(result.error.message)
window.location.href = '/'
}
return <button onClick={handleSignOut}>Sign out</button>
}Astro.locals 类型定义
将类型引用添加到 src/env.d.ts,以获得 Astro.locals.xidAuth 的完整类型覆盖。
import '@xid-kit/astro/locals'导出的 API
| 导出 | 类型 | 模块 |
|---|---|---|
xidIntegration |
Astro 集成工厂 | @xid-kit/astro |
createXidMiddleware |
middleware 工厂 | @xid-kit/astro |
getAuth, currentUser, xidClient |
服务端辅助工具 | @xid-kit/astro/server |
getClient, initClient, resetClient |
island 客户端单例 | @xid-kit/astro/client |
安全注意事项
jwtKey是 JWKS 公钥;可安全用于 networkless 验证,不包含私钥。secretKey(sk_live_xxx)必须仅限服务端使用;不要传给 island 或客户端 bundle。- 受保护路由在任何页面处理器运行前通过 middleware 中的
Response.redirect重定向;无需客户端 JS。 - 仅将 Core opaque cookie 转发到 exact same-origin session-token endpoint;绝不在本地验证其值