Aperture

api-client

Effect services for the Aperture REST API.

npm install @aperture-browser/api-client effect

Each API area is a service: AuthApi, SessionsApi, SnapshotsApi, TenantsApi, UsersApi, TokensApi, EventsApi and HealthApi. apiClientLayer provides all of them over the HttpClient your app supplies, and baseUrlLayer points it at an instance on another origin. Failures are ApiRequestErrors carrying the server's error code and HTTP status, plus the underlying HTTP or decoding failure as cause when the server sent no error body to explain it.

import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Redacted from "effect/Redacted";
import * as FetchHttpClient from "effect/http/FetchHttpClient";
import { apiClientLayer, baseUrlLayer, SessionsApi } from "@aperture-browser/api-client";

const credentials = {
  kind: "bearer",
  token: Redacted.make(process.env.APERTURE_TOKEN!),
  authorityType: "tenant",
  tenantId: "my-tenant",
  selectedTenantId: null,
} as const;

const program = SessionsApi.use((sessions) => sessions.listSessions(credentials, { limit: 20 }));

const layer = apiClientLayer.pipe(
  Layer.provide(baseUrlLayer("https://aperture.example.com")),
  Layer.provide(FetchHttpClient.layer),
);

const page = await Effect.runPromise(program.pipe(Effect.provide(layer)));

Fixed credentials

A caller that always acts with the same credentials, such as a server holding one API token, can bind them once. apertureClientLayer(credentials) provides ApertureClient, which groups sessions, snapshots, tenants, users, tokens and events with the same methods minus the credentials argument, plus auth.getAuthMe() and health.getHealth(). withCredentials(service, credentials) binds a single service the same way.

import { ApertureClient, apertureClientLayer } from "@aperture-browser/api-client";

const layer = apertureClientLayer(credentials).pipe(
  Layer.provide(baseUrlLayer("https://aperture.example.com")),
  Layer.provide(FetchHttpClient.layer),
);

const program = Effect.gen(function* () {
  const client = yield* ApertureClient;
  const base = yield* client.snapshots.getSnapshotByName("signed-in-base");
  const { session } = yield* client.sessions.createSession({
    baseSnapshotName: Option.isSome(base) ? base.value.name : null,
    browser: { channel: "chromium" },
    proxy: {
      upstreams: { office: { url: "socks5://proxy.example.com" } },
      rules: [{ match: "*", via: "office" }],
    },
  });
  yield* client.sessions.updateSessionProxy(session.id, { rules: [] });
});

Pagination

Every paginated list (sessions, snapshots, tenants, users, admin and tenant tokens, events, audit events) has the same three calls, derived from one generic: listX(params) fetches one page (pass the previous meta.nextCursor as cursor), streamX(filter) is a Stream of items that fetches the next page only when pulled, and listAllX(filter) collects every page. The filter is the list params without cursor; its limit is the page size.

const page = yield * client.sessions.listSessions({ status: "running", limit: 20 });
const all = yield * client.sessions.listAllSessions({ status: "running", limit: 100 });

getSnapshotByName(name) returns an Option, since the API has no direct lookup by name.

Export browser storage

Export storage from a running session and pass it directly to session creation:

const storageState =
  yield *
  client.sessions.exportSessionStorageState(sessionId, {
    origins: ["*"],
  });
const restored =
  yield *
  client.sessions.createSession({
    browser: { channel: "chromium" },
    storageState,
  });

The REST equivalent is POST /api/sessions/{sessionId}/storage-state with the same body. It requires sessions:read and access to that session. Suspended sessions must be woken first.

SelectionBody
Every stored HTTP origin, including closed sites{ "origins": ["*"] }
Exact origins{ "origins": ["https://example.com", "https://app.example.org"] }
Partial wildcards{ "origins": ["https://*.example.com"] }
Current pages and their frames{ "origins": "open-tabs" }

Lists can mix exact origins and patterns. Only * is special; it matches zero or more characters in the complete origin, including its scheme and non-default port. Paths, queries, fragments, and credentials are not accepted. Exact origins include their stored partitions; open-tabs includes only the partitions used by the current frames.

Cookies follow the selection, including all cookie paths and matching parent-domain cookies. For open-tabs, partitioned cookies must also match an open frame's top-level site and cross-site status. ["*"] exports every representable cookie in the profile.

The result includes localStorage, IndexedDB, Cache Storage, and OPFS files in the existing storageState format. Sensitive fields remain redacted values in the TypeScript client. Session storage is target-specific and belongs to initialTargets instead.

Export briefly creates helper pages, serves synthetic documents without fetching the selected sites, and closes them afterward. It does not pause other pages, so concurrent writes can appear at different points in the export. Partition ancestor chains may be replaced by equivalent chains that recreate the same Chromium storage key. This is a portable storage export, not a filesystem snapshot.

Chromium's inventory omits the top-level scheme for partitioned site data. List and wildcard selection therefore reject partitioned HTTP site data rather than risk omitting an inaccessible HTTPS-ancestor partition. Use open-tabs for an accessible HTTP partition. HTTPS origins support both HTTP and HTTPS top-level partitions.

Exports also fail for unsupported partitions, named storage buckets, opaque cache responses, non-extractable cryptographic keys, or data exceeding the import limits: 100 origin partitions, 10,000 cookies, and 64 MiB of JSON. These fail with storage_export_unsupported (422), whose message names the reason. Failures return no partial state. The JSON response uses Cache-Control: no-store.

Thumbnails

getSessionThumbnail(credentials, sessionId, targetId?) returns a JPEG Blob of the session, or of one tab. It never wakes a suspended session. For image elements, use the signed session.thumbnail.url and session.thumbnail.targetUrlTemplate from getSession or the session list instead; see Thumbnails.

Favicons

getSessionFavicon(credentials, sessionId, targetId, version?) returns a tab's icon as a Blob typed by its response. It never wakes a suspended session. Pass the page's faviconVersion so the HTTP cache can keep the response. For image elements, use the signed session.favicon.targetUrlTemplate; see Favicons.

Passive browser status

getBrowserStatus(credentials, sessionId, sessionToken?) reads page metadata without waking the browser, mounting its profile, updating retention activity, or preventing idle suspension. Account credentials need sessions:read; the optional bearer credential may instead be the owner session token or an editor or viewer capability.

status is the session lifecycle state. source: "live" reports a running browser snapshot, while source: "persisted" reports the page generation saved with suspension thumbnails. Both include capturedAt, pages, and the optional representativeTargetId. A suspended session created before page persistence existed, or one whose best-effort capture failed returns source: "unavailable" and an empty page list rather than waking.

Each page says whether its generation has a thumbnail. thumbnailAvailable does the same for the representative session thumbnail. Retrieve those images with getSessionThumbnail. Target IDs in persisted metadata identify the saved generation only; Chromium may assign different IDs after resume.

Session files

listSessionFiles(sessionId) lists a session's files and directories, tagged with type, and sessionFileTree(entries) arranges them into directory and file nodes for a tree view; sessionFileRootDirectories names the top-level directories that cannot be deleted, moved or renamed. uploadSessionFiles(sessionId, files, { directory }), createSessionDirectory(sessionId, relativePath), deleteSessionFile(sessionId, relativePath, { recursive }) and moveSessionFile(sessionId, { from, to }) manage files and folders in any retained state; moves never overwrite, and a non-empty folder is deleted only with recursive. createSessionFileDownloadURL(sessionId, { relativePath, disposition: "inline" }) returns a signed URL usable as an <img> source. Upload contents may be a Blob, a Uint8Array or a byte Stream. Any stream makes the whole request body streamed, which browsers other than Chromium cannot send. Each file carries relativePath for browser_file_upload and sandboxPath for CDP DOM.setFileInputFiles.

const program = Effect.gen(function* () {
  const client = yield* ApertureClient;
  const tree = sessionFileTree(yield* client.sessions.listSessionFiles(sessionId));
  yield* client.sessions.uploadSessionFiles(sessionId, [{ name: file.name, content: file }]);
  yield* client.sessions.moveSessionFile(sessionId, {
    from: "downloads/report.pdf",
    to: "uploads/report.pdf",
  });
  const preview = yield* client.sessions.createSessionFileDownloadURL(sessionId, {
    relativePath: "outputs/page.png",
    disposition: "inline",
  });
  return { tree, previewUrl: preview.url };
});

The live session

The live-session calls reach the running session directly and take an optional Redacted sessionToken in place of the credentials: uploadLiveSessionFiles stores files in its uploads directory, setSessionViewport resizes a target, and streamSessionRecording streams a recording as a Stream of bytes without buffering it; downloadSessionRecording still returns a Blob. A failure inside the running session is an ApiRequestError with code live_session_error, its HTTP status, and the session's message.

Passkeys

Browser passkey sign-in and registration live in @aperture-browser/api-client/passkeys, so the main entry does not pull in @simplewebauthn/browser. It is an optional peer dependency; install it alongside when you use that entry. loginWithPasskey() and registerPasskey(name) run the whole WebAuthn ceremony and fail with PasskeyCeremonyError when the browser does not complete it. Its reason is cancelled for a dismissed or timed-out prompt and failed otherwise.

Url paths

@aperture-browser/api-client/url-path builds request paths and urls from values a url treats specially. Every interpolation in UrlPath.make`/sessions/${sessionId}/recordings/${recordingId}/content` is encoded as one segment, so an id cannot escape it. UrlPath.raw inserts a base url or an already built path as it is, and UrlPath.segments encodes each segment of a multi-segment value and keeps its slashes.

The endpoints, their parameters and error codes are in the REST API reference.

api-schema

@aperture-browser/api-schema holds the Effect Schemas and a typed HttpClient generated from the OpenAPI spec with @effect/openapi-generator. api-client builds on it; depend on it directly only when you need the raw generated client.

Both require effect 4.

Edit on GitHub

On this page