Skip to content

armgit / hypit

Public Imported from GitHub
0

Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.

fix(credentials): rotate OAuth through declared endpoint slots

kashorin6c2fae51b0cf
diff --git a/packages/cli/src/oauth.ts b/packages/cli/src/oauth.ts
index 5c9384c5..b97f141d 100644
--- a/packages/cli/src/oauth.ts
+++ b/packages/cli/src/oauth.ts
@@ -3,6 +3,7 @@ import { createServer } from "node:http";
import { spawn } from "node:child_process";
import type { CredentialAcquisition } from "@hypit/runtime";
+import { encodeOAuth2Credential } from "@hypit/runtime";
import type { CliIo } from "./output.js";
@@ -10,6 +11,17 @@ function base64url(bytes: Uint8Array): string {
return Buffer.from(bytes).toString("base64").replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "");
}
+function positiveNumber(value: unknown): number | undefined {
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined;
+}
+
+function tokenExpiry(value: { readonly expires_at?: unknown; readonly expires_in?: unknown }): number | undefined {
+ const absolute = positiveNumber(value.expires_at);
+ if (absolute !== undefined) return absolute > 10_000_000_000 ? absolute : absolute * 1_000;
+ const seconds = positiveNumber(value.expires_in);
+ return seconds === undefined ? undefined : Date.now() + seconds * 1_000;
+}
+
/** Acquire one OAuth credential from the exact data declared by its Endpoint package. */
export async function acquireOAuthCredential(
io: CliIo,
@@ -93,11 +105,23 @@ export async function acquireOAuthCredential(
});
const body = await tokenResponse.text();
if (!tokenResponse.ok) throw new Error(`OAuth token exchange failed (${tokenResponse.status}): ${body.slice(0, 200)}`);
- const parsed = JSON.parse(body) as { access_token?: unknown };
+ const parsed = JSON.parse(body) as {
+ readonly access_token?: unknown;
+ readonly refresh_token?: unknown;
+ readonly expires_at?: unknown;
+ readonly expires_in?: unknown;
+ };
if (typeof parsed.access_token !== "string" || parsed.access_token.length === 0) {
throw new Error("OAuth token response contained no access token");
}
- return parsed.access_token;
+ const expiresAt = tokenExpiry(parsed);
+ return encodeOAuth2Credential({
+ accessToken: parsed.access_token,
+ ...(typeof parsed.refresh_token === "string" && parsed.refresh_token.length > 0
+ ? { refreshToken: parsed.refresh_token }
+ : {}),
+ ...(expiresAt === undefined ? {} : { expiresAt }),
+ });
}
function callbackPage(success: boolean): string {
diff --git a/packages/credential-store-os/runtime/windows-credential.ps1 b/packages/credential-store-os/runtime/windows-credential.ps1
index ce87d5b2..4117b3a8 100644
--- a/packages/credential-store-os/runtime/windows-credential.ps1
+++ b/packages/credential-store-os/runtime/windows-credential.ps1
@@ -16,7 +16,9 @@ function Find-Credential {
try {
return $vault.Retrieve([string]$request.service, [string]$request.account)
} catch {
- if ($_.Exception.HResult -eq $notFound) { return $null }
+ if ($_.Exception.HResult -eq $notFound -or $_.Exception.InnerException.HResult -eq $notFound) {
+ return $null
+ }
throw
}
}
diff --git a/packages/driver-node/src/driver.ts b/packages/driver-node/src/driver.ts
index 473371c0..c9191f08 100644
--- a/packages/driver-node/src/driver.ts
+++ b/packages/driver-node/src/driver.ts
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
import { reduce, resolveNeedCommand, resolveProducer } from "@hypit/core";
import type { ProducerHandlerResult } from "@hypit/component-kit";
-import type { EndpointFulfillment, EndpointOutcome } from "@hypit/endpoint-kit";
+import type { EndpointCredential, EndpointFulfillment, EndpointOutcome } from "@hypit/endpoint-kit";
import { endpointResourceClaims } from "@hypit/endpoint-kit";
import type {
BuildState,
@@ -28,6 +28,7 @@ import type {
RuntimePreparation,
RuntimeRunnableCommand,
} from "@hypit/runtime";
+import { writableCredentialStore } from "@hypit/runtime";
import { MemoryResourceStore } from "./resources.js";
import {
@@ -115,13 +116,13 @@ export class NodeDriver {
async #endpointCredentials(
registration: EndpointRegistration,
- ): Promise<Readonly<Record<string, CredentialValue>>> {
+ ): Promise<Readonly<Record<string, EndpointCredential>>> {
const requested = registration.credentials ?? {};
if (Object.keys(requested).length === 0) return {};
if (this.credentials === undefined) {
throw new Error(`Endpoint ${registration.id} requires a CredentialStore`);
}
- const resolved: Record<string, CredentialValue> = {};
+ const resolved: Record<string, EndpointCredential> = {};
for (const slot of Object.keys(requested).sort()) {
const ref = requested[slot]!;
const key = JSON.stringify([ref.store, ref.key]);
@@ -134,7 +135,13 @@ export class NodeDriver {
if (value === undefined) {
throw new Error(`Endpoint ${registration.id} credential ${slot} is unavailable from ${ref.store}:${ref.key}`);
}
- resolved[slot] = value;
+ const writable = await writableCredentialStore(this.credentials, ref);
+ resolved[slot] = {
+ ...value,
+ ...(writable === undefined ? {} : {
+ replace: async (replacement: CredentialValue) => await writable.put(ref, replacement),
+ }),
+ };
}
return resolved;
}
diff --git a/packages/driver-node/test/driver.test.ts b/packages/driver-node/test/driver.test.ts
index 77db795c..c484b1c0 100644
--- a/packages/driver-node/test/driver.test.ts
+++ b/packages/driver-node/test/driver.test.ts
@@ -9,6 +9,7 @@ import {
EndpointRegistry,
} from "@hypit/driver-node";
import { credentialRef } from "@hypit/runtime";
+import type { WritableCredentialStore } from "@hypit/runtime";
import { capabilities, createGreetingBuild, producers as greetingProducers, types } from "../../core/test/greeting-fixture.js";
@@ -147,6 +148,37 @@ test("an Endpoint receives only declared credential slots and secrets never ente
assert.equal(JSON.stringify(completed.state).includes("top-secret-value"), false);
});
+test("a writable credential gives its Endpoint authority to replace only that declared slot", async () => {
+ const { producers, endpoints } = configuredRegistry();
+ let stored = "old-secret";
+ endpoints.registerImmediateEndpoint(
+ "example:credential-rotation",
+ capabilities.generation,
+ types.generated,
+ async ({ credentials }) => {
+ assert.equal(typeof credentials.apiKey?.replace, "function");
+ await credentials.apiKey!.replace!({ secret: "new-secret" });
+ assert.equal("credentialStore" in credentials.apiKey!, false);
+ return { value: { kind: "inline", value: "Credentialed result" } };
+ },
+ { credentials: { apiKey: credentialRef("test", "endpoint-key") } },
+ );
+ const credentialStore: WritableCredentialStore = {
+ owns(ref) { return ref.store === "test"; },
+ async resolve() { return { secret: stored }; },
+ async put(_ref, value) { stored = value.secret; },
+ async delete() { return false; },
+ };
+ const driver = new NodeDriver({
+ producers,
+ endpoints,
+ credentials: credentialStore,
+ });
+ const completed = await driver.run(createGreetingBuild());
+ assert.equal(completed.status, "complete");
+ assert.equal(stored, "new-secret");
+});
+
test("Endpoint capabilities may narrow themselves with typed Need constraints", async () => {
const { producers, endpoints } = configuredRegistry();
endpoints.registerImmediateEndpoint("example:wrong-model", capabilities.generation, types.generated, () => {
diff --git a/packages/endpoint-kit/src/index.ts b/packages/endpoint-kit/src/index.ts
index a5f1427e..21c3033d 100644
--- a/packages/endpoint-kit/src/index.ts
+++ b/packages/endpoint-kit/src/index.ts
@@ -43,12 +43,17 @@ export type EndpointRequest = {
readonly pendingInputs?: readonly EndpointInputSlot[];
};
+export type EndpointCredential = CredentialValue & {
+ /** Narrow write authority for this declared slot only, when its selected Store is writable. */
+ readonly replace?: (value: CredentialValue) => Promise<void>;
+};
+
export type EndpointInvocationContext = {
readonly command: FulfillNeedCommand;
readonly need: Need;
readonly resources: ResourceStore;
/** Only slots explicitly declared by this configured Endpoint instance are present. */
- readonly credentials: Readonly<Record<string, CredentialValue>>;
+ readonly credentials: Readonly<Record<string, EndpointCredential>>;
};
export type ImmediateEndpointHandler = (
diff --git a/packages/provider-hypihub/README.md b/packages/provider-hypihub/README.md
index 6640093e..91a24489 100644
--- a/packages/provider-hypihub/README.md
+++ b/packages/provider-hypihub/README.md
@@ -35,9 +35,9 @@ Gemini VLM is exposed as the Provider-neutral `@hypit/gemini` Runtime capability
transcription is exposed as the same `@hypit/whisperx` alignment capability implemented by the local
WhisperX Provider. An Author
Source can select the exact model while the Runtime chooses HypiHub or Vertex. Existing embedded
-callers can still use the exported `createHypiHubGeminiGenerator`. Run `hypit auth login hypihub.default --runtime hypit.runtime.json` to sign in with HypiHub OAuth (and optionally set `HYPIHUB_BASE_URL`; either the origin or
-an existing `/v1`/`/v1beta` base is accepted) only when choosing HypiHub. The Runtime Provider also
-accepts the origin or either versioned base and normalizes it to `/v1`; missing or insufficient user
+callers can still use the exported `createHypiHubGeminiGenerator`. Run `hypit auth login hypihub.default --runtime hypit.runtime.json` to sign in with HypiHub OAuth only when choosing HypiHub. A Profile may set `baseUrl`
+to the selected deployment's origin or an existing `/v1`/`/v1beta` base. The Runtime Provider
+normalizes it to `/v1`; missing or insufficient user
credentials should be resolved at [hypit.ai](https://hypit.ai). Referenced image, audio and video
Resources are uploaded through a session from `POST /v1/files/uploads`, followed by the private
regional multipart instructions returned by HypiHub. The Provider follows the server-selected part
@@ -46,6 +46,12 @@ one upload, and then passes the returned HTTPS URL to generation, Gemini or tran
Resource identity is uploaded once within one Runtime operation. Hypit keeps no upload catalog or
cross-Build cache. Embedded callers may replace this transport with `publicAssetUrl`.
+OAuth login stores the access token, refresh token and expiry as one opaque credential value. The
+Provider refreshes that value shortly before expiry or after an unauthorised response when the
+selected Store is writable. Its Endpoint receives only the credential slot it declared and a narrow
+operation for replacing that same slot; it cannot enumerate the Store, choose another key or read
+another Endpoint's credentials. A raw credential remains an ordinary static API key.
+
The service currently requires whole-file and per-part SHA-256 values as fields of its signed upload
protocol. They exist only while transferring bytes; Hypit never uses them as Resource identity,
Result metadata, lookup keys or reuse evidence. Signed URLs and their query credentials are removed
diff --git a/packages/provider-hypihub/src/oauth.ts b/packages/provider-hypihub/src/oauth.ts
new file mode 100644
index 00000000..f3642613
--- /dev/null
+++ b/packages/provider-hypihub/src/oauth.ts
@@ -0,0 +1,113 @@
+import type { EndpointCredential } from "@hypit/endpoint-kit";
+import { decodeOAuth2Credential, encodeOAuth2Credential } from "@hypit/runtime";
+import { requestDeadline } from "@hypit/runtime-kit";
+
+const OAUTH_CLIENT_ID = "hyc_d5d5e8e7131b0c877756e66c";
+const REFRESH_SKEW_MS = 60_000;
+
+type OAuthTokenResponse = {
+ readonly access_token?: unknown;
+ readonly refresh_token?: unknown;
+ readonly expires_in?: unknown;
+ readonly expires_at?: unknown;
+};
+
+function assert(condition: unknown, message: string): asserts condition {
+ if (!condition) throw new Error(message);
+}
+
+function positiveNumber(value: unknown): number | undefined {
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined;
+}
+
+function tokenExpiry(value: OAuthTokenResponse): number | undefined {
+ const absolute = positiveNumber(value.expires_at);
+ if (absolute !== undefined) return absolute > 10_000_000_000 ? absolute : absolute * 1_000;
+ const seconds = positiveNumber(value.expires_in);
+ return seconds === undefined ? undefined : Date.now() + seconds * 1_000;
+}
+
+export type HypiHubAuth = {
+ token(): Promise<string>;
+ canRefresh(): boolean;
+ refresh(): Promise<string>;
+};
+
+/**
+ * Interpret one declared HypiHub credential. Raw values are ordinary static API keys. OAuth values
+ * use the host-neutral credential envelope written by the CLI. Rotation can replace only this
+ * credential slot; the Provider never receives a CredentialStore or another credential reference.
+ */
+export function createHypiHubAuth(options: {
+ readonly credential: EndpointCredential;
+ readonly baseUrl: string;
+ readonly requestTimeoutMs: number;
+ readonly fetch: typeof globalThis.fetch;
+}): HypiHubAuth {
+ const decoded = decodeOAuth2Credential(options.credential.secret);
+ let accessToken = decoded?.accessToken ?? options.credential.secret;
+ let refreshToken = decoded?.refreshToken;
+ let expiresAt = decoded?.expiresAt;
+ let refreshing: Promise<string> | undefined;
+ const tokenEndpoint = new URL("/oauth/token", new URL(options.baseUrl).origin).toString();
+
+ const refresh = async (): Promise<string> => {
+ if (refreshing !== undefined) return await refreshing;
+ if (refreshToken === undefined) throw new Error("HypiHub credential has no refresh token; run hypit auth login");
+ const replace = options.credential.replace;
+ if (replace === undefined) {
+ throw new Error("HypiHub OAuth credential is read-only; run hypit auth login with a writable Credential Store");
+ }
+ refreshing = (async () => {
+ const deadline = requestDeadline(options.requestTimeoutMs);
+ try {
+ const response = await deadline.wait(options.fetch(tokenEndpoint, {
+ method: "POST",
+ headers: { "content-type": "application/x-www-form-urlencoded" },
+ body: new URLSearchParams({
+ grant_type: "refresh_token",
+ refresh_token: refreshToken!,
+ client_id: OAUTH_CLIENT_ID,
+ }),
+ signal: deadline.signal,
+ }));
+ const text = await deadline.wait(response.text());
+ let body: OAuthTokenResponse;
+ try { body = JSON.parse(text) as OAuthTokenResponse; }
+ catch { throw new Error(`HypiHub OAuth refresh returned invalid JSON (${response.status})`); }
+ if (!response.ok) throw new Error(`HypiHub OAuth refresh failed (${response.status}): ${text.slice(0, 200)}`);
+ assert(typeof body.access_token === "string" && body.access_token.length > 0,
+ "HypiHub OAuth refresh returned no access token");
+ accessToken = body.access_token;
+ if (typeof body.refresh_token === "string" && body.refresh_token.length > 0) {
+ refreshToken = body.refresh_token;
+ }
+ expiresAt = tokenExpiry(body);
+ await replace({
+ secret: encodeOAuth2Credential({
+ accessToken,
+ ...(refreshToken === undefined ? {} : { refreshToken }),
+ ...(expiresAt === undefined ? {} : { expiresAt }),
+ }),
+ ...(expiresAt === undefined ? {} : { expiresAt }),
+ });
+ return accessToken;
+ } finally {
+ deadline.finish();
+ }
+ })();
+ try { return await refreshing; }
+ finally { refreshing = undefined; }
+ };
+
+ return {
+ async token() {
+ if (expiresAt !== undefined && expiresAt <= Date.now() + REFRESH_SKEW_MS) return await refresh();
+ return accessToken;
+ },
+ canRefresh() {
+ return refreshToken !== undefined && options.credential.replace !== undefined;
+ },
+ refresh,
+ };
+}
diff --git a/packages/provider-hypihub/src/provider.ts b/packages/provider-hypihub/src/provider.ts
index a0d8b141..ef02cc5d 100644
--- a/packages/provider-hypihub/src/provider.ts
+++ b/packages/provider-hypihub/src/provider.ts
@@ -19,6 +19,8 @@ import { createHypiHubGeminiGenerator } from "./gemini.js";
import { hypiHubRouteForCapability, hypiHubRoutes } from "./routes.js";
import { HypiHubUploader } from "./upload.js";
import type { RuntimeDoctorDiagnostic } from "@hypit/runtime-kit";
+import { createHypiHubAuth } from "./oauth.js";
+import type { HypiHubAuth } from "./oauth.js";
export const hypiHubProviderModuleRef = { name: "@hypit/provider-hypihub", version: "1" } as const;
@@ -59,10 +61,10 @@ function apiBaseUrl(value: string): string {
const origin = trimmed.replace(/\/(?:v1beta|v1)$/iu, "");
return `${origin}/v1`;
}
-function credential(context: EndpointInvocationContext): string {
+function credential(context: EndpointInvocationContext) {
const value = context.credentials.apiKey?.secret;
assert(typeof value === "string" && value.length > 0, "HypiHub login is unavailable; run hypit auth login for HypiHub");
- return value;
+ return context.credentials.apiKey!;
}
function guidedMessage(error: unknown): string {
const message = error instanceof Error ? error.message : String(error);
@@ -88,8 +90,8 @@ function jobId(value: Record<string, unknown>): string {
type HypiHubModelOperation = "images" | "image_edits" | "videos" | "audio_speech" | "transcriptions" | "gemini";
-async function verifyModelRoute(client: HypiHubClient, apiKey: string, model: string, operation: HypiHubModelOperation): Promise<void> {
- const card = await client.json(`/models/${encodeURIComponent(model)}`, apiKey);
+async function verifyModelRoute(client: HypiHubClient, auth: HypiHubAuth, model: string, operation: HypiHubModelOperation): Promise<void> {
+ const card = await client.json(`/models/${encodeURIComponent(model)}`, auth);
const endpoints = card.endpoints;
assert(Array.isArray(endpoints) && endpoints.includes(operation),
`HypiHub model ${model} is not enabled for ${operation} with this API key`);
@@ -125,11 +127,15 @@ class HypiHubClient {
fetch: this.fetcher,
});
}
- async json(path: string, apiKey: string, init: RequestInit = {}): Promise<Record<string, unknown>> {
+ async json(path: string, auth: HypiHubAuth, init: RequestInit = {}, refreshOnUnauthorized = true): Promise<Record<string, unknown>> {
const deadline = requestDeadline(this.timeout);
try {
- const response = await deadline.wait(this.fetcher(`${this.baseUrl}${path}`, { ...init, signal: deadline.signal, headers: { authorization: `Bearer ${apiKey}`, ...(init.headers ?? {}) } }));
+ const response = await deadline.wait(this.fetcher(`${this.baseUrl}${path}`, { ...init, signal: deadline.signal, headers: { authorization: `Bearer ${await auth.token()}`, ...(init.headers ?? {}) } }));
const text = await deadline.wait(response.text()); let body: unknown = {};
+ if (response.status === 401 && refreshOnUnauthorized && auth.canRefresh()) {
+ await auth.refresh();
+ return await this.json(path, auth, init, false);
+ }
if (!response.ok) throw new HypiHubHttpError(response.status, `HypiHub returned HTTP ${response.status}: ${text.slice(0, 300)}`);
try { body = text.length === 0 ? {} : JSON.parse(text); } catch { throw new Error(`HypiHub returned invalid JSON (${response.status})`); }
return object(body, "HypiHub response");
@@ -151,29 +157,41 @@ class HypiHubClient {
}
throw lastError instanceof Error ? lastError : new Error(String(lastError));
}
- async upload(artifact: BlobRef, resources: ResourceStore, apiKey: string): Promise<string> {
+ async upload(artifact: BlobRef, resources: ResourceStore, auth: HypiHubAuth, refreshOnUnauthorized = true): Promise<string> {
const bytes = await resources.get(artifact.resource);
assert(bytes !== undefined, `HypiHub reference artifact ${artifact.resource} is unavailable`);
assert(bytes.byteLength === artifact.size, `HypiHub reference artifact ${artifact.resource} size differs`);
- return await this.uploader.upload({ bytes, mediaType: artifact.mediaType }, apiKey);
+ try {
+ return await this.uploader.upload({ bytes, mediaType: artifact.mediaType }, await auth.token());
+ } catch (error) {
+ if (refreshOnUnauthorized && auth.canRefresh() && /HTTP 401\b/u.test(error instanceof Error ? error.message : String(error))) {
+ await auth.refresh();
+ return await this.upload(artifact, resources, auth, false);
+ }
+ throw error;
+ }
}
- async transcribe(body: Record<string, unknown>, apiKey: string): Promise<Record<string, unknown>> {
- return await this.json("/audio/transcriptions", apiKey, {
+ async transcribe(body: Record<string, unknown>, auth: HypiHubAuth): Promise<Record<string, unknown>> {
+ return await this.json("/audio/transcriptions", auth, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
}
- async speech(apiKey: string, body: Record<string, unknown>): Promise<readonly { readonly bytes: Uint8Array; readonly mediaType: string }[]> {
+ async speech(auth: HypiHubAuth, body: Record<string, unknown>, refreshOnUnauthorized = true): Promise<readonly { readonly bytes: Uint8Array; readonly mediaType: string }[]> {
const deadline = requestDeadline(this.timeout);
try {
const response = await deadline.wait(this.fetcher(`${this.baseUrl}/audio/speech`, {
method: "POST",
- headers: { authorization: `Bearer ${apiKey}`, "content-type": "application/json" },
+ headers: { authorization: `Bearer ${await auth.token()}`, "content-type": "application/json" },
body: JSON.stringify({ ...body, output: "b64_json" }),
signal: deadline.signal,
}));
const bytes = new Uint8Array(await deadline.wait(response.arrayBuffer()));
+ if (response.status === 401 && refreshOnUnauthorized && auth.canRefresh()) {
+ await auth.refresh();
+ return await this.speech(auth, body, false);
+ }
if (!response.ok) {
throw new Error(`HypiHub returned HTTP ${response.status}: ${Buffer.from(bytes).toString("utf8").slice(0, 300)}`);
}
@@ -210,6 +228,15 @@ class HypiHubClient {
}
}
+function authFor(context: EndpointInvocationContext, client: HypiHubClient): HypiHubAuth {
+ return createHypiHubAuth({
+ credential: credential(context),
+ baseUrl: client.baseUrl,
+ requestTimeoutMs: client.timeout,
+ fetch: client.fetcher,
+ });
+}
+
function cardEndpoints(card: Record<string, unknown> | undefined): readonly string[] {
return Array.isArray(card?.endpoints)
? card.endpoints.filter((item): item is string => typeof item === "string")
@@ -234,7 +261,13 @@ export async function diagnoseHypiHubProvider(
downloadAttempts: options.downloadAttempts ?? 3,
fetcher: options.fetch ?? globalThis.fetch,
});
- const response = await client.json("/models", apiKey);
+ const auth = createHypiHubAuth({
+ credential: { secret: apiKey },
+ baseUrl: client.baseUrl,
+ requestTimeoutMs: client.timeout,
+ fetch: client.fetcher,
+ });
+ const response = await client.json("/models", auth);
assert(Array.isArray(response.data), "HypiHub model catalogue has no data array");
const cards = new Map<string, Record<string, unknown>>();
for (const value of response.data) {
@@ -281,8 +314,8 @@ function generationOperation(route: (typeof hypiHubRoutes)[number], input: Recor
return hasReferences ? "image_edits" : "images";
}
-async function complete(client: HypiHubClient, apiKey: string, route: (typeof hypiHubRoutes)[number], id: string, artifacts: ResourceStore): Promise<EndpointOutcome> {
- const response = await client.json(`/jobs/${encodeURIComponent(id)}/assets`, apiKey); const items = response.items;
+async function complete(client: HypiHubClient, auth: HypiHubAuth, route: (typeof hypiHubRoutes)[number], id: string, artifacts: ResourceStore): Promise<EndpointOutcome> {
+ const response = await client.json(`/jobs/${encodeURIComponent(id)}/assets`, auth); const items = response.items;
assert(Array.isArray(items) && items.length > 0, "HypiHub job has no assets"); const blobs: BlobRef[] = [];
for (const item of items) { const asset = object(item, "HypiHub asset"); assert(typeof asset.url === "string", "HypiHub asset has no URL"); const downloaded = await client.download(asset.url); blobs.push(await artifacts.put(downloaded.bytes, downloaded.mediaType)); }
return { status: "completed", result: { value: route.packageResult(blobs) } };
@@ -291,11 +324,12 @@ async function complete(client: HypiHubClient, apiKey: string, route: (typeof hy
async function synthesizeAudio(client: HypiHubClient, context: EndpointInvocationContext, publicAssetUrl: CreateHypiHubProviderOptions["publicAssetUrl"]): Promise<EndpointFulfillment> {
const route = hypiHubRouteForCapability(context.need.capability);
assert(route !== undefined && route.media === "audio", "HypiHub does not implement this exact capability");
+ const auth = authFor(context, client);
const compiled = await route.compile(context.need.constraints, async (artifact) => publicAssetUrl === undefined
- ? await client.upload(artifact, context.resources, credential(context))
+ ? await client.upload(artifact, context.resources, auth)
: await publicAssetUrl(artifact, context.resources));
- await verifyModelRoute(client, credential(context), compiled.model, "audio_speech");
- const audio = await client.speech(credential(context), { model: compiled.model, ...(compiled.input as Record<string, unknown>) });
+ await verifyModelRoute(client, auth, compiled.model, "audio_speech");
+ const audio = await client.speech(auth, { model: compiled.model, ...(compiled.input as Record<string, unknown>) });
const artifacts = await Promise.all(audio.map(async (item) => await context.resources.put(item.bytes, item.mediaType)));
return { value: route.packageResult(artifacts) };
}
@@ -305,13 +339,14 @@ function endpoint(client: HypiHubClient, pollIntervalMs: number, maxOperationMs:
async start(context: EndpointStartContext) {
try {
const route = hypiHubRouteForCapability(context.need.capability);
- assert(route !== undefined, "HypiHub does not implement this exact capability"); const apiKey = credential(context);
+ assert(route !== undefined, "HypiHub does not implement this exact capability");
+ const auth = authFor(context, client);
const uploaded = new Map<string, Promise<string>>();
const resolve = (artifact: BlobRef): Promise<string> => {
const existing = uploaded.get(artifact.resource);
if (existing !== undefined) return existing;
const promise = publicAssetUrl === undefined
- ? client.upload(artifact, context.resources, apiKey)
+ ? client.upload(artifact, context.resources, auth)
: publicAssetUrl(artifact, context.resources);
uploaded.set(artifact.resource, promise);
return promise;
@@ -322,8 +357,8 @@ function endpoint(client: HypiHubClient, pollIntervalMs: number, maxOperationMs:
const operation = generationOperation(route, input);
const path = operation === "image_edits" ? "/images/edits"
: operation === "images" ? "/images/generations" : "/videos";
- await verifyModelRoute(client, apiKey, compiled.model, operation);
- const response = await client.json(path, apiKey, { method: "POST", headers: { "content-type": "application/json", "idempotency-key": context.operation }, body: JSON.stringify({ model: compiled.model, ...input }) });
+ await verifyModelRoute(client, auth, compiled.model, operation);
+ const response = await client.json(path, auth, { method: "POST", headers: { "content-type": "application/json", "idempotency-key": context.operation }, body: JSON.stringify({ model: compiled.model, ...input }) });
const status = response.status;
const remoteEnded = status === "succeeded" || status === "completed";
const handle: Handle = { contract: "hypit.hypihub-operation@1", jobId: jobId(response), route: capabilityKey(route.capability), startedAt: Date.now() };
@@ -343,7 +378,7 @@ function endpoint(client: HypiHubClient, pollIntervalMs: number, maxOperationMs:
return { status: "failed",
failure: { code: "HYPIHUB_OPERATION_TIMEOUT", message: "HypiHub operation timed out" } };
}
- const job = await client.json(`/jobs/${encodeURIComponent(handle.jobId)}`, credential(context)); const status = job.status;
+ const job = await client.json(`/jobs/${encodeURIComponent(handle.jobId)}`, authFor(context, client)); const status = job.status;
if (status === "queued" || status === "running" || status === "in_progress") return wakeAfter(canonicalize(handle), pollIntervalMs, Date.now(), { phase: String(status) });
if (status === "failed" || status === "queue_expired" || status === "cancelled") {
const detail = [job.error, job.message, job.reason, job.detail]
@@ -360,7 +395,7 @@ function endpoint(client: HypiHubClient, pollIntervalMs: number, maxOperationMs:
const handle = object(context.handle, "HypiHub handle") as unknown as Handle;
const route = hypiHubRouteForCapability(context.need.capability);
assert(route !== undefined && handle.route === capabilityKey(route.capability), "HypiHub collection route differs");
- return await complete(client, credential(context), route, handle.jobId, context.resources);
+ return await complete(client, authFor(context, client), route, handle.jobId, context.resources);
},
};
@@ -410,8 +445,9 @@ export function createHypiHubProvider(options: CreateHypiHubProviderOptions = {}
};
const geminiEndpoint: ImmediateEndpointHandler = async (context) => {
const request = inlineGeminiRequest(context);
- const generate = createHypiHubGeminiGenerator({
- apiKey: credential(context),
+ const auth = authFor(context, client);
+ const generate = async (): Promise<string> => await createHypiHubGeminiGenerator({
+ apiKey: await auth.token(),
model: context.need.capability.name,
...(options.baseUrl === undefined ? {} : { baseUrl: options.baseUrl }),
requestTimeoutMs,
@@ -420,20 +456,27 @@ export function createHypiHubProvider(options: CreateHypiHubProviderOptions = {}
...(options.fetch === undefined ? {} : { fetch: options.fetch }),
maxRateLimitRetries: geminiRateLimitAttempts - 1,
rateLimitRetryDelayMs: geminiRateLimitRetryDelayMs,
- });
+ })({ parts, instruction: request.instruction });
const parts: Array<{ text: string } | { fileData: { mimeType: string; fileUri: string } }> = [{ text: request.prompt }];
const uploaded = new Map<string, Promise<string>>();
for (const item of request.media) {
let url = uploaded.get(item.artifact.resource);
if (url === undefined) {
url = options.publicAssetUrl === undefined
- ? client.upload(item.artifact, context.resources, credential(context))
+ ? client.upload(item.artifact, context.resources, auth)
: options.publicAssetUrl(item.artifact, context.resources);
uploaded.set(item.artifact.resource, url);
}
parts.push({ fileData: { mimeType: item.artifact.mediaType, fileUri: await url } });
}
- const value = await generate({ parts, instruction: request.instruction });
+ let value: string;
+ try {
+ value = await generate();
+ } catch (error) {
+ if (!auth.canRefresh() || !/HTTP 401\b/u.test(error instanceof Error ? error.message : String(error))) throw error;
+ await auth.refresh();
+ value = await generate();
+ }
return { value: { kind: "inline", value: canonicalize(sealVisualObservation(value)) } };
};
const transcriptionModel = options.transcriptionModel?.trim() || "victor-upmeet/whisperx";
@@ -444,10 +487,10 @@ export function createHypiHubProvider(options: CreateHypiHubProviderOptions = {}
assert(bytes !== undefined && bytes.byteLength === request.audio.size,
`WhisperX evidence Resource ${request.audio.resource} is unavailable or has changed`);
assertWhisperXEvidenceWav(bytes, request.sampleFrames);
- const apiKey = credential(context);
- await verifyModelRoute(client, apiKey, transcriptionModel, "transcriptions");
+ const auth = authFor(context, client);
+ await verifyModelRoute(client, auth, transcriptionModel, "transcriptions");
const url = options.publicAssetUrl === undefined
- ? await client.upload(request.audio, context.resources, apiKey)
+ ? await client.upload(request.audio, context.resources, auth)
: await options.publicAssetUrl(request.audio, context.resources);
const response = await client.transcribe({
model: transcriptionModel,
@@ -455,7 +498,7 @@ export function createHypiHubProvider(options: CreateHypiHubProviderOptions = {}
response_format: "verbose_json",
language: request.language,
timestamp_granularities: ["segment", "word"],
- }, apiKey);
+ }, auth);
const evidence = sealAlignedTranscriptEvidence({
passages: interpretWhisperXTranscript(response as WhisperXTranscriptResponse, request.sampleFrames),
});
@@ -464,6 +507,7 @@ export function createHypiHubProvider(options: CreateHypiHubProviderOptions = {}
throw new Error(guidedMessage(error), { cause: error });
}
};
+ const oauthOrigin = new URL(options.baseUrl ?? "https://hypit.ai").origin;
return defineEndpointPackage({
module: hypiHubProviderModuleRef, facet: "gateway", instance: options.instance ?? "hypihub.default", pool: options.pool ?? options.instance ?? "hypihub.default",
pricing: { kind: "page", url: "https://hypit.ai/commercial/pricing/" },
@@ -472,8 +516,8 @@ export function createHypiHubProvider(options: CreateHypiHubProviderOptions = {}
label: "HypiHub login",
acquisition: {
kind: "oauth2-pkce",
- authorizationEndpoint: "https://hypit.ai/oauth/consent",
- tokenEndpoint: "https://hypit.ai/oauth/token",
+ authorizationEndpoint: new URL("/oauth/consent", oauthOrigin).toString(),
+ tokenEndpoint: new URL("/oauth/token", oauthOrigin).toString(),
clientId: "hyc_d5d5e8e7131b0c877756e66c",
scopes: ["user:profile", "user:inference"],
},
diff --git a/packages/provider-hypihub/test/oauth.test.ts b/packages/provider-hypihub/test/oauth.test.ts
new file mode 100644
index 00000000..67c4ba8d
--- /dev/null
+++ b/packages/provider-hypihub/test/oauth.test.ts
@@ -0,0 +1,54 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import type { EndpointCredential } from "@hypit/endpoint-kit";
+import { decodeOAuth2Credential, encodeOAuth2Credential } from "@hypit/runtime";
+
+import { createHypiHubAuth } from "../src/oauth.js";
+
+test("HypiHub rotates OAuth through only its declared credential slot", async () => {
+ let saved: string | undefined;
+ const requests: URLSearchParams[] = [];
+ const credential: EndpointCredential = {
+ secret: encodeOAuth2Credential({
+ accessToken: "expired-access",
+ refreshToken: "refresh-one",
+ expiresAt: Date.now() - 1,
+ }),
+ async replace(value) { saved = value.secret; },
+ };
+ const auth = createHypiHubAuth({
+ credential,
+ baseUrl: "https://hypit.ai/v1",
+ requestTimeoutMs: 1_000,
+ fetch: async (_input, init) => {
+ requests.push(new URLSearchParams(String(init?.body)));
+ return Response.json({
+ access_token: "fresh-access",
+ refresh_token: "refresh-two",
+ expires_in: 3600,
+ });
+ },
+ });
+
+ assert.equal(await auth.token(), "fresh-access");
+ assert.equal(requests.length, 1);
+ assert.equal(requests[0]?.get("grant_type"), "refresh_token");
+ assert.equal(requests[0]?.get("refresh_token"), "refresh-one");
+ assert(saved !== undefined);
+ const decoded = decodeOAuth2Credential(saved);
+ assert.equal(decoded?.accessToken, "fresh-access");
+ assert.equal(decoded?.refreshToken, "refresh-two");
+ assert(decoded?.expiresAt !== undefined && decoded.expiresAt > Date.now());
+});
+
+test("a static HypiHub API key remains an ordinary non-refreshing credential", async () => {
+ const auth = createHypiHubAuth({
+ credential: { secret: "static-api-key" },
+ baseUrl: "https://hypit.ai",
+ requestTimeoutMs: 1_000,
+ fetch: async () => { throw new Error("static credentials do not refresh"); },
+ });
+ assert.equal(await auth.token(), "static-api-key");
+ assert.equal(auth.canRefresh(), false);
+});
diff --git a/packages/provider-hypihub/test/provider.test.ts b/packages/provider-hypihub/test/provider.test.ts
index fbed3261..4b435bff 100644
--- a/packages/provider-hypihub/test/provider.test.ts
+++ b/packages/provider-hypihub/test/provider.test.ts
@@ -62,6 +62,12 @@ test("HypiHub declares its own credential acquisition flow", () => {
assert.equal(credential?.acquisition?.tokenEndpoint, "https://hypit.ai/oauth/token");
});
+test("HypiHub derives credential acquisition from its configured service origin", () => {
+ const [credential] = createHypiHubProvider({ baseUrl: "https://gateway.example.test/v1" }).credentials;
+ assert.equal(credential?.acquisition?.authorizationEndpoint, "https://gateway.example.test/oauth/consent");
+ assert.equal(credential?.acquisition?.tokenEndpoint, "https://gateway.example.test/oauth/token");
+});
+
test("HypiHub doctor checks the authenticated catalogue only when actively invoked", async () => {
let calls = 0;
const diagnostics = await diagnoseHypiHubProvider({ fetch: async (input, init) => {
diff --git a/packages/runtime-local/src/config.ts b/packages/runtime-local/src/config.ts
index 7861e893..1d9dbe98 100644
--- a/packages/runtime-local/src/config.ts
+++ b/packages/runtime-local/src/config.ts
@@ -8,13 +8,14 @@ import {
} from "@hypit/package-loader-node";
import type { NodePackageSelectionRequest } from "@hypit/package-loader-node";
import { EndpointRegistry, NodeDriver } from "@hypit/driver-node";
-import type { EndpointFulfillment, EndpointRegistrar, EndpointScheduling } from "@hypit/endpoint-kit";
+import type { EndpointCredential, EndpointFulfillment, EndpointRegistrar, EndpointScheduling } from "@hypit/endpoint-kit";
import { endpointResourceClaims } from "@hypit/endpoint-kit";
import { assertBuildId, canonicalize, canonicalStringify } from "@hypit/protocol";
import type { CanonicalValue, CapabilityRef, Need } from "@hypit/protocol";
import {
CompositeCredentialStore,
capacityUnits,
+ writableCredentialStore,
} from "@hypit/runtime";
import type { CredentialStore, CredentialValue, ResourceStore } from "@hypit/runtime";
import { FileResourceStore } from "@hypit/resource-store-fs";
@@ -702,7 +703,7 @@ export async function invokeRuntimeConfigNeed(
if (activation === undefined) throw new Error(`Endpoint ${registration.id} is not declared by ${absolute}`);
const stores = await openCredentialStores(document, root, hostStateRoot, registry);
try {
- const credentials: Record<string, CredentialValue> = {};
+ const credentials: Record<string, EndpointCredential> = {};
for (const slot of activation.endpoint.credentials) {
const value = await stores.store.resolve(slot.ref);
if (value === undefined) {
@@ -711,7 +712,13 @@ export async function invokeRuntimeConfigNeed(
? `Set ${slot.ref.key} in this process environment.`
: `Configure it with: hypit auth login ${slot.endpoint} --runtime ${absolute}`}`);
}
- credentials[slot.slot] = value;
+ const writable = await writableCredentialStore(stores.store, slot.ref);
+ credentials[slot.slot] = {
+ ...value,
+ ...(writable === undefined ? {} : {
+ replace: async (replacement: CredentialValue) => await writable.put(slot.ref, replacement),
+ }),
+ };
}
return await registration.handler({
command: { kind: "fulfill-need", id: `command:${need.id}`, need },
diff --git a/packages/runtime/src/credentials.ts b/packages/runtime/src/credentials.ts
index 1c46bbe0..7877c4c6 100644
--- a/packages/runtime/src/credentials.ts
+++ b/packages/runtime/src/credentials.ts
@@ -11,6 +11,34 @@ export type CredentialValue = {
readonly expiresAt?: number;
};
+export type OAuth2Credential = {
+ readonly format: "hypit.oauth2-credential@1";
+ readonly accessToken: string;
+ readonly refreshToken?: string;
+ readonly expiresAt?: number;
+};
+
+export function encodeOAuth2Credential(value: Omit<OAuth2Credential, "format">): string {
+ assert(value.accessToken.length > 0, "OAuth access token is empty");
+ if (value.refreshToken !== undefined) assert(value.refreshToken.length > 0, "OAuth refresh token is empty");
+ if (value.expiresAt !== undefined) assert(Number.isFinite(value.expiresAt), "OAuth expiry is invalid");
+ return JSON.stringify({ format: "hypit.oauth2-credential@1", ...value } satisfies OAuth2Credential);
+}
+
+export function decodeOAuth2Credential(secret: string): OAuth2Credential | undefined {
+ let value: unknown;
+ try { value = JSON.parse(secret); } catch { return undefined; }
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined;
+ const candidate = value as Partial<OAuth2Credential>;
+ if (candidate.format !== "hypit.oauth2-credential@1"
+ || typeof candidate.accessToken !== "string" || candidate.accessToken.length === 0
+ || (candidate.refreshToken !== undefined
+ && (typeof candidate.refreshToken !== "string" || candidate.refreshToken.length === 0))
+ || (candidate.expiresAt !== undefined
+ && (typeof candidate.expiresAt !== "number" || !Number.isFinite(candidate.expiresAt)))) return undefined;
+ return candidate as OAuth2Credential;
+}
+
/** Host-facing way to acquire one credential; Provider-specific values stay in its Endpoint package. */
export type CredentialAcquisition = {
readonly kind: "oauth2-pkce";
diff --git a/packages/runtime/src/index.ts b/packages/runtime/src/index.ts
index 4eb52c80..5166d655 100644
--- a/packages/runtime/src/index.ts
+++ b/packages/runtime/src/index.ts
@@ -3,6 +3,8 @@ export type * from "./catalog.js";
export {
CompositeCredentialStore,
credentialRef,
+ decodeOAuth2Credential,
+ encodeOAuth2Credential,
isWritableCredentialStore,
writableCredentialStore,
verifyCredentialRef,