An open-source, faster Devin alternative
TypeScript
Add browser profile auth check SDK (#532)
Mohamed Habibdfad5421a6a2
diff --git a/docs/browser-sessions/overview.mdx b/docs/browser-sessions/overview.mdxindex 11408b2a..d5894f7d 100644--- a/docs/browser-sessions/overview.mdx+++ b/docs/browser-sessions/overview.mdx@@ -68,6 +68,29 @@ Kernel telemetry configuration object directly.Replay recording is disabled by default. Set `recording: true` /`recording=True` to enable replay recording for a headful browser session.+## Profile Auth Checks++Saved profiles can start an asynchronous auth check for a site. The SDK returns+a run immediately; `wait()` polls with short requests until the run completes.++```typescript TypeScript+const profile = await BrowserProfile.connect("linkedin-profile");++const run = await profile.checkAuth({+ homepage: "https://www.linkedin.com/feed/",+ user: "motatoes",+ mode: "vision",+ compareFresh: true,+});++const result = await run.wait();+console.log(result.status, result.result);+```++Auth checks are read-only. They create temporary browser sessions with profile+saving disabled and compare the saved profile against a fresh browser when+`compareFresh` is enabled.+## PlaywrightThe browser response includes a CDP WebSocket URL. Pass it directly todiff --git a/sdks/typescript/src/browser.test.ts b/sdks/typescript/src/browser.test.tsindex 46778256..448a01a8 100644--- a/sdks/typescript/src/browser.test.ts+++ b/sdks/typescript/src/browser.test.ts@@ -1,6 +1,7 @@import { afterEach, describe, expect, it, vi } from "vitest";import { Browser } from "./browser.js";import { BrowserProfile } from "./browser.js";+import { BrowserProfileAuthCheck } from "./browser.js";const browserResponse = {id: "br_1",@@ -131,4 +132,103 @@ describe("Browser", () => {expect.objectContaining({ method: "DELETE" }),);});++ it("creates and polls browser profile auth checks", async () => {+ const profileResponse = {+ id: "prof_1",+ provider: "kernel",+ provider_profile_id: "kernel_profile_1",+ name: "linkedin",+ };+ const runningResponse = {+ id: "authchk_1",+ status: "running",+ profile_id: "prof_1",+ provider_profile_id: "kernel_profile_1",+ homepage: "https://www.linkedin.com/feed/",+ user: "motatoes",+ mode: "vision",+ compare_fresh: true,+ trigger_run_id: "run_1",+ };+ const completedResponse = {+ ...runningResponse,+ status: "completed",+ result: { outcome: "authenticated", confidence: 0.99 },+ completed_at: "2026-07-17T00:00:00.000Z",+ };+ const fetchMock = vi.spyOn(globalThis, "fetch")+ .mockResolvedValueOnce(Response.json(profileResponse))+ .mockResolvedValueOnce(Response.json(runningResponse, { status: 202 }))+ .mockResolvedValueOnce(Response.json(completedResponse));++ const profile = await BrowserProfile.connect("linkedin", {+ apiKey: "osb_test",+ apiUrl: "https://browser.example.test",+ });+ const run = await profile.checkAuth({+ homepage: "https://www.linkedin.com/feed/",+ user: "motatoes",+ mode: "vision",+ compareFresh: true,+ });+ const refreshed = await run.refresh();++ expect(run.id).toBe("authchk_1");+ expect(run.done).toBe(false);+ expect(refreshed.done).toBe(true);+ expect(refreshed.result).toEqual({ outcome: "authenticated", confidence: 0.99 });+ expect(fetchMock).toHaveBeenNthCalledWith(+ 2,+ "https://browser.example.test/v1/profiles/prof_1/auth-checks",+ expect.objectContaining({+ method: "POST",+ body: JSON.stringify({+ homepage: "https://www.linkedin.com/feed/",+ user: "motatoes",+ mode: "vision",+ compare_fresh: true,+ }),+ }),+ );+ expect(fetchMock).toHaveBeenNthCalledWith(+ 3,+ "https://browser.example.test/v1/profile-auth-checks/authchk_1",+ expect.objectContaining({ headers: expect.objectContaining({ "X-API-Key": "osb_test" }) }),+ );+ });++ it("waits for browser profile auth checks by polling", async () => {+ vi.useFakeTimers();+ const runningResponse = {+ id: "authchk_1",+ status: "running",+ profile_id: "prof_1",+ homepage: "https://mail.google.com/",+ };+ const completedResponse = {+ ...runningResponse,+ status: "completed",+ result: { outcome: "authenticated" },+ };+ const fetchMock = vi.spyOn(globalThis, "fetch")+ .mockResolvedValueOnce(Response.json(runningResponse))+ .mockResolvedValueOnce(Response.json(completedResponse));++ try {+ const run = await BrowserProfileAuthCheck.connect("authchk_1", {+ apiKey: "osb_test",+ apiUrl: "https://browser.example.test",+ });+ const waitPromise = run.wait({ intervalMs: 10, timeoutMs: 1000 });+ await vi.advanceTimersByTimeAsync(10);+ const done = await waitPromise;++ expect(done.status).toBe("completed");+ expect(done.result).toEqual({ outcome: "authenticated" });+ expect(fetchMock).toHaveBeenCalledTimes(2);+ } finally {+ vi.useRealTimers();+ }+ });});diff --git a/sdks/typescript/src/browser.ts b/sdks/typescript/src/browser.tsindex 261661ff..0c21678a 100644--- a/sdks/typescript/src/browser.ts+++ b/sdks/typescript/src/browser.ts@@ -61,6 +61,35 @@ export interface BrowserProfileData {provider_last_used_at?: string;}+export interface BrowserProfileAuthCheckCreateOpts {+ homepage: string;+ user?: string;+ mode?: "vision" | "playwright" | "hybrid";+ compareFresh?: boolean;+}++export interface BrowserProfileAuthCheckData {+ id: string;+ status: "queued" | "running" | "completed" | "failed" | string;+ profile_id: string;+ provider_profile_id?: string;+ homepage: string;+ user?: string | null;+ mode?: "vision" | "playwright" | "hybrid" | string;+ compare_fresh?: boolean;+ trigger_run_id?: string | null;+ result?: unknown;+ error?: unknown;+ created_at?: string;+ updated_at?: string;+ completed_at?: string | null;+}++export interface BrowserProfileAuthCheckWaitOpts {+ intervalMs?: number;+ timeoutMs?: number;+}+export class Browser {readonly id: string;readonly provider: "kernel";@@ -218,6 +247,92 @@ export class BrowserProfile {throw await browserError(resp, "delete browser profile");}}++ async checkAuth(opts: BrowserProfileAuthCheckCreateOpts): Promise<BrowserProfileAuthCheck> {+ const resp = await fetch(`${this.apiUrl}/v1/profiles/${encodeURIComponent(this.id)}/auth-checks`, {+ method: "POST",+ headers: headers(this.apiKey),+ body: JSON.stringify(toAuthCheckBody(opts)),+ });+ if (!resp.ok) {+ throw await browserError(resp, "create browser profile auth check");+ }+ return new BrowserProfileAuthCheck(await resp.json() as BrowserProfileAuthCheckData, this.apiUrl, this.apiKey);+ }+}++export class BrowserProfileAuthCheck {+ readonly id: string;+ readonly status: string;+ readonly profileId: string;+ readonly providerProfileId?: string;+ readonly homepage: string;+ readonly user: string | null;+ readonly mode?: string;+ readonly compareFresh?: boolean;+ readonly triggerRunId: string | null;+ readonly result: unknown;+ readonly error: unknown;+ readonly createdAt?: string;+ readonly updatedAt?: string;+ readonly completedAt?: string | null;++ private readonly apiUrl: string;+ private readonly apiKey: string;++ constructor(data: BrowserProfileAuthCheckData, apiUrl: string, apiKey: string) {+ this.id = data.id;+ this.status = data.status;+ this.profileId = data.profile_id;+ this.providerProfileId = data.provider_profile_id;+ this.homepage = data.homepage;+ this.user = data.user ?? null;+ this.mode = data.mode;+ this.compareFresh = data.compare_fresh;+ this.triggerRunId = data.trigger_run_id ?? null;+ this.result = data.result ?? null;+ this.error = data.error ?? null;+ this.createdAt = data.created_at;+ this.updatedAt = data.updated_at;+ this.completedAt = data.completed_at;+ this.apiUrl = apiUrl;+ this.apiKey = apiKey;+ }++ get done(): boolean {+ return this.status === "completed" || this.status === "failed";+ }++ static async connect(id: string, opts: { apiKey?: string; apiUrl?: string } = {}): Promise<BrowserProfileAuthCheck> {+ const apiUrl = resolveBrowserApiUrl(opts.apiUrl);+ const apiKey = opts.apiKey || process.env.OPENCOMPUTER_API_KEY || "";+ const resp = await fetch(`${apiUrl}/v1/profile-auth-checks/${encodeURIComponent(id)}`, {+ headers: headers(apiKey),+ });+ if (!resp.ok) {+ throw await browserError(resp, "connect browser profile auth check");+ }+ return new BrowserProfileAuthCheck(await resp.json() as BrowserProfileAuthCheckData, apiUrl, apiKey);+ }++ async refresh(): Promise<BrowserProfileAuthCheck> {+ return BrowserProfileAuthCheck.connect(this.id, { apiUrl: this.apiUrl, apiKey: this.apiKey });+ }++ async wait(opts: BrowserProfileAuthCheckWaitOpts = {}): Promise<BrowserProfileAuthCheck> {+ const intervalMs = opts.intervalMs ?? 2000;+ const timeoutMs = opts.timeoutMs ?? 120000;+ const startedAt = Date.now();+ let current: BrowserProfileAuthCheck = this;+ while (!current.done) {+ if (Date.now() - startedAt > timeoutMs) {+ throw new Error(`Timed out waiting for browser profile auth check ${this.id}`);+ }+ await sleep(intervalMs);+ current = await current.refresh();+ }+ return current;+ }}function headers(apiKey: string): HeadersInit {@@ -258,6 +373,18 @@ function toCreateBody(opts: BrowserCreateOpts): Record<string, unknown> {return body;}+function toAuthCheckBody(opts: BrowserProfileAuthCheckCreateOpts): Record<string, unknown> {+ const body: Record<string, unknown> = { homepage: opts.homepage };+ if (opts.user !== undefined) body.user = opts.user;+ if (opts.mode !== undefined) body.mode = opts.mode;+ if (opts.compareFresh !== undefined) body.compare_fresh = opts.compareFresh;+ return body;+}++function sleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}+async function browserError(resp: Response, action: string): Promise<Error> {const text = await resp.text();return new Error(`Failed to ${action}: ${resp.status} ${text}`);diff --git a/sdks/typescript/src/index.ts b/sdks/typescript/src/index.tsindex 1a017168..d9addbee 100644--- a/sdks/typescript/src/index.ts+++ b/sdks/typescript/src/index.ts@@ -16,7 +16,18 @@ export {type AllowedHostsInfo,type SandboxKillOptions,} from "./sandbox.js";-export { Browser, BrowserProfile, type BrowserCreateOpts, type BrowserData, type BrowserProfileCreateOpts, type BrowserProfileData } from "./browser.js";+export {+ Browser,+ BrowserProfile,+ BrowserProfileAuthCheck,+ type BrowserCreateOpts,+ type BrowserData,+ type BrowserProfileAuthCheckCreateOpts,+ type BrowserProfileAuthCheckData,+ type BrowserProfileAuthCheckWaitOpts,+ type BrowserProfileCreateOpts,+ type BrowserProfileData+} from "./browser.js";export { SandboxAgent, type SandboxAgentEvent, type SandboxAgentConfig, type SandboxAgentStartOpts, type SandboxAgentSession, type McpServerConfig } from "./agent.js";// Managed Durable Agent Sessions (the OpenComputer client + Session handle).export * from "./agents/index.js";