| 1 | import { Service } from '@deepseek-ai/cordis' |
| 2 | import { ErrorCode } from '../protocol.ts' |
| 3 | import { RpcError } from '../rpc.ts' |
| 4 | import type { AdapterHost, DshAdapter } from './adapters.ts' |
| 5 | |
| 6 | export const CREDENTIAL_HANDLE_PREFIX = 'codewhale-credential:' |
| 7 | |
| 8 | interface BrokeredResponse { |
| 9 | status: number |
| 10 | url: string |
| 11 | redirected: boolean |
| 12 | headers: [string, string][] |
| 13 | body_base64: string |
| 14 | } |
| 15 | |
| 16 | function credentialRef(ref: unknown): string { |
| 17 | if (typeof ref !== 'string' || ref.length === 0) throw new RpcError(ErrorCode.InvalidParams, 'a credential ref is a non-empty string') |
| 18 | return ref |
| 19 | } |
| 20 | |
| 21 | function credentialSite(site: unknown): string { |
| 22 | let url: URL |
| 23 | try { |
| 24 | url = new URL(String(site)) |
| 25 | } catch { |
| 26 | throw new RpcError(ErrorCode.InvalidParams, 'a credential is stored for one https site, such as https://api.example.com') |
| 27 | } |
| 28 | if (typeof site !== 'string' || url.protocol !== 'https:' || url.username !== '' || url.password !== '' || url.pathname !== '/' || url.search !== '' || url.hash !== '') { |
| 29 | throw new RpcError(ErrorCode.InvalidParams, 'a credential is stored for one https site, such as https://api.example.com') |
| 30 | } |
| 31 | return url.origin |
| 32 | } |
| 33 | |
| 34 | function brokered(value: unknown): BrokeredResponse { |
| 35 | const response = value as Partial<BrokeredResponse> | null |
| 36 | if (response === null || typeof response !== 'object' || typeof response.status !== 'number' || typeof response.url !== 'string' |
| 37 | || typeof response.body_base64 !== 'string' || !Array.isArray(response.headers)) { |
| 38 | throw new RpcError(ErrorCode.Internal, 'invalid network broker response') |
| 39 | } |
| 40 | return response as BrokeredResponse |
| 41 | } |
| 42 | |
| 43 | async function requestBody(body: unknown): Promise<string | undefined> { |
| 44 | if (body === undefined || body === null) return undefined |
| 45 | if (typeof body === 'string') return Buffer.from(body, 'utf8').toString('base64') |
| 46 | if (body instanceof ArrayBuffer) return Buffer.from(body).toString('base64') |
| 47 | if (ArrayBuffer.isView(body)) return Buffer.from(body.buffer, body.byteOffset, body.byteLength).toString('base64') |
| 48 | if (body instanceof URLSearchParams) return Buffer.from(body.toString(), 'utf8').toString('base64') |
| 49 | if (body instanceof Blob) return Buffer.from(await body.arrayBuffer()).toString('base64') |
| 50 | throw new RpcError(ErrorCode.InvalidParams, 'the network broker sends string, binary, URLSearchParams or Blob bodies') |
| 51 | } |
| 52 | |
| 53 | export async function brokeredFetch(host: AdapterHost, ctx: unknown, input: string | URL | Request, init: RequestInit = {}): Promise<Response> { |
| 54 | const request = input instanceof Request ? input : undefined |
| 55 | const url = request?.url ?? String(input) |
| 56 | const headers = new Headers(request?.headers) |
| 57 | new Headers(init.headers).forEach((value, name) => headers.set(name, value)) |
| 58 | const body = init.body !== undefined ? init.body : request !== undefined && request.body !== null ? await request.arrayBuffer() : undefined |
| 59 | const result = brokered(await host.broker(ctx, 'network', 'fetch', { |
| 60 | url, |
| 61 | method: init.method ?? request?.method ?? 'GET', |
| 62 | headers: [...headers.entries()], |
| 63 | body_base64: await requestBody(body), |
| 64 | })) |
| 65 | const bytes = Buffer.from(result.body_base64, 'base64') |
| 66 | const nullBody = [101, 204, 205, 304].includes(result.status) |
| 67 | const response = new Response(nullBody ? null : bytes, { status: result.status, headers: result.headers }) |
| 68 | Object.defineProperty(response, 'url', { value: result.url }) |
| 69 | Object.defineProperty(response, 'redirected', { value: result.redirected === true }) |
| 70 | return response |
| 71 | } |
| 72 | |
| 73 | export const credentialsAdapter: DshAdapter = { |
| 74 | service: 'credentials', |
| 75 | define(host) { |
| 76 | class CredentialsService extends Service { |
| 77 | constructor(ctx: any) { super(ctx, 'credentials') } |
| 78 | |
| 79 | async resolve(ref: unknown): Promise<{ value: string } | undefined> { |
| 80 | const result = await host.broker(this.ctx, 'network', 'credentials.resolve', { ref: credentialRef(ref) }) as { value?: unknown } | null |
| 81 | const value = result?.value |
| 82 | if (value === null || value === undefined) return undefined |
| 83 | if (typeof value !== 'string' || !value.startsWith(CREDENTIAL_HANDLE_PREFIX)) throw new RpcError(ErrorCode.Internal, 'invalid credential handle') |
| 84 | return { value } |
| 85 | } |
| 86 | |
| 87 | async describe(ref: unknown): Promise<{ ref: string, set: boolean, site?: string }> { |
| 88 | const result = await host.broker(this.ctx, 'network', 'credentials.describe', { ref: credentialRef(ref) }) as { ref?: unknown, set?: unknown, site?: unknown } | null |
| 89 | if (result === null || typeof result !== 'object' || typeof result.set !== 'boolean') throw new RpcError(ErrorCode.Internal, 'invalid credential description') |
| 90 | return typeof result.site === 'string' ? { ref: credentialRef(ref), set: result.set, site: result.site } : { ref: credentialRef(ref), set: result.set } |
| 91 | } |
| 92 | |
| 93 | async set(ref: unknown, value: unknown, site: unknown): Promise<void> { |
| 94 | if (typeof value !== 'string' || value.length === 0) throw new RpcError(ErrorCode.InvalidParams, 'a credential value is a non-empty string') |
| 95 | await host.broker(this.ctx, 'network', 'credentials.set', { ref: credentialRef(ref), value, site: credentialSite(site) }) |
| 96 | } |
| 97 | |
| 98 | fetch(input: string | URL | Request, init?: RequestInit): Promise<Response> { |
| 99 | return brokeredFetch(host, this.ctx, input, init) |
| 100 | } |
| 101 | } |
| 102 | Object.freeze(CredentialsService.prototype) |
| 103 | return CredentialsService |
| 104 | }, |
| 105 | } |
| 106 |