Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions .github/codeql/codeql-config.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
name: "CodeQL Configuration"

# Exclude false-positive rule on fast keyed hashing for high-entropy API tokens.
# Passwords in obliq-api are strictly hashed using bcrypt with CryptContext.
paths-ignore:
- 'scripts/**'
- 'tests/**'

# Exclude false-positive rule on fast keyed hashing for high-entropy API tokens,
# and exclude clear-text logging for internal provisioning CLI scripts.
query-filters:
- exclude:
id: py/weak-sensitive-data-hashing
- exclude:
id: py/clear-text-logging-sensitive-data
10 changes: 9 additions & 1 deletion .github/workflows/canary.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,14 @@ jobs:
else
CLEAN_NAME=$(echo "$HF_SPACE_PRODUCTION" | tr '/' '-' | tr '_' '-')
fi
TARGET_URL="https://${CLEAN_NAME}.hf.space"
if [ -n "$CLEAN_NAME" ]; then
TARGET_URL="https://${CLEAN_NAME}.hf.space"
fi
fi

if [ -z "$TARGET_URL" ]; then
echo "[CANARY] WARNING: Neither API_BASE_URL nor HF_SPACE_${{ matrix.environment }} secret is configured. Skipping canary check."
exit 0
fi
echo "Target Canary URL: $TARGET_URL"
python scripts/canary.py \
Expand All @@ -55,4 +62,5 @@ jobs:
--fixture tests/fixtures/golden_fixture.pdf \
--truth tests/fixtures/golden_fixture_truth.txt \
--max-latency 4.0 \
--max-e2e-latency 30.0 \
--max-cer 0.03
3 changes: 3 additions & 0 deletions .gitleaksignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,6 @@

# Historic commit from initial prototype (revoked local development key, replaced with CLI arg)
aff34396170ddac267d817493f11eecfb4cda3d6:scripts/poll_job.py:generic-api-key:5

# Unit test fixture prefix from commit b805562
b8055624c6c5772361f16b358d9803f7c22bb97f:tests/unit/test_keys_management_and_ui.py:generic-api-key:30
39 changes: 39 additions & 0 deletions alembic/versions/002_api_key_scopes_and_expiry.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
"""add scopes and expires_at to api_keys

Revision ID: 002
Revises: 001
Create Date: 2026-11-17
"""

from collections.abc import Sequence

import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

from alembic import op

revision: str = "002"
down_revision: str | None = "001"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
op.add_column(
"api_keys",
sa.Column(
"scopes",
postgresql.JSONB(astext_type=sa.Text()),
nullable=False,
server_default='["ocr:read", "ocr:write"]',
),
)
op.add_column(
"api_keys",
sa.Column("expires_at", sa.DateTime(timezone=True), nullable=True),
)


def downgrade() -> None:
op.drop_column("api_keys", "expires_at")
op.drop_column("api_keys", "scopes")
2 changes: 1 addition & 1 deletion docs/deployment/environments-and-secrets.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
| **Database (Neon)** | Dedicated branch: `staging` | Dedicated branch: `main` / `production` |
| **Redis (Upstash)** | Staging database / prefix `obliq:staging:` | Production database / prefix `obliq:prod:` |
| **Log Format** | Structured JSON | Structured JSON |
| **Deployment Gate** | Automatic on merge to `main` | Gated behind manual GitHub Environment approval |
| **Deployment Gate** | Automatic on merge to `main` | Gated behind manual GitHub Environment approval (Required reviewers: `@abhirajadhikary06`, `@Naman-iitm`; 1 approval required) |

---

Expand Down
4 changes: 3 additions & 1 deletion docs/deployment/handover-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,9 @@ In the GitHub repository, the admin needs to set up **Environments** and **Secre
1. **`staging`**:
- No protection rules needed (auto-deploys upon merge to `main`).
2. **`production`**:
- Check **Required reviewers** ➔ Add designated team members/admins who must approve production releases.
- Check **Required reviewers** ➔ Add designated reviewers (`@abhirajadhikary06`, `@Naman-iitm`).
- Configure **1 approval required** so that any single designated reviewer can approve the production deployment gate.
- Leave **Prevent self-review** unchecked (`false`) to allow authorized maintainers to self-approve when initiating releases.

#### 2. Configure GitHub Secrets (`Settings ➔ Secrets and variables ➔ Actions`)

Expand Down
108 changes: 108 additions & 0 deletions packages/client/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# @obliq/client

Official TypeScript and JavaScript client library for **Obliq API** — High-performance Document OCR and Text Extraction.

## Features

- 🚀 **Isomorphic:** Runs in Node.js 18+, Bun, browsers, and Next.js (Server Components, Server Actions, Client Components).
- 🔒 **Type-Safe:** Complete TypeScript typings matching Obliq API schemas.
- ⚡ **Zero External Dependencies:** Built on native global `fetch` and standard `FormData`.
- 🔁 **Resilient:** Automatic exponential backoff with jitter on 429 rate limits, 503 transient errors, and network drops.
- ⏱️ **Ergonomic Polling:** Built-in polling helper (`client.jobs.poll(...)`) with progress callbacks.

---

## Installation

```bash
npm install @obliq/client
# or
pnpm add @obliq/client
# or
yarn add @obliq/client
```

---

## Quickstart

### 1. Initialize the Client

```typescript
import { ObliqClient } from "@obliq/client";

const obliq = new ObliqClient({
apiKey: process.env.OBLIQ_API_KEY, // defaults to process.env.OBLIQ_API_KEY
baseUrl: "https://api.obliq.in", // defaults to https://api.obliq.in
});
```

### 2. Submit and Poll an OCR Job

```typescript
import { ObliqClient } from "@obliq/client";
import * as fs from "node:fs/promises";

const obliq = new ObliqClient();

// Submit document (accepts File, Blob, Buffer, or Uint8Array)
const fileBuffer = await fs.readFile("./invoice.pdf");
const job = await obliq.jobs.create({
file: fileBuffer,
fileName: "invoice.pdf",
});

console.log(`Job queued: ${job.id}`);

// Poll until completed with live progress callback
const result = await obliq.jobs.poll(job.id, {
pollIntervalMs: 1000,
timeoutMs: 60000,
onProgress: (status) => console.log(`Current status: ${status.status}`),
});

console.log(`Processed ${result.page_count} pages in ${result.processing_time_ms}ms:`);
for (const page of result.pages) {
console.log(`--- Page ${page.page_number} ---`);
console.log(page.text);
}
```

### 3. Manage API Keys

```typescript
// List active workspace keys
const keys = await obliq.keys.list();

// Generate a new key with specific scopes and expiry
const newKey = await obliq.keys.create({
name: "backend-microservice",
scopes: ["ocr:read", "ocr:write"],
expiresInDays: 90,
});
console.log(`Copy your API key now: ${newKey.key}`);

// Rotate key with a 24-hour grace period for zero downtime
const rotated = await obliq.keys.rotate(newKey.id, { gracePeriodHours: 24 });
console.log(`New key: ${rotated.key}`);

// Revoke a key
await obliq.keys.revoke(newKey.id);
```

### 4. Query Usage Analytics

```typescript
const summary = await obliq.dashboard.getSummary();
console.log(`Credit balance: ${summary.organisation.credit_balance}`);
console.log(`Total jobs last 30d: ${summary.usage_last_30_days.jobs}`);

const dailyUsage = await obliq.dashboard.getDailyUsage({ days: 7 });
console.table(dailyUsage);
```

---

## License

Apache-2.0
41 changes: 41 additions & 0 deletions packages/client/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"name": "@obliq/client",
"version": "0.1.0",
"description": "Official TypeScript and JavaScript client SDK for Obliq API",
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js",
"require": "./dist/index.cjs"
}
},
"files": [
"dist",
"README.md",
"LICENSE"
],
"scripts": {
"build": "tsup src/index.ts --format esm,cjs --dts",
"test": "vitest run",
"lint": "tsc --noEmit"
},
"keywords": [
"obliq",
"ocr",
"document-processing",
"sdk",
"typescript",
"client"
],
"author": "Obliq Team",
"license": "Apache-2.0",
"devDependencies": {
"tsup": "^8.0.0",
"typescript": "^5.4.0",
"vitest": "^1.5.0"
}
}
124 changes: 124 additions & 0 deletions packages/client/src/client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import {
AuthenticationError,
ForbiddenError,
NetworkError,
NotFoundError,
PayloadTooLargeError,
RateLimitError,
ServerError,
ValidationError,
ObliqError,
} from "./errors.js";
import { DashboardResource } from "./resources/dashboard.js";
import { JobsResource } from "./resources/jobs.js";
import { KeysResource } from "./resources/keys.js";
import type { ClientOptions } from "./types.js";

export class ObliqClient {
public readonly jobs: JobsResource;
public readonly keys: KeysResource;
public readonly dashboard: DashboardResource;

private readonly apiKey?: string;
private readonly baseUrl: string;
private readonly timeoutMs: number;
private readonly maxRetries: number;
private readonly fetchImpl: typeof fetch;

constructor(options: ClientOptions = {}) {
this.apiKey = options.apiKey || (typeof process !== "undefined" ? process.env?.OBLIQ_API_KEY : undefined);
this.baseUrl = (options.baseUrl || (typeof process !== "undefined" ? process.env?.OBLIQ_BASE_URL : undefined) || "https://api.obliq.in").replace(/\/+$/, "");
this.timeoutMs = options.timeoutMs ?? 30000;
this.maxRetries = options.maxRetries ?? 3;
this.fetchImpl = options.fetch || fetch.bind(globalThis);

const boundRequest = this.request.bind(this);
this.jobs = new JobsResource(boundRequest);
this.keys = new KeysResource(boundRequest);
this.dashboard = new DashboardResource(boundRequest);
}

/**
* Internal HTTP dispatcher with automatic exponential backoff, timeout handling, and typed error parsing.
*/
private async request(path: string, init: RequestInit = {}): Promise<Response> {
const url = `${this.baseUrl}${path}`;
const headers = new Headers(init.headers);

if (this.apiKey && !headers.has("Authorization")) {
headers.set("Authorization", `Bearer ${this.apiKey}`);
}

let attempt = 0;
while (true) {
attempt++;
let timeoutController: AbortController | undefined;
let signal = init.signal;

if (!signal && this.timeoutMs > 0) {
timeoutController = new AbortController();
const timeoutId = setTimeout(() => timeoutController?.abort(), this.timeoutMs);
signal = timeoutController.signal;
// Clean up timeout on exit
const originalSignal = signal;
originalSignal.addEventListener("abort", () => clearTimeout(timeoutId), { once: true });
}

try {
const response = await this.fetchImpl(url, {
...init,
headers,
signal,
});

if (response.ok) {
return response;
}

// Handle error responses
const errorData = await response.json().catch(() => ({}));
const message = errorData.error?.message || errorData.detail || response.statusText;
const details = errorData.error?.details || errorData;

if (response.status === 401) {
throw new AuthenticationError(message, details);
} else if (response.status === 403) {
throw new ForbiddenError(message, details);
} else if (response.status === 404) {
throw new NotFoundError(message, details);
} else if (response.status === 413) {
throw new PayloadTooLargeError(message, details);
} else if (response.status === 422) {
throw new ValidationError(message, details);
} else if (response.status === 429) {
const retryAfter = Number(response.headers.get("Retry-After")) || 60;
if (attempt <= this.maxRetries) {
const backoffMs = Math.min(retryAfter * 1000, 5000 * Math.pow(2, attempt - 1));
await new Promise((resolve) => setTimeout(resolve, backoffMs));
continue;
}
throw new RateLimitError(retryAfter, details);
} else if (response.status >= 500) {
if (attempt <= this.maxRetries) {
const backoffMs = 500 * Math.pow(2, attempt - 1) + Math.random() * 200;
await new Promise((resolve) => setTimeout(resolve, backoffMs));
continue;
}
throw new ServerError(message, response.status, details);
}

throw new ObliqError("api_error", message, response.status, false, details);
} catch (err: unknown) {
if (err instanceof ObliqError) {
throw err;
}
if (attempt <= this.maxRetries) {
const backoffMs = 500 * Math.pow(2, attempt - 1) + Math.random() * 200;
await new Promise((resolve) => setTimeout(resolve, backoffMs));
continue;
}
throw new NetworkError(err instanceof Error ? err.message : "Network request failed");
}
}
}
}
Loading
Loading