Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fresh-connection-auth.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@inkcre/core': patch
---

默认数据库认证按连接快照签发和续签 JWT,在实际请求边界拒绝已切换连接的旧查询,避免过期凭据和跨连接认证竞态。保留显式 SDK token provider 的调用方式。
130 changes: 86 additions & 44 deletions packages/core/src/auth/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,56 +5,98 @@ import { configStore } from '../config'
import { signDatabaseToken } from './sign'
export { signDatabaseToken } from './sign'

const token = ref<string | undefined>(undefined)
let signingSecret: string | undefined
let expiresAt = 0

async function newToken(): Promise<string> {
const secret = configStore.metaConfig.INKCRE_JWT_SECRET
try {
const signedToken = await signDatabaseToken(secret)

if (secret === configStore.metaConfig.INKCRE_JWT_SECRET) {
signingSecret = secret
expiresAt = decodeJwt<{ exp: number }>(signedToken).exp * 1000
token.value = signedToken
/** Create reactive authentication for the currently selected connection. */
export function createAuthStore(configStoreIns = configStore) {
const token = ref<string | undefined>(undefined)
let current = snapshot()

function snapshot() {
return {
baseUrl: configStoreIns.metaConfig.INKCRE_PGREST_URL,
secret: configStoreIns.metaConfig.INKCRE_JWT_SECRET,
expiresAt: 0,
pending: undefined as Promise<string> | undefined,
}
return signedToken
} catch (error) {
console.error('[Auth] Failed to sign a new token:', error)
throw new Error('Failed to sign a new token')
}
}

async function getToken(): Promise<string> {
if (
!token.value ||
signingSecret !== configStore.metaConfig.INKCRE_JWT_SECRET ||
Date.now() >= expiresAt
) {
return await newToken()
function assertCurrent(connection: typeof current, requestUrl?: string) {
if (connection !== current)
throw new Error('Database connection changed during authentication.')
if (!requestUrl) return
if (!connection.baseUrl) throw new Error('PostgREST URL is not configured.')
const base = new URL(connection.baseUrl)
const target = new URL(requestUrl)
const basePath = base.pathname.replace(/\/+$/, '')
const matchesPath = target.pathname === basePath || target.pathname.startsWith(`${basePath}/`)
if (target.origin !== base.origin || !matchesPath) {
throw new Error('Database request does not match the selected connection.')
}
}
return token.value
}

async function refreshToken(): Promise<string> {
return await newToken()
}

// Watch for JWT secret changes and regenerate token
watch(
() => configStore.metaConfig.INKCRE_JWT_SECRET,
async (newSecret) => {
async function sign(connection: typeof current): Promise<string> {
token.value = undefined
signingSecret = undefined
if (!newSecret) return
connection.expiresAt = 0
try {
await newToken()
} catch (error) {
console.error('[Auth] Failed to generate token on secret change:', error)
const signedToken = await signDatabaseToken(connection.secret)
assertCurrent(connection)
const { exp } = decodeJwt(signedToken)
if (typeof exp !== 'number') throw new Error('Database token has no expiration.')
connection.expiresAt = exp * 1000
token.value = signedToken
return signedToken
} catch {
// Signing failures must not retain a usable cache or expose signing credentials.
throw new Error('Failed to sign a new token')
}
}

async function newToken(): Promise<string> {
const connection = current
if (!connection.pending) {
connection.pending = sign(connection).finally(() => {
connection.pending = undefined
})
}
},
{ immediate: true }
)
return connection.pending
}

async function getToken(): Promise<string> {
const connection = current
const signedToken =
token.value && Date.now() < connection.expiresAt ? token.value : await newToken()
// A connection can change while WebCrypto signs or another caller awaits the same promise.
assertCurrent(connection)
return signedToken
}

function requestAuthorizer() {
const connection = current
return async (requestUrl: string) => {
const assertRequestConnection = () => assertCurrent(connection, requestUrl)
assertRequestConnection()
const signedToken = await getToken()
return { token: signedToken, assertCurrent: assertRequestConnection }
}
}

async function refreshToken(): Promise<string> {
return newToken()
}

watch(
() => [
configStoreIns.metaConfig.INKCRE_PGREST_URL,
configStoreIns.metaConfig.INKCRE_JWT_SECRET,
],
() => {
current = snapshot()
token.value = undefined
},
{ flush: 'sync' }
)

return { token, newToken, getToken, refreshToken, requestAuthorizer }
}

export const authStore = { token, newToken, getToken, refreshToken }
/** Global authentication for the application-selected connection. */
export const authStore = createAuthStore()
42 changes: 32 additions & 10 deletions packages/core/src/base/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,25 @@ export function captureDatabaseConnection({
return { baseUrl, tokenProvider, fetch: fetcher }
}

export type AuthorizeDatabaseRequest = (
requestUrl: string
) => Promise<{ token: string; assertCurrent?: () => void }>

export function createPostgrestFetch(
fetcher: typeof globalThis.fetch,
authorizeRequest: AuthorizeDatabaseRequest
): typeof globalThis.fetch {
return async (input, init) => {
const authorization = await authorizeRequest(
input instanceof Request ? input.url : String(input)
)
const headers = new Headers(init?.headers)
headers.set('Authorization', `Bearer ${authorization.token}`)
authorization.assertCurrent?.()
return fetcher(input, { ...init, headers })
}
}

function encodeTransportValue<Value>(value: unknown): Value {
const encoded = JSON.stringify(value)
if (encoded === undefined) {
Expand Down Expand Up @@ -59,9 +78,14 @@ export type RawPostgrestRequestOptions = RequestInit & {
* The regular PostgREST client remains the owner of relational/JSON queries;
* this seam exists for admitted media contracts such as raw bytea RPCs.
*/
export async function rawPostgrestFetch(
export function rawPostgrestFetch(path: string, options: RawPostgrestRequestOptions) {
return rawPostgrestFetchWithAuthorization(path, options)
}

export async function rawPostgrestFetchWithAuthorization(
path: string,
options: RawPostgrestRequestOptions
options: RawPostgrestRequestOptions,
authorizeRequest?: AuthorizeDatabaseRequest
): Promise<Response> {
const {
schema = 'inkcre',
Expand All @@ -79,13 +103,15 @@ export async function rawPostgrestFetch(
? configuredBaseUrl
: `${configuredBaseUrl}/`
const url = new URL(path.replace(/^\//, ''), normalizedBaseUrl)
const token = await tokenProvider()
const headers = new Headers(init.headers)
headers.set('Authorization', `Bearer ${token}`)
headers.set('Accept-Profile', schema)
headers.set('Content-Profile', schema)

const response = await fetcher(url, { ...init, headers })
const request = createPostgrestFetch(
fetcher,
authorizeRequest ?? (async () => ({ token: await tokenProvider() }))
)
const response = await request(url, { ...init, headers })
if (!response.ok) {
const errorResponse = response.clone()
let details: unknown
Expand Down Expand Up @@ -120,11 +146,7 @@ export class DatabaseClient<
}
super(normalizePostgrestBaseUrl(url.href), {
schema: 'inkcre',
fetch: async (input, init) => {
const headers = new Headers(init?.headers)
headers.set('Authorization', `Bearer ${await tokenProvider()}`)
return fetcher(input, { ...init, headers })
},
fetch: createPostgrestFetch(fetcher, async () => ({ token: await tokenProvider() })),
})
}

Expand Down
40 changes: 27 additions & 13 deletions packages/core/src/base/db-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import { observeOperation, SpanKind, SpanStatusCode } from '../obsrv/telemetry'
import type { RelationName, RelationRow } from '../database'
import {
DatabaseClient,
rawPostgrestFetch as fetchRaw,
createPostgrestFetch,
rawPostgrestFetchWithAuthorization,
type DatabaseTokenProvider,
type RawPostgrestRequestOptions as ExplicitRequestOptions,
} from './client'
Expand Down Expand Up @@ -38,12 +39,17 @@ export type RawPostgrestRequestOptions = Omit<

/** Compatibility with the published Vue entry; new SDK callers supply a connection. */
export function rawPostgrestFetch(path: string, options: RawPostgrestRequestOptions = {}) {
return fetchRaw(path, {
...options,
baseUrl: options.baseUrl ?? configStore.metaConfig.INKCRE_PGREST_URL,
tokenProvider: options.tokenProvider ?? (() => authStore.getToken()),
fetch: options.fetch ?? observedFetch,
})
const { baseUrl, tokenProvider, fetch: fetcher, ...init } = options
return rawPostgrestFetchWithAuthorization(
path,
{
...init,
baseUrl: baseUrl ?? configStore.metaConfig.INKCRE_PGREST_URL,
tokenProvider: tokenProvider ?? authStore.getToken,
fetch: fetcher ?? observedFetch,
},
tokenProvider ? undefined : authStore.requestAuthorizer()
)
}

/** Application-selected default retained for published Vue consumers. */
Expand All @@ -56,19 +62,27 @@ export class DBAPIClient<
defSchema?: { parse(input: unknown): DT },
public schemaName: 'inkcre' = 'inkcre',
baseUrl = '',
tokenProvider: DatabaseTokenProvider = () => authStore.getToken()
tokenProvider?: DatabaseTokenProvider
) {
// Unconfigured UI may construct models before the connection form is completed.
super(relation, defSchema, {
baseUrl: baseUrl || configStore.metaConfig.INKCRE_PGREST_URL || 'http://unconfigured.invalid',
tokenProvider,
tokenProvider: tokenProvider ?? authStore.getToken,
fetch: observedFetch,
})
if (!baseUrl) {
if (!baseUrl || !tokenProvider) {
watch(
() => configStore.metaConfig.INKCRE_PGREST_URL,
(value) => {
this.url = value.replace(/\/+$/, '')
() =>
[
configStore.metaConfig.INKCRE_PGREST_URL,
configStore.metaConfig.INKCRE_JWT_SECRET,
] as const,
([selectedUrl]) => {
if (!baseUrl) this.url = selectedUrl.replace(/\/+$/, '')
if (!tokenProvider) {
// PostgREST builders retain this Fetch when created.
this.fetch = createPostgrestFetch(observedFetch, authStore.requestAuthorizer())
}
},
{ immediate: true, flush: 'sync' }
)
Expand Down
Loading
Loading