mirror of
https://github.com/kennethnym/aris.git
synced 2026-04-13 05:11:17 +01:00
Compare commits
1 Commits
feat/cloud
...
kn/admin-d
| Author | SHA1 | Date | |
|---|---|---|---|
|
987dd9e59a
|
@@ -20,13 +20,7 @@ import {
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import { Switch } from "@/components/ui/switch"
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"
|
||||
import {
|
||||
fetchSourceConfig,
|
||||
pushLocation,
|
||||
replaceSource,
|
||||
updateProviderConfig,
|
||||
updateSourceCredentials,
|
||||
} from "@/lib/api"
|
||||
import { fetchSourceConfig, pushLocation, replaceSource, updateProviderConfig } from "@/lib/api"
|
||||
|
||||
interface SourceConfigPanelProps {
|
||||
source: SourceDefinition
|
||||
@@ -89,11 +83,7 @@ export function SourceConfigPanel({ source, onUpdate }: SourceConfigPanelProps)
|
||||
(v) => typeof v === "string" && v.length > 0,
|
||||
)
|
||||
if (hasCredentials) {
|
||||
if (source.perUserCredentials) {
|
||||
promises.push(updateSourceCredentials(source.id, credentialFields))
|
||||
} else {
|
||||
promises.push(updateProviderConfig(source.id, { credentials: credentialFields }))
|
||||
}
|
||||
promises.push(updateProviderConfig(source.id, { credentials: credentialFields }))
|
||||
}
|
||||
|
||||
await Promise.all(promises)
|
||||
|
||||
@@ -23,8 +23,6 @@ export interface SourceDefinition {
|
||||
name: string
|
||||
description: string
|
||||
alwaysEnabled?: boolean
|
||||
/** When true, secret fields are stored as per-user credentials via /api/sources/:id/credentials. */
|
||||
perUserCredentials?: boolean
|
||||
fields: Record<string, ConfigFieldDef>
|
||||
}
|
||||
|
||||
@@ -80,44 +78,6 @@ const sourceDefinitions: SourceDefinition[] = [
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "aelis.caldav",
|
||||
name: "CalDAV",
|
||||
description: "Calendar events from any CalDAV server (Nextcloud, Radicale, Baikal, etc.).",
|
||||
perUserCredentials: true,
|
||||
fields: {
|
||||
serverUrl: {
|
||||
type: "string",
|
||||
label: "Server URL",
|
||||
required: true,
|
||||
secret: false,
|
||||
description: "CalDAV server URL (e.g. https://nextcloud.example.com/remote.php/dav)",
|
||||
},
|
||||
username: {
|
||||
type: "string",
|
||||
label: "Username",
|
||||
required: true,
|
||||
secret: false,
|
||||
},
|
||||
password: {
|
||||
type: "string",
|
||||
label: "Password",
|
||||
required: true,
|
||||
secret: true,
|
||||
},
|
||||
lookAheadDays: {
|
||||
type: "number",
|
||||
label: "Look-ahead Days",
|
||||
defaultValue: 0,
|
||||
description: "Number of additional days beyond today to fetch events for",
|
||||
},
|
||||
timeZone: {
|
||||
type: "string",
|
||||
label: "Timezone",
|
||||
description: "IANA timezone for determining \"today\" (e.g. Europe/London). Defaults to UTC.",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "aelis.tfl",
|
||||
name: "TfL",
|
||||
@@ -204,22 +164,6 @@ export async function updateProviderConfig(
|
||||
}
|
||||
}
|
||||
|
||||
export async function updateSourceCredentials(
|
||||
sourceId: string,
|
||||
credentials: Record<string, unknown>,
|
||||
): Promise<void> {
|
||||
const res = await fetch(`${serverBase()}/sources/${sourceId}/credentials`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
credentials: "include",
|
||||
body: JSON.stringify(credentials),
|
||||
})
|
||||
if (!res.ok) {
|
||||
const data = (await res.json()) as { error?: string }
|
||||
throw new Error(data.error ?? `Failed to update credentials: ${res.status}`)
|
||||
}
|
||||
}
|
||||
|
||||
export interface LocationInput {
|
||||
lat: number
|
||||
lng: number
|
||||
|
||||
@@ -5,16 +5,15 @@ DATABASE_URL=postgresql://user:password@localhost:5432/aris
|
||||
BETTER_AUTH_SECRET=
|
||||
|
||||
# Encryption key for source credentials at rest (32 bytes, generate with: openssl rand -base64 32)
|
||||
CREDENTIAL_ENCRYPTION_KEY=
|
||||
CREDENTIALS_ENCRYPTION_KEY=
|
||||
|
||||
# Base URL of the backend
|
||||
BETTER_AUTH_URL=http://localhost:3000
|
||||
|
||||
# Cloudflare Workers AI (LLM feed enhancement)
|
||||
CF_ACCOUNT_ID=
|
||||
WORKERS_AI_API_KEY=
|
||||
# Optional: override the default model (default: @cf/zai-org/glm-4.7-flash)
|
||||
# WORKERS_AI_MODEL=@cf/zai-org/glm-4.7-flash
|
||||
# OpenRouter (LLM feed enhancement)
|
||||
OPENROUTER_API_KEY=
|
||||
# Optional: override the default model (default: openai/gpt-4.1-mini)
|
||||
# OPENROUTER_MODEL=openai/gpt-4.1-mini
|
||||
|
||||
# Apple WeatherKit credentials
|
||||
WEATHERKIT_PRIVATE_KEY=
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
"@aelis/source-location": "workspace:*",
|
||||
"@aelis/source-tfl": "workspace:*",
|
||||
"@aelis/source-weatherkit": "workspace:*",
|
||||
"@openrouter/sdk": "^0.9.11",
|
||||
"arktype": "^2.1.29",
|
||||
"better-auth": "^1",
|
||||
"drizzle-orm": "^0.45.1",
|
||||
|
||||
@@ -1,85 +0,0 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
|
||||
import { CalDavSourceProvider } from "./provider.ts"
|
||||
|
||||
describe("CalDavSourceProvider", () => {
|
||||
const provider = new CalDavSourceProvider()
|
||||
|
||||
test("sourceId is aelis.caldav", () => {
|
||||
expect(provider.sourceId).toBe("aelis.caldav")
|
||||
})
|
||||
|
||||
test("throws when credentials are null", async () => {
|
||||
const config = { serverUrl: "https://caldav.icloud.com", username: "user@icloud.com" }
|
||||
await expect(provider.feedSourceForUser("user-1", config, null)).rejects.toThrow(
|
||||
"No CalDAV credentials configured",
|
||||
)
|
||||
})
|
||||
|
||||
test("throws when credentials are missing password", async () => {
|
||||
const config = { serverUrl: "https://caldav.icloud.com", username: "user@icloud.com" }
|
||||
await expect(provider.feedSourceForUser("user-1", config, {})).rejects.toThrow(
|
||||
"password must be a string",
|
||||
)
|
||||
})
|
||||
|
||||
test("throws when config is missing serverUrl", async () => {
|
||||
const credentials = { password: "app-specific-password" }
|
||||
await expect(
|
||||
provider.feedSourceForUser("user-1", { username: "user@icloud.com" }, credentials),
|
||||
).rejects.toThrow("Invalid CalDAV config")
|
||||
})
|
||||
|
||||
test("throws when config is missing username", async () => {
|
||||
const credentials = { password: "app-specific-password" }
|
||||
await expect(
|
||||
provider.feedSourceForUser("user-1", { serverUrl: "https://caldav.icloud.com" }, credentials),
|
||||
).rejects.toThrow("Invalid CalDAV config")
|
||||
})
|
||||
|
||||
test("throws when config has extra keys", async () => {
|
||||
const config = {
|
||||
serverUrl: "https://caldav.icloud.com",
|
||||
username: "user@icloud.com",
|
||||
extra: true,
|
||||
}
|
||||
const credentials = { password: "app-specific-password" }
|
||||
await expect(provider.feedSourceForUser("user-1", config, credentials)).rejects.toThrow(
|
||||
"Invalid CalDAV config",
|
||||
)
|
||||
})
|
||||
|
||||
test("throws when credentials have extra keys", async () => {
|
||||
const config = { serverUrl: "https://caldav.icloud.com", username: "user@icloud.com" }
|
||||
const credentials = { password: "app-specific-password", extra: true }
|
||||
await expect(provider.feedSourceForUser("user-1", config, credentials)).rejects.toThrow(
|
||||
"extra must be removed",
|
||||
)
|
||||
})
|
||||
|
||||
test("returns CalDavSource with valid config and credentials", async () => {
|
||||
const config = {
|
||||
serverUrl: "https://caldav.icloud.com",
|
||||
username: "user@icloud.com",
|
||||
lookAheadDays: 3,
|
||||
timeZone: "Europe/London",
|
||||
}
|
||||
const credentials = { password: "app-specific-password" }
|
||||
|
||||
const source = await provider.feedSourceForUser("user-1", config, credentials)
|
||||
expect(source).toBeDefined()
|
||||
expect(source.id).toBe("aelis.caldav")
|
||||
})
|
||||
|
||||
test("returns CalDavSource with minimal config", async () => {
|
||||
const config = {
|
||||
serverUrl: "https://caldav.icloud.com",
|
||||
username: "user@icloud.com",
|
||||
}
|
||||
const credentials = { password: "app-specific-password" }
|
||||
|
||||
const source = await provider.feedSourceForUser("user-1", config, credentials)
|
||||
expect(source).toBeDefined()
|
||||
expect(source.id).toBe("aelis.caldav")
|
||||
})
|
||||
})
|
||||
@@ -1,53 +0,0 @@
|
||||
import { CalDavSource } from "@aelis/source-caldav"
|
||||
import { type } from "arktype"
|
||||
|
||||
import type { FeedSourceProvider } from "../session/feed-source-provider.ts"
|
||||
|
||||
import { InvalidSourceCredentialsError } from "../sources/errors.ts"
|
||||
|
||||
const caldavConfig = type({
|
||||
"+": "reject",
|
||||
serverUrl: "string",
|
||||
username: "string",
|
||||
"lookAheadDays?": "number",
|
||||
"timeZone?": "string",
|
||||
})
|
||||
|
||||
const caldavCredentials = type({
|
||||
"+": "reject",
|
||||
password: "string",
|
||||
})
|
||||
|
||||
export class CalDavSourceProvider implements FeedSourceProvider {
|
||||
readonly sourceId = "aelis.caldav"
|
||||
readonly configSchema = caldavConfig
|
||||
|
||||
async feedSourceForUser(
|
||||
_userId: string,
|
||||
config: unknown,
|
||||
credentials: unknown,
|
||||
): Promise<CalDavSource> {
|
||||
const parsed = caldavConfig(config)
|
||||
if (parsed instanceof type.errors) {
|
||||
throw new Error(`Invalid CalDAV config: ${parsed.summary}`)
|
||||
}
|
||||
|
||||
if (!credentials) {
|
||||
throw new InvalidSourceCredentialsError("aelis.caldav", "No CalDAV credentials configured")
|
||||
}
|
||||
|
||||
const creds = caldavCredentials(credentials)
|
||||
if (creds instanceof type.errors) {
|
||||
throw new InvalidSourceCredentialsError("aelis.caldav", creds.summary)
|
||||
}
|
||||
|
||||
return new CalDavSource({
|
||||
serverUrl: parsed.serverUrl,
|
||||
authMethod: "basic",
|
||||
username: parsed.username,
|
||||
password: creds.password,
|
||||
lookAheadDays: parsed.lookAheadDays,
|
||||
timeZone: parsed.timeZone,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,13 @@
|
||||
import { type } from "arktype"
|
||||
import { OpenRouter } from "@openrouter/sdk"
|
||||
|
||||
import type { EnhancementResult } from "./schema.ts"
|
||||
|
||||
import { enhancementResultJsonSchema, parseEnhancementResult } from "./schema.ts"
|
||||
|
||||
const DEFAULT_MODEL = "@cf/zai-org/glm-4.7-flash"
|
||||
const DEFAULT_MODEL = "z-ai/glm-4.7-flash"
|
||||
const DEFAULT_TIMEOUT_MS = 30_000
|
||||
|
||||
export interface LlmClientConfig {
|
||||
accountId: string
|
||||
apiKey: string
|
||||
model?: string
|
||||
timeoutMs?: number
|
||||
@@ -23,94 +22,52 @@ export interface LlmClient {
|
||||
enhance(request: LlmClientRequest): Promise<EnhancementResult | null>
|
||||
}
|
||||
|
||||
const CloudflareApiResponse = type({
|
||||
result: {
|
||||
choices: type({
|
||||
message: {
|
||||
content: "string",
|
||||
"role?": "string",
|
||||
},
|
||||
}).array(),
|
||||
},
|
||||
success: "boolean",
|
||||
"errors?": type({ message: "string" }).array(),
|
||||
})
|
||||
|
||||
/**
|
||||
* Creates a reusable LLM client backed by Cloudflare Workers AI.
|
||||
* Uses the REST API with structured JSON output.
|
||||
* Creates a reusable LLM client backed by OpenRouter.
|
||||
* The OpenRouter SDK instance is created once and reused across calls.
|
||||
*/
|
||||
export function createLlmClient(config: LlmClientConfig): LlmClient {
|
||||
const client = new OpenRouter({
|
||||
apiKey: config.apiKey,
|
||||
timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
||||
})
|
||||
const model = config.model ?? DEFAULT_MODEL
|
||||
const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS
|
||||
const baseUrl = `https://api.cloudflare.com/client/v4/accounts/${config.accountId}/ai/run/${model}`
|
||||
|
||||
return {
|
||||
async enhance(request) {
|
||||
try {
|
||||
const res = await fetch(baseUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${config.apiKey}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
messages: [
|
||||
{ role: "system", content: request.systemPrompt },
|
||||
{ role: "user", content: request.userMessage },
|
||||
],
|
||||
response_format: {
|
||||
type: "json_schema",
|
||||
json_schema: {
|
||||
name: "enhancement_result",
|
||||
strict: false,
|
||||
schema: enhancementResultJsonSchema,
|
||||
},
|
||||
const response = await client.chat.send({
|
||||
chatGenerationParams: {
|
||||
model,
|
||||
messages: [
|
||||
{ role: "system" as const, content: request.systemPrompt },
|
||||
{ role: "user" as const, content: request.userMessage },
|
||||
],
|
||||
responseFormat: {
|
||||
type: "json_schema" as const,
|
||||
jsonSchema: {
|
||||
name: "enhancement_result",
|
||||
strict: false,
|
||||
schema: enhancementResultJsonSchema,
|
||||
},
|
||||
stream: false,
|
||||
}),
|
||||
// @ts-expect-error — bun-types AbortSignal conflicts with ESNext lib in tsc; works at runtime and in VSCode
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
})
|
||||
},
|
||||
reasoning: { effort: "none" },
|
||||
stream: false,
|
||||
},
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
const body = await res.text()
|
||||
console.warn(`[enhancement] Cloudflare API error ${res.status}: ${body}`)
|
||||
return null
|
||||
}
|
||||
|
||||
const json: unknown = await res.json()
|
||||
const parsed = CloudflareApiResponse(json)
|
||||
if (parsed instanceof type.errors) {
|
||||
console.warn("[enhancement] Unexpected API response shape:", parsed.summary)
|
||||
return null
|
||||
}
|
||||
|
||||
if (!parsed.success) {
|
||||
console.warn("[enhancement] Cloudflare API errors:", parsed.errors)
|
||||
return null
|
||||
}
|
||||
|
||||
const content = parsed.result.choices[0]?.message.content
|
||||
if (content === undefined) {
|
||||
console.warn("[enhancement] LLM returned no choices in response")
|
||||
return null
|
||||
}
|
||||
|
||||
const result = parseEnhancementResult(content)
|
||||
if (!result) {
|
||||
console.warn("[enhancement] Failed to parse LLM response:", content)
|
||||
}
|
||||
|
||||
return result
|
||||
} catch (error) {
|
||||
if (error instanceof DOMException && error.name === "TimeoutError") {
|
||||
console.warn("[enhancement] LLM request timed out")
|
||||
} else {
|
||||
console.warn("[enhancement] LLM request failed:", error)
|
||||
}
|
||||
const message = response.choices?.[0]?.message
|
||||
const content = message?.content ?? message?.reasoning
|
||||
if (typeof content !== "string") {
|
||||
console.warn("[enhancement] LLM returned no content in response")
|
||||
return null
|
||||
}
|
||||
|
||||
const result = parseEnhancementResult(content)
|
||||
if (!result) {
|
||||
console.warn("[enhancement] Failed to parse LLM response:", content)
|
||||
}
|
||||
|
||||
return result
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,8 @@ export type SyntheticItem = typeof SyntheticItem.infer
|
||||
export type EnhancementResult = typeof EnhancementResult.infer
|
||||
|
||||
/**
|
||||
* JSON Schema passed to Cloudflare Workers AI for structured output.
|
||||
* JSON Schema passed to OpenRouter's structured output.
|
||||
* OpenRouter doesn't support arktype, so this is maintained separately.
|
||||
*
|
||||
* ⚠️ Must stay in sync with EnhancementResult above.
|
||||
* If you add/remove fields, update both schemas.
|
||||
|
||||
@@ -5,11 +5,7 @@ import type { FeedSourceProvider } from "../session/feed-source-provider.ts"
|
||||
export class LocationSourceProvider implements FeedSourceProvider {
|
||||
readonly sourceId = "aelis.location"
|
||||
|
||||
async feedSourceForUser(
|
||||
_userId: string,
|
||||
_config: unknown,
|
||||
_credentials: unknown,
|
||||
): Promise<LocationSource> {
|
||||
async feedSourceForUser(_userId: string, _config: unknown): Promise<LocationSource> {
|
||||
return new LocationSource()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,12 +6,10 @@ import { createRequireAdmin } from "./auth/admin-middleware.ts"
|
||||
import { registerAuthHandlers } from "./auth/http.ts"
|
||||
import { createAuth } from "./auth/index.ts"
|
||||
import { createRequireSession } from "./auth/session-middleware.ts"
|
||||
import { CalDavSourceProvider } from "./caldav/provider.ts"
|
||||
import { createDatabase } from "./db/index.ts"
|
||||
import { registerFeedHttpHandlers } from "./engine/http.ts"
|
||||
import { createFeedEnhancer } from "./enhancement/enhance-feed.ts"
|
||||
import { createLlmClient } from "./enhancement/llm-client.ts"
|
||||
import { CredentialEncryptor } from "./lib/crypto.ts"
|
||||
import { registerLocationHttpHandlers } from "./location/http.ts"
|
||||
import { LocationSourceProvider } from "./location/provider.ts"
|
||||
import { UserSessionManager } from "./session/index.ts"
|
||||
@@ -23,38 +21,22 @@ function main() {
|
||||
const { db, close: closeDb } = createDatabase(process.env.DATABASE_URL!)
|
||||
const auth = createAuth(db)
|
||||
|
||||
const cfAccountId = process.env.CF_ACCOUNT_ID
|
||||
const workersAiApiKey = process.env.WORKERS_AI_API_KEY
|
||||
const feedEnhancer =
|
||||
cfAccountId && workersAiApiKey
|
||||
? createFeedEnhancer({
|
||||
client: createLlmClient({
|
||||
accountId: cfAccountId,
|
||||
apiKey: workersAiApiKey,
|
||||
model: process.env.WORKERS_AI_MODEL || undefined,
|
||||
}),
|
||||
})
|
||||
: null
|
||||
if (!feedEnhancer) {
|
||||
console.warn(
|
||||
"[enhancement] CF_ACCOUNT_ID/WORKERS_AI_API_KEY not set — feed enhancement disabled",
|
||||
)
|
||||
}
|
||||
|
||||
const credentialEncryptionKey = process.env.CREDENTIAL_ENCRYPTION_KEY
|
||||
const credentialEncryptor = credentialEncryptionKey
|
||||
? new CredentialEncryptor(credentialEncryptionKey)
|
||||
const openrouterApiKey = process.env.OPENROUTER_API_KEY
|
||||
const feedEnhancer = openrouterApiKey
|
||||
? createFeedEnhancer({
|
||||
client: createLlmClient({
|
||||
apiKey: openrouterApiKey,
|
||||
model: process.env.OPENROUTER_MODEL || undefined,
|
||||
}),
|
||||
})
|
||||
: null
|
||||
if (!credentialEncryptor) {
|
||||
console.warn(
|
||||
"[credentials] CREDENTIAL_ENCRYPTION_KEY not set — per-user credential storage disabled",
|
||||
)
|
||||
if (!feedEnhancer) {
|
||||
console.warn("[enhancement] OPENROUTER_API_KEY not set — feed enhancement disabled")
|
||||
}
|
||||
|
||||
const sessionManager = new UserSessionManager({
|
||||
db,
|
||||
providers: [
|
||||
new CalDavSourceProvider(),
|
||||
new LocationSourceProvider(),
|
||||
new WeatherSourceProvider({
|
||||
credentials: {
|
||||
@@ -67,7 +49,6 @@ function main() {
|
||||
new TflSourceProvider({ apiKey: process.env.TFL_API_KEY! }),
|
||||
],
|
||||
feedEnhancer,
|
||||
credentialEncryptor,
|
||||
})
|
||||
|
||||
const app = new Hono()
|
||||
|
||||
@@ -8,5 +8,5 @@ export interface FeedSourceProvider {
|
||||
readonly sourceId: string
|
||||
/** Arktype schema for validating user-provided config. Omit if the source has no config. */
|
||||
readonly configSchema?: ConfigSchema
|
||||
feedSourceForUser(userId: string, config: unknown, credentials: unknown): Promise<FeedSource>
|
||||
feedSourceForUser(userId: string, config: unknown): Promise<FeedSource>
|
||||
}
|
||||
|
||||
@@ -7,12 +7,6 @@ import { beforeEach, describe, expect, mock, spyOn, test } from "bun:test"
|
||||
import type { Database } from "../db/index.ts"
|
||||
import type { FeedSourceProvider } from "./feed-source-provider.ts"
|
||||
|
||||
import { CredentialEncryptor } from "../lib/crypto.ts"
|
||||
import {
|
||||
CredentialStorageUnavailableError,
|
||||
InvalidSourceCredentialsError,
|
||||
} from "../sources/errors.ts"
|
||||
import { SourceNotFoundError } from "../sources/errors.ts"
|
||||
import { UserSessionManager } from "./user-session-manager.ts"
|
||||
|
||||
/**
|
||||
@@ -44,13 +38,6 @@ function getEnabledSourceIds(userId: string): string[] {
|
||||
*/
|
||||
let mockFindResult: unknown | undefined
|
||||
|
||||
/**
|
||||
* Spy for `updateCredentials` calls. Tests can inspect calls via
|
||||
* `mockUpdateCredentialsCalls` or override behavior.
|
||||
*/
|
||||
const mockUpdateCredentialsCalls: Array<{ sourceId: string; credentials: Buffer }> = []
|
||||
let mockUpdateCredentialsError: Error | null = null
|
||||
|
||||
// Mock the sources module so UserSessionManager's DB query returns controlled data.
|
||||
mock.module("../sources/user-sources.ts", () => ({
|
||||
sources: (_db: Database, userId: string) => ({
|
||||
@@ -81,12 +68,6 @@ mock.module("../sources/user-sources.ts", () => ({
|
||||
updatedAt: now,
|
||||
}
|
||||
},
|
||||
async updateCredentials(sourceId: string, credentials: Buffer) {
|
||||
if (mockUpdateCredentialsError) {
|
||||
throw mockUpdateCredentialsError
|
||||
}
|
||||
mockUpdateCredentialsCalls.push({ sourceId, credentials })
|
||||
},
|
||||
}),
|
||||
}))
|
||||
|
||||
@@ -112,11 +93,8 @@ function createStubSource(id: string, items: FeedItem[] = []): FeedSource {
|
||||
|
||||
function createStubProvider(
|
||||
sourceId: string,
|
||||
factory: (
|
||||
userId: string,
|
||||
config: Record<string, unknown>,
|
||||
credentials: unknown,
|
||||
) => Promise<FeedSource> = async () => createStubSource(sourceId),
|
||||
factory: (userId: string, config: Record<string, unknown>) => Promise<FeedSource> = async () =>
|
||||
createStubSource(sourceId),
|
||||
): FeedSourceProvider {
|
||||
return { sourceId, feedSourceForUser: factory }
|
||||
}
|
||||
@@ -138,8 +116,6 @@ const weatherProvider: FeedSourceProvider = {
|
||||
beforeEach(() => {
|
||||
enabledByUser.clear()
|
||||
mockFindResult = undefined
|
||||
mockUpdateCredentialsCalls.length = 0
|
||||
mockUpdateCredentialsError = null
|
||||
})
|
||||
|
||||
describe("UserSessionManager", () => {
|
||||
@@ -705,122 +681,3 @@ describe("UserSessionManager.replaceProvider", () => {
|
||||
expect(feedAfter.items[0]!.data.version).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
const TEST_ENCRYPTION_KEY = "/bv1nbzC4ozZkT/pcv5oQfl+JAMuMZDUSVDesG2dur8="
|
||||
const testEncryptor = new CredentialEncryptor(TEST_ENCRYPTION_KEY)
|
||||
|
||||
describe("UserSessionManager.updateSourceCredentials", () => {
|
||||
test("encrypts and persists credentials", async () => {
|
||||
setEnabledSources(["test"])
|
||||
const provider = createStubProvider("test")
|
||||
const manager = new UserSessionManager({
|
||||
db: fakeDb,
|
||||
providers: [provider],
|
||||
credentialEncryptor: testEncryptor,
|
||||
})
|
||||
|
||||
await manager.updateSourceCredentials("user-1", "test", { token: "secret-123" })
|
||||
|
||||
expect(mockUpdateCredentialsCalls).toHaveLength(1)
|
||||
expect(mockUpdateCredentialsCalls[0]!.sourceId).toBe("test")
|
||||
|
||||
// Verify the persisted buffer decrypts to the original credentials
|
||||
const decrypted = JSON.parse(testEncryptor.decrypt(mockUpdateCredentialsCalls[0]!.credentials))
|
||||
expect(decrypted).toEqual({ token: "secret-123" })
|
||||
})
|
||||
|
||||
test("throws CredentialStorageUnavailableError when encryptor is not configured", async () => {
|
||||
setEnabledSources(["test"])
|
||||
const provider = createStubProvider("test")
|
||||
const manager = new UserSessionManager({
|
||||
db: fakeDb,
|
||||
providers: [provider],
|
||||
// no credentialEncryptor
|
||||
})
|
||||
|
||||
await expect(
|
||||
manager.updateSourceCredentials("user-1", "test", { token: "x" }),
|
||||
).rejects.toBeInstanceOf(CredentialStorageUnavailableError)
|
||||
})
|
||||
|
||||
test("throws SourceNotFoundError for unknown source", async () => {
|
||||
setEnabledSources([])
|
||||
const manager = new UserSessionManager({
|
||||
db: fakeDb,
|
||||
providers: [],
|
||||
credentialEncryptor: testEncryptor,
|
||||
})
|
||||
|
||||
await expect(
|
||||
manager.updateSourceCredentials("user-1", "unknown", { token: "x" }),
|
||||
).rejects.toBeInstanceOf(SourceNotFoundError)
|
||||
})
|
||||
|
||||
test("propagates InvalidSourceCredentialsError from provider", async () => {
|
||||
setEnabledSources(["test"])
|
||||
let callCount = 0
|
||||
const provider: FeedSourceProvider = {
|
||||
sourceId: "test",
|
||||
async feedSourceForUser(_userId: string, _config: unknown, _credentials: unknown) {
|
||||
callCount++
|
||||
// Succeed on first call (session creation), throw on refresh
|
||||
if (callCount > 1) {
|
||||
throw new InvalidSourceCredentialsError("test", "bad credentials")
|
||||
}
|
||||
return createStubSource("test")
|
||||
},
|
||||
}
|
||||
const manager = new UserSessionManager({
|
||||
db: fakeDb,
|
||||
providers: [provider],
|
||||
credentialEncryptor: testEncryptor,
|
||||
})
|
||||
|
||||
// Create a session first so the refresh path is exercised
|
||||
await manager.getOrCreate("user-1")
|
||||
|
||||
await expect(
|
||||
manager.updateSourceCredentials("user-1", "test", { token: "bad" }),
|
||||
).rejects.toBeInstanceOf(InvalidSourceCredentialsError)
|
||||
|
||||
// Credentials should still have been persisted before the provider threw
|
||||
expect(mockUpdateCredentialsCalls).toHaveLength(1)
|
||||
})
|
||||
|
||||
test("refreshes source in active session after credential update", async () => {
|
||||
setEnabledSources(["test"])
|
||||
let receivedCredentials: unknown = null
|
||||
const provider = createStubProvider("test", async (_userId, _config, credentials) => {
|
||||
receivedCredentials = credentials
|
||||
return createStubSource("test")
|
||||
})
|
||||
const manager = new UserSessionManager({
|
||||
db: fakeDb,
|
||||
providers: [provider],
|
||||
credentialEncryptor: testEncryptor,
|
||||
})
|
||||
|
||||
await manager.getOrCreate("user-1")
|
||||
await manager.updateSourceCredentials("user-1", "test", { token: "refreshed" })
|
||||
|
||||
expect(receivedCredentials).toEqual({ token: "refreshed" })
|
||||
})
|
||||
|
||||
test("persists credentials without session refresh when no active session", async () => {
|
||||
setEnabledSources(["test"])
|
||||
const factory = mock(async () => createStubSource("test"))
|
||||
const provider: FeedSourceProvider = { sourceId: "test", feedSourceForUser: factory }
|
||||
const manager = new UserSessionManager({
|
||||
db: fakeDb,
|
||||
providers: [provider],
|
||||
credentialEncryptor: testEncryptor,
|
||||
})
|
||||
|
||||
// No session created — just update credentials
|
||||
await manager.updateSourceCredentials("user-1", "test", { token: "stored" })
|
||||
|
||||
expect(mockUpdateCredentialsCalls).toHaveLength(1)
|
||||
// feedSourceForUser should not have been called (no session to refresh)
|
||||
expect(factory).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -5,14 +5,9 @@ import merge from "lodash.merge"
|
||||
|
||||
import type { Database } from "../db/index.ts"
|
||||
import type { FeedEnhancer } from "../enhancement/enhance-feed.ts"
|
||||
import type { CredentialEncryptor } from "../lib/crypto.ts"
|
||||
import type { FeedSourceProvider } from "./feed-source-provider.ts"
|
||||
|
||||
import {
|
||||
CredentialStorageUnavailableError,
|
||||
InvalidSourceConfigError,
|
||||
SourceNotFoundError,
|
||||
} from "../sources/errors.ts"
|
||||
import { InvalidSourceConfigError, SourceNotFoundError } from "../sources/errors.ts"
|
||||
import { sources } from "../sources/user-sources.ts"
|
||||
import { UserSession } from "./user-session.ts"
|
||||
|
||||
@@ -20,7 +15,6 @@ export interface UserSessionManagerConfig {
|
||||
db: Database
|
||||
providers: FeedSourceProvider[]
|
||||
feedEnhancer?: FeedEnhancer | null
|
||||
credentialEncryptor?: CredentialEncryptor | null
|
||||
}
|
||||
|
||||
export class UserSessionManager {
|
||||
@@ -29,7 +23,7 @@ export class UserSessionManager {
|
||||
private readonly db: Database
|
||||
private readonly providers = new Map<string, FeedSourceProvider>()
|
||||
private readonly feedEnhancer: FeedEnhancer | null
|
||||
private readonly encryptor: CredentialEncryptor | null
|
||||
private readonly db: Database
|
||||
|
||||
constructor(config: UserSessionManagerConfig) {
|
||||
this.db = config.db
|
||||
@@ -37,7 +31,7 @@ export class UserSessionManager {
|
||||
this.providers.set(provider.sourceId, provider)
|
||||
}
|
||||
this.feedEnhancer = config.feedEnhancer ?? null
|
||||
this.encryptor = config.credentialEncryptor ?? null
|
||||
this.db = config.db
|
||||
}
|
||||
|
||||
getProvider(sourceId: string): FeedSourceProvider | undefined {
|
||||
@@ -126,15 +120,14 @@ export class UserSessionManager {
|
||||
return
|
||||
}
|
||||
|
||||
// Fetch the existing row for config merging and credential access.
|
||||
// When config is provided, fetch existing to deep-merge before validating.
|
||||
// NOTE: find + updateConfig is not atomic. A concurrent update could
|
||||
// read stale config. Use SELECT FOR UPDATE or atomic jsonb merge if
|
||||
// this becomes a problem.
|
||||
const existingRow = await sources(this.db, userId).find(sourceId)
|
||||
|
||||
let mergedConfig: Record<string, unknown> | undefined
|
||||
if (update.config !== undefined && provider.configSchema) {
|
||||
const existingConfig = (existingRow?.config ?? {}) as Record<string, unknown>
|
||||
const existing = await sources(this.db, userId).find(sourceId)
|
||||
const existingConfig = (existing?.config ?? {}) as Record<string, unknown>
|
||||
mergedConfig = merge({}, existingConfig, update.config)
|
||||
|
||||
const validated = provider.configSchema(mergedConfig)
|
||||
@@ -156,10 +149,7 @@ export class UserSessionManager {
|
||||
if (update.enabled === false) {
|
||||
session.removeSource(sourceId)
|
||||
} else {
|
||||
const credentials = existingRow?.credentials
|
||||
? this.decryptCredentials(existingRow.credentials)
|
||||
: null
|
||||
const source = await provider.feedSourceForUser(userId, mergedConfig ?? {}, credentials)
|
||||
const source = await provider.feedSourceForUser(userId, mergedConfig ?? {})
|
||||
session.replaceSource(sourceId, source)
|
||||
}
|
||||
}
|
||||
@@ -192,11 +182,6 @@ export class UserSessionManager {
|
||||
}
|
||||
|
||||
const config = data.config ?? {}
|
||||
|
||||
// Fetch existing row before upsert to capture credentials for session refresh.
|
||||
// For new rows this will be undefined — credentials will be null.
|
||||
const existingRow = await sources(this.db, userId).find(sourceId)
|
||||
|
||||
await sources(this.db, userId).upsertConfig(sourceId, {
|
||||
enabled: data.enabled,
|
||||
config,
|
||||
@@ -207,10 +192,7 @@ export class UserSessionManager {
|
||||
if (!data.enabled) {
|
||||
session.removeSource(sourceId)
|
||||
} else {
|
||||
const credentials = existingRow?.credentials
|
||||
? this.decryptCredentials(existingRow.credentials)
|
||||
: null
|
||||
const source = await provider.feedSourceForUser(userId, config, credentials)
|
||||
const source = await provider.feedSourceForUser(userId, config)
|
||||
if (session.hasSource(sourceId)) {
|
||||
session.replaceSource(sourceId, source)
|
||||
} else {
|
||||
@@ -220,44 +202,6 @@ export class UserSessionManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates, encrypts, and persists per-user credentials for a source,
|
||||
* then refreshes the active session.
|
||||
*
|
||||
* @throws {SourceNotFoundError} if the source row doesn't exist or has no registered provider
|
||||
* @throws {CredentialStorageUnavailableError} if no CredentialEncryptor is configured
|
||||
*/
|
||||
async updateSourceCredentials(
|
||||
userId: string,
|
||||
sourceId: string,
|
||||
credentials: unknown,
|
||||
): Promise<void> {
|
||||
const provider = this.providers.get(sourceId)
|
||||
if (!provider) {
|
||||
throw new SourceNotFoundError(sourceId, userId)
|
||||
}
|
||||
|
||||
if (!this.encryptor) {
|
||||
throw new CredentialStorageUnavailableError()
|
||||
}
|
||||
|
||||
const encrypted = this.encryptor.encrypt(JSON.stringify(credentials))
|
||||
await sources(this.db, userId).updateCredentials(sourceId, encrypted)
|
||||
|
||||
// Refresh the source in the active session.
|
||||
// If feedSourceForUser throws (e.g. provider rejects the credentials),
|
||||
// the DB already has the new credentials but the session keeps the old
|
||||
// source. The next session creation will pick up the persisted credentials.
|
||||
const session = this.sessions.get(userId)
|
||||
if (session && session.hasSource(sourceId)) {
|
||||
const row = await sources(this.db, userId).find(sourceId)
|
||||
if (row?.enabled) {
|
||||
const source = await provider.feedSourceForUser(userId, row.config ?? {}, credentials)
|
||||
session.replaceSource(sourceId, source)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces a provider and updates all active sessions.
|
||||
* The new provider must have the same sourceId as an existing one.
|
||||
@@ -310,12 +254,7 @@ export class UserSessionManager {
|
||||
const row = await sources(this.db, session.userId).find(provider.sourceId)
|
||||
if (!row?.enabled) return
|
||||
|
||||
const credentials = row.credentials ? this.decryptCredentials(row.credentials) : null
|
||||
const newSource = await provider.feedSourceForUser(
|
||||
session.userId,
|
||||
row.config ?? {},
|
||||
credentials,
|
||||
)
|
||||
const newSource = await provider.feedSourceForUser(session.userId, row.config ?? {})
|
||||
session.replaceSource(provider.sourceId, newSource)
|
||||
} catch (err) {
|
||||
console.error(
|
||||
@@ -332,8 +271,7 @@ export class UserSessionManager {
|
||||
for (const row of enabledRows) {
|
||||
const provider = this.providers.get(row.sourceId)
|
||||
if (provider) {
|
||||
const credentials = row.credentials ? this.decryptCredentials(row.credentials) : null
|
||||
promises.push(provider.feedSourceForUser(userId, row.config ?? {}, credentials))
|
||||
promises.push(provider.feedSourceForUser(userId, row.config ?? {}))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -364,19 +302,4 @@ export class UserSessionManager {
|
||||
|
||||
return new UserSession(userId, feedSources, this.feedEnhancer)
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypts a credentials buffer from the DB, returning parsed JSON or null.
|
||||
* Returns null (with a warning) if decryption or parsing fails — e.g. due to
|
||||
* key rotation, data corruption, or malformed JSON.
|
||||
*/
|
||||
private decryptCredentials(credentials: Buffer): unknown {
|
||||
if (!this.encryptor) return null
|
||||
try {
|
||||
return JSON.parse(this.encryptor.decrypt(credentials))
|
||||
} catch (err) {
|
||||
console.warn("[UserSessionManager] Failed to decrypt credentials:", err)
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,26 +24,3 @@ export class InvalidSourceConfigError extends Error {
|
||||
this.sourceId = sourceId
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Thrown by providers when credentials fail validation.
|
||||
*/
|
||||
export class InvalidSourceCredentialsError extends Error {
|
||||
readonly sourceId: string
|
||||
|
||||
constructor(sourceId: string, summary: string) {
|
||||
super(summary)
|
||||
this.name = "InvalidSourceCredentialsError"
|
||||
this.sourceId = sourceId
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Thrown when credential storage is not configured (missing encryption key).
|
||||
*/
|
||||
export class CredentialStorageUnavailableError extends Error {
|
||||
constructor() {
|
||||
super("Credential storage is not configured")
|
||||
this.name = "CredentialStorageUnavailableError"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,11 +7,10 @@ import type { Database } from "../db/index.ts"
|
||||
import type { ConfigSchema, FeedSourceProvider } from "../session/feed-source-provider.ts"
|
||||
|
||||
import { mockAuthSessionMiddleware } from "../auth/session-middleware.ts"
|
||||
import { CredentialEncryptor } from "../lib/crypto.ts"
|
||||
import { UserSessionManager } from "../session/user-session-manager.ts"
|
||||
import { tflConfig } from "../tfl/provider.ts"
|
||||
import { weatherConfig } from "../weather/provider.ts"
|
||||
import { InvalidSourceCredentialsError, SourceNotFoundError } from "./errors.ts"
|
||||
import { SourceNotFoundError } from "./errors.ts"
|
||||
import { registerSourcesHttpHandlers } from "./http.ts"
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -40,7 +39,7 @@ function createStubProvider(sourceId: string, configSchema?: ConfigSchema): Feed
|
||||
return {
|
||||
sourceId,
|
||||
configSchema,
|
||||
async feedSourceForUser(_userId: string, _config: unknown, _credentials: unknown) {
|
||||
async feedSourceForUser() {
|
||||
return createStubSource(sourceId)
|
||||
},
|
||||
}
|
||||
@@ -106,12 +105,6 @@ function createInMemoryStore() {
|
||||
})
|
||||
}
|
||||
},
|
||||
async updateCredentials(sourceId: string, _credentials: Buffer) {
|
||||
const existing = rows.get(key(userId, sourceId))
|
||||
if (!existing) {
|
||||
throw new SourceNotFoundError(sourceId, userId)
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -149,30 +142,6 @@ function get(app: Hono, sourceId: string) {
|
||||
return app.request(`/api/sources/${sourceId}`, { method: "GET" })
|
||||
}
|
||||
|
||||
const TEST_ENCRYPTION_KEY = "/bv1nbzC4ozZkT/pcv5oQfl+JAMuMZDUSVDesG2dur8="
|
||||
|
||||
function createAppWithEncryptor(providers: FeedSourceProvider[], userId?: string) {
|
||||
const sessionManager = new UserSessionManager({
|
||||
providers,
|
||||
db: fakeDb,
|
||||
credentialEncryptor: new CredentialEncryptor(TEST_ENCRYPTION_KEY),
|
||||
})
|
||||
const app = new Hono()
|
||||
registerSourcesHttpHandlers(app, {
|
||||
sessionManager,
|
||||
authSessionMiddleware: mockAuthSessionMiddleware(userId),
|
||||
})
|
||||
return { app, sessionManager }
|
||||
}
|
||||
|
||||
function putCredentials(app: Hono, sourceId: string, body: unknown) {
|
||||
return app.request(`/api/sources/${sourceId}/credentials`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
function put(app: Hono, sourceId: string, body: unknown) {
|
||||
return app.request(`/api/sources/${sourceId}`, {
|
||||
method: "PUT",
|
||||
@@ -739,86 +708,3 @@ describe("PUT /api/sources/:sourceId", () => {
|
||||
expect(res.status).toBe(204)
|
||||
})
|
||||
})
|
||||
|
||||
describe("PUT /api/sources/:sourceId/credentials", () => {
|
||||
test("returns 401 without auth", async () => {
|
||||
activeStore = createInMemoryStore()
|
||||
const { app } = createAppWithEncryptor([createStubProvider("aelis.location")])
|
||||
|
||||
const res = await putCredentials(app, "aelis.location", { token: "x" })
|
||||
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
test("returns 404 for unknown source", async () => {
|
||||
activeStore = createInMemoryStore()
|
||||
const { app } = createAppWithEncryptor([createStubProvider("aelis.location")], MOCK_USER_ID)
|
||||
|
||||
const res = await putCredentials(app, "unknown.source", { token: "x" })
|
||||
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
test("returns 400 for invalid JSON", async () => {
|
||||
activeStore = createInMemoryStore()
|
||||
activeStore.seed(MOCK_USER_ID, "aelis.location")
|
||||
const { app } = createAppWithEncryptor([createStubProvider("aelis.location")], MOCK_USER_ID)
|
||||
|
||||
const res = await app.request("/api/sources/aelis.location/credentials", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: "not-json",
|
||||
})
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const body = (await res.json()) as { error: string }
|
||||
expect(body.error).toBe("Invalid JSON")
|
||||
})
|
||||
|
||||
test("returns 204 and persists credentials", async () => {
|
||||
activeStore = createInMemoryStore()
|
||||
activeStore.seed(MOCK_USER_ID, "aelis.location")
|
||||
const { app } = createAppWithEncryptor([createStubProvider("aelis.location")], MOCK_USER_ID)
|
||||
|
||||
const res = await putCredentials(app, "aelis.location", { token: "secret" })
|
||||
|
||||
expect(res.status).toBe(204)
|
||||
})
|
||||
|
||||
test("returns 400 when provider throws InvalidSourceCredentialsError", async () => {
|
||||
activeStore = createInMemoryStore()
|
||||
activeStore.seed(MOCK_USER_ID, "test.creds")
|
||||
let callCount = 0
|
||||
const provider: FeedSourceProvider = {
|
||||
sourceId: "test.creds",
|
||||
async feedSourceForUser(_userId: string, _config: unknown, _credentials: unknown) {
|
||||
callCount++
|
||||
if (callCount > 1) {
|
||||
throw new InvalidSourceCredentialsError("test.creds", "invalid token format")
|
||||
}
|
||||
return createStubSource("test.creds")
|
||||
},
|
||||
}
|
||||
const { app, sessionManager } = createAppWithEncryptor([provider], MOCK_USER_ID)
|
||||
|
||||
await sessionManager.getOrCreate(MOCK_USER_ID)
|
||||
|
||||
const res = await putCredentials(app, "test.creds", { token: "bad" })
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const body = (await res.json()) as { error: string }
|
||||
expect(body.error).toContain("invalid token format")
|
||||
})
|
||||
|
||||
test("returns 503 when credential encryption is not configured", async () => {
|
||||
activeStore = createInMemoryStore()
|
||||
activeStore.seed(MOCK_USER_ID, "aelis.location")
|
||||
const { app } = createApp([createStubProvider("aelis.location")], MOCK_USER_ID)
|
||||
|
||||
const res = await putCredentials(app, "aelis.location", { token: "x" })
|
||||
|
||||
expect(res.status).toBe(503)
|
||||
const body = (await res.json()) as { error: string }
|
||||
expect(body.error).toContain("not configured")
|
||||
})
|
||||
})
|
||||
|
||||
@@ -6,12 +6,7 @@ import { createMiddleware } from "hono/factory"
|
||||
import type { AuthSessionMiddleware } from "../auth/session-middleware.ts"
|
||||
import type { UserSessionManager } from "../session/index.ts"
|
||||
|
||||
import {
|
||||
CredentialStorageUnavailableError,
|
||||
InvalidSourceConfigError,
|
||||
InvalidSourceCredentialsError,
|
||||
SourceNotFoundError,
|
||||
} from "./errors.ts"
|
||||
import { InvalidSourceConfigError, SourceNotFoundError } from "./errors.ts"
|
||||
|
||||
type Env = {
|
||||
Variables: {
|
||||
@@ -53,12 +48,6 @@ export function registerSourcesHttpHandlers(
|
||||
app.get("/api/sources/:sourceId", inject, authSessionMiddleware, handleGetSource)
|
||||
app.patch("/api/sources/:sourceId", inject, authSessionMiddleware, handleUpdateSource)
|
||||
app.put("/api/sources/:sourceId", inject, authSessionMiddleware, handleReplaceSource)
|
||||
app.put(
|
||||
"/api/sources/:sourceId/credentials",
|
||||
inject,
|
||||
authSessionMiddleware,
|
||||
handleUpdateCredentials,
|
||||
)
|
||||
}
|
||||
|
||||
async function handleGetSource(c: Context<Env>) {
|
||||
@@ -182,43 +171,3 @@ async function handleReplaceSource(c: Context<Env>) {
|
||||
|
||||
return c.body(null, 204)
|
||||
}
|
||||
|
||||
async function handleUpdateCredentials(c: Context<Env>) {
|
||||
const sourceId = c.req.param("sourceId")
|
||||
if (!sourceId) {
|
||||
return c.body(null, 404)
|
||||
}
|
||||
|
||||
const sessionManager = c.get("sessionManager")
|
||||
|
||||
const provider = sessionManager.getProvider(sourceId)
|
||||
if (!provider) {
|
||||
return c.json({ error: `Source "${sourceId}" not found` }, 404)
|
||||
}
|
||||
|
||||
let body: unknown
|
||||
try {
|
||||
body = await c.req.json()
|
||||
} catch {
|
||||
return c.json({ error: "Invalid JSON" }, 400)
|
||||
}
|
||||
|
||||
const user = c.get("user")!
|
||||
|
||||
try {
|
||||
await sessionManager.updateSourceCredentials(user.id, sourceId, body)
|
||||
} catch (err) {
|
||||
if (err instanceof SourceNotFoundError) {
|
||||
return c.json({ error: err.message }, 404)
|
||||
}
|
||||
if (err instanceof InvalidSourceCredentialsError) {
|
||||
return c.json({ error: err.message }, 400)
|
||||
}
|
||||
if (err instanceof CredentialStorageUnavailableError) {
|
||||
return c.json({ error: err.message }, 503)
|
||||
}
|
||||
throw err
|
||||
}
|
||||
|
||||
return c.body(null, 204)
|
||||
}
|
||||
|
||||
@@ -23,11 +23,7 @@ export class TflSourceProvider implements FeedSourceProvider {
|
||||
this.client = "client" in options ? options.client : undefined
|
||||
}
|
||||
|
||||
async feedSourceForUser(
|
||||
_userId: string,
|
||||
config: unknown,
|
||||
_credentials: unknown,
|
||||
): Promise<TflSource> {
|
||||
async feedSourceForUser(_userId: string, config: unknown): Promise<TflSource> {
|
||||
const parsed = tflConfig(config)
|
||||
if (parsed instanceof type.errors) {
|
||||
throw new Error(`Invalid TFL config: ${parsed.summary}`)
|
||||
|
||||
@@ -26,11 +26,7 @@ export class WeatherSourceProvider implements FeedSourceProvider {
|
||||
this.client = options.client
|
||||
}
|
||||
|
||||
async feedSourceForUser(
|
||||
_userId: string,
|
||||
config: unknown,
|
||||
_credentials: unknown,
|
||||
): Promise<WeatherSource> {
|
||||
async feedSourceForUser(_userId: string, config: unknown): Promise<WeatherSource> {
|
||||
const parsed = weatherConfig(config)
|
||||
if (parsed instanceof type.errors) {
|
||||
throw new Error(`Invalid weather config: ${parsed.summary}`)
|
||||
|
||||
13
bun.lock
13
bun.lock
@@ -7,7 +7,7 @@
|
||||
"devDependencies": {
|
||||
"@json-render/core": "^0.12.1",
|
||||
"@nym.sh/jrx": "^0.2.0",
|
||||
"@types/bun": "^1.3.12",
|
||||
"@types/bun": "latest",
|
||||
"oxfmt": "^0.24.0",
|
||||
"oxlint": "^1.39.0",
|
||||
},
|
||||
@@ -55,6 +55,7 @@
|
||||
"@aelis/source-location": "workspace:*",
|
||||
"@aelis/source-tfl": "workspace:*",
|
||||
"@aelis/source-weatherkit": "workspace:*",
|
||||
"@openrouter/sdk": "^0.9.11",
|
||||
"arktype": "^2.1.29",
|
||||
"better-auth": "^1",
|
||||
"drizzle-orm": "^0.45.1",
|
||||
@@ -767,6 +768,8 @@
|
||||
|
||||
"@open-draft/until": ["@open-draft/until@2.1.0", "", {}, "sha512-U69T3ItWHvLwGg5eJ0n3I62nWuE6ilHlmz7zM0npLBRvPRd7e6NYmg54vvRtP5mZG7kZqZCFVdsTWo7BPtBujg=="],
|
||||
|
||||
"@openrouter/sdk": ["@openrouter/sdk@0.9.11", "", { "dependencies": { "zod": "^3.25.0 || ^4.0.0" } }, "sha512-BgFu6NcIJO4a9aVjr04y3kZ8pyM71j15I+bzfVAGEvxnj+KQNIkBYQGgwrG3D+aT1QpDKLki8btcQmpaxUas6A=="],
|
||||
|
||||
"@oxfmt/darwin-arm64": ["@oxfmt/darwin-arm64@0.24.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-aYXuGf/yq8nsyEcHindGhiz9I+GEqLkVq8CfPbd+6VE259CpPEH+CaGHEO1j6vIOmNr8KHRq+IAjeRO2uJpb8A=="],
|
||||
|
||||
"@oxfmt/darwin-x64": ["@oxfmt/darwin-x64@0.24.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-vs3b8Bs53hbiNvcNeBilzE/+IhDTWKjSBB3v/ztr664nZk65j0xr+5IHMBNz3CFppmX7o/aBta2PxY+t+4KoPg=="],
|
||||
@@ -1369,7 +1372,7 @@
|
||||
|
||||
"@types/babel__traverse": ["@types/babel__traverse@7.28.0", "", { "dependencies": { "@babel/types": "^7.28.2" } }, "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q=="],
|
||||
|
||||
"@types/bun": ["@types/bun@1.3.12", "", { "dependencies": { "bun-types": "1.3.12" } }, "sha512-DBv81elK+/VSwXHDlnH3Qduw+KxkTIWi7TXkAeh24zpi5l0B2kUg9Ga3tb4nJaPcOFswflgi/yAvMVBPrxMB+A=="],
|
||||
"@types/bun": ["@types/bun@1.3.10", "", { "dependencies": { "bun-types": "1.3.10" } }, "sha512-0+rlrUrOrTSskibryHbvQkDOWRJwJZqZlxrUs1u4oOoTln8+WIXBPmAuCF35SWB2z4Zl3E84Nl/D0P7803nigQ=="],
|
||||
|
||||
"@types/bunyan": ["@types/bunyan@1.8.11", "", { "dependencies": { "@types/node": "*" } }, "sha512-758fRH7umIMk5qt5ELmRMff4mLDlN+xyYzC+dkPTdKwbSkJFvz6xwyScrytPU0QIBbRRwbiE8/BIg8bpajerNQ=="],
|
||||
|
||||
@@ -1661,7 +1664,7 @@
|
||||
|
||||
"buffer-from": ["buffer-from@1.1.2", "", {}, "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ=="],
|
||||
|
||||
"bun-types": ["bun-types@1.3.12", "", { "dependencies": { "@types/node": "*" } }, "sha512-HqOLj5PoFajAQciOMRiIZGNoKxDJSr6qigAttOX40vJuSp6DN/CxWp9s3C1Xwm4oH7ybueITwiaOcWXoYVoRkA=="],
|
||||
"bun-types": ["bun-types@1.3.10", "", { "dependencies": { "@types/node": "*" } }, "sha512-tcpfCCl6XWo6nCVnpcVrxQ+9AYN1iqMIzgrSKYMB/fjLtV2eyAVEg7AxQJuCq/26R6HpKWykQXuSOq/21RYcbg=="],
|
||||
|
||||
"bundle-name": ["bundle-name@4.1.0", "", { "dependencies": { "run-applescript": "^7.0.0" } }, "sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q=="],
|
||||
|
||||
@@ -3929,6 +3932,8 @@
|
||||
|
||||
"body-parser/raw-body": ["raw-body@2.5.3", "", { "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", "iconv-lite": "~0.4.24", "unpipe": "~1.0.0" } }, "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA=="],
|
||||
|
||||
"bun-types/@types/node": ["@types/node@22.19.15", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-F0R/h2+dsy5wJAUe3tAU6oqa2qbWY5TpNfL/RGmo1y38hiyO1w3x2jPtt76wmuaJI4DQnOBu21cNXQ2STIUUWg=="],
|
||||
|
||||
"c12/dotenv": ["dotenv@16.6.1", "", {}, "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow=="],
|
||||
|
||||
"c12/jiti": ["jiti@2.6.1", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ=="],
|
||||
@@ -4549,6 +4554,8 @@
|
||||
|
||||
"body-parser/debug/ms": ["ms@2.0.0", "", {}, "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="],
|
||||
|
||||
"bun-types/@types/node/undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"chrome-launcher/@types/node/undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"chromium-edge-launcher/@types/node/undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
"devDependencies": {
|
||||
"@json-render/core": "^0.12.1",
|
||||
"@nym.sh/jrx": "^0.2.0",
|
||||
"@types/bun": "^1.3.12",
|
||||
"@types/bun": "latest",
|
||||
"oxfmt": "^0.24.0",
|
||||
"oxlint": "^1.39.0"
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user