dmsandhika / ocr-client
Official PHP Client SDK for OCR Service (KTP, MyKad IC, Passport, and Receipts)
Package info
github.com/dmsandhika/OCR-Service
Language:JavaScript
pkg:composer/dmsandhika/ocr-client
Requires
- php: ^8.1
- guzzlehttp/guzzle: ^7.5
Requires (Dev)
None
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-12-03 09:05:05 UTC
README
OCR service powered by Tesseract.js, built as a standalone API so it can be reused across multiple platforms (web, mobile, backend integrations, etc). Supports English, Indonesian, and Malay text out of the box, plus optional structured field extraction for a few known document layouts (KTP, Malaysian IC, passport, and receipts).
Features
POST /ocr— upload an image, get back extracted textPOST /ocr/bulk— bulk upload multiple images, get back structured results concurrently- Structured field extraction:
ktp,ic,passport,struk, andlanding_page(CTAs, pricing, contacts, headlines, features) - Long screenshot auto-tiling — uses
sharpto slice full-height webpage captures into manageable segments, preventing memory overflow - Per-platform API keys — each client gets its own key, revocable independently
- Interactive API docs at
/docs(Swagger UI) - Dockerized, with a persistent cache for Tesseract's language data
Client SDKs (NPM & Composer)
Official client libraries are available for fast integration:
- JavaScript / TypeScript (NPM):
@dmsandhika/ocr-client. Runs OCR locally inside your own Node project (engine and language data are bundled: no server, no API key, works offline). PassbaseUrl+apiKeyinstead to call a hosted server.npm install @dmsandhika/ocr-client
const ocr = new OcrClient(); const { fields } = await ocr.scan('./ktp.jpg', { type: 'ktp' });
- PHP / Laravel (Composer):
dmsandhika/ocr-clientcomposer require dmsandhika/ocr-client
Tech Stack
- Fastify — HTTP server
- tesseract.js — OCR engine (runs server-side, not in the browser)
- @fastify/multipart — file upload handling
- @fastify/swagger + @fastify/swagger-ui — API documentation
Getting Started
Prerequisites
- Node.js 20+
- (Optional) Docker, for containerized deployment
Local development
npm install npm run dev
The server starts on http://localhost:3000 (override with PORT).
Configuration
Copy .env.example to .env:
cp .env.example .env
| Variable | Default | Description |
|---|---|---|
PORT |
3000 |
HTTP port |
TESSDATA_CACHE_PATH |
./.cache/tesseract |
Where downloaded Tesseract language data is cached |
API_KEYS_PATH |
./config/api-keys.json |
Path to the API keys config file |
USAGE_PATH |
./data/usage.json |
Where per-key usage counters are persisted (keep it on a volume) |
The limits and hardening options (quotas, upload sizes, CORS, proxy) are listed under Running it publicly.
API keys
Each platform that calls this service needs its own API key, sent via the x-api-key header. Keys live in config/api-keys.json (gitignored — copy config/api-keys.example.json to get started).
Generate a new key for a platform, optionally with its own quota:
npm run generate-key -- <platform-name> npm run generate-key -- partner-app --hourly 200 --daily 2000 --monthly unlimited
The key is printed once and only its SHA-256 hash is stored, so a leaked config file does not leak usable keys. Give the key to whoever owns that platform.
The server re-reads the file when it changes, so keys can be added, re-limited or revoked without a restart: set "disabled": true on an entry, or delete it. (Older plaintext "key" entries keep working.)
If config/api-keys.json doesn't exist yet (e.g. fresh clone), the server generates a temporary key on startup and logs it — fine for local testing, not for anything shared. In production (NODE_ENV=production) it never does this: with no keys file every OCR request is rejected.
Running it publicly
The defaults are sized for a small public instance. Everything below is configurable through environment variables.
Quotas
Every successful scan counts against the API key's quota, in fixed UTC windows. When a window is used up the API answers 429 with a Retry-After header and a JSON body telling which window was hit and when it resets. A scan that fails on the server side (500/503/504) is refunded; a rejected upload (bad file) never counts.
| Variable | Default | |
|---|---|---|
QUOTA_HOURLY |
50 |
Scans per key per hour |
QUOTA_DAILY |
300 |
Scans per key per day |
QUOTA_MONTHLY |
3000 |
Scans per key per month |
Use 0 or unlimited to remove a window. Individual keys override these (hourlyLimit, dailyLimit, monthlyLimit in api-keys.json, or the --hourly/--daily/--monthly flags of generate-key; null = unlimited). Remaining quota is returned on every response:
X-Quota-Hourly-Limit: 50 X-Quota-Hourly-Remaining: 49
X-Quota-Daily-Limit: 300 X-Quota-Daily-Remaining: 299
X-Quota-Monthly-Limit: 3000 X-Quota-Monthly-Remaining: 2999
Counters live in USAGE_PATH and survive restarts. They are kept in one process, so run a single instance (or move the counters to a shared store before scaling out).
Privacy policy (/privacy)
The landing page links to a privacy policy written for what this code actually does: images and OCR results are never stored, what is stored (account, key hash, usage counters, logs) and for how long, cookies, third parties (GitHub, optionally Cloudflare Turnstile), and the user's rights. A test checks that the policy keeps mentioning the facts it relies on (no-store, cookie names, hashing, ...), so it cannot silently drift from the code.
Before going public, set these — the policy names who runs the service and how to reach them:
| Variable | Default | |
|---|---|---|
OPERATOR_NAME |
"pengelola layanan ini" | Your name or company, as the data controller |
PRIVACY_EMAIL |
(unset: points to CONTACT_URL) |
Where data requests go. In production the server logs a warning while this is unset |
LOG_RETENTION_DAYS |
30 |
The retention period the policy states for server logs |
The policy is only true if the deployment matches it:
- Log retention:
LOG_RETENTION_DAYSis a statement, not a setting that deletes anything. Make it real: the bundleddocker-compose.ymlrotates container logs by size; also check logs kept by your reverse proxy (Caddy/Nginx access logs contain client IPs) and your host. - HTTPS everywhere (the policy and the cookies assume it).
- The landing-page demo asks for explicit consent before scanning, since faces on ID documents are biometric data. Users can delete their own account from the API-key section (
DELETE /account), which removes the login, GitHub id and key hash; usage counters (numbers only) are kept until the month ends so that signing up again cannot reset a quota. - The text describes the service's technical practices; it is not legal advice. Have it reviewed against the rules that apply to you (e.g. UU PDP No. 27/2022 in Indonesia, GDPR for EU users). Edit
public/privacy.htmlto adapt it, and update the date at the top.
Landing page and public demo
GET / serves a landing page with a "try it" demo: pick a document type, upload a photo, see the parsed fields, confidence, raw text and JSON. It is a single static page (no build step, files in public/) with a strict Content-Security-Policy — no inline scripts or styles.
The demo needs no API key, so it has its own, tighter protection:
- a per-visitor limit (
DEMO_IP_PER_HOUR, default 10 scans/hour per IP) — setTRUST_PROXYcorrectly or every visitor shares one bucket; - a global cap across all visitors (
DEMO_GLOBAL_HOURLY60,DEMO_GLOBAL_DAILY500), so a crowd or a bot net cannot burn the server's CPU. Demo scans never use an API key's quota; - an optional Cloudflare Turnstile captcha: create a free widget, then set
TURNSTILE_SITE_KEYandTURNSTILE_SECRET. Without the secret the captcha is off (fine locally; turn it on for a public site); landing_pagescans are not offered (CPU heavy), and images larger than 2600 px are downscaled in the browser before upload.
Nothing is stored: the image lives in memory for the length of the request, and logs only contain the document type. Set DEMO_ENABLED=false to serve the API only (/ then redirects to /docs). CONTACT_URL is where the "Minta API key" button points.
Self-service API keys ("Sign in with GitHub")
Instead of creating every key by hand, visitors can sign in with GitHub on the landing page and create their own key. It is off until you configure a GitHub OAuth App, and keys made with generate-key keep working next to it.
Set it up (5 minutes)
-
GitHub → Settings → Developer settings → OAuth Apps → New OAuth App.
- Homepage URL: your public origin, e.g.
https://ocr.example.com - Authorization callback URL:
https://ocr.example.com/auth/github/callback
- Homepage URL: your public origin, e.g.
-
Copy the Client ID, generate a Client secret, and set:
Variable GITHUB_CLIENT_ID,GITHUB_CLIENT_SECRETFrom the OAuth App. Both are needed to switch the feature on SESSION_SECRETA long random string ( openssl rand -hex 32) that signs the login cookie. Required in production; changing it logs everyone outPUBLIC_URLThe public https://origin, matching the OAuth App. Recommended; otherwise it is derived from the requestGITHUB_MIN_ACCOUNT_AGE_DAYSDefault 7. Rejects brand-new throwaway accountsKEY_REGEN_PER_DAYDefault 3. How often one account may create/rotate its key per 24 hACCOUNTS_PATHDefault ./data/accounts.json(keep it on a volume)
How it behaves
- One GitHub account = one active key. Creating a new one replaces the old key immediately.
- The key is shown once; only its SHA-256 hash is stored.
- Quota belongs to the account, not the key, so rotating a key never resets usage. New accounts get the default quota (
QUOTA_*). - GitHub is only asked who the visitor is: the OAuth token is used for a single
/usercall and revoked straight away, and no email address is requested or stored. - The login cookie is signed,
HttpOnly,SameSite=LaxandSecureon https; the OAuthstateis bound to the browser; key management also checks theOriginheader.
Users can delete their own account from the API-key section of the page (login, GitHub id and key hash are removed; usage counters, which are only numbers, stay until the end of the month so that re-registering cannot reset a quota).
Admin (while the server is stopped, edit data/accounts.json): give an account its own limits with "hourlyLimit" / "dailyLimit" / "monthlyLimit" (null = unlimited) or block it with "disabled": true — a blocked account's key stops working and it cannot sign in.
Limits and protection
| Variable | Default | |
|---|---|---|
RATE_LIMIT_KEY_MAX |
10 |
Requests per minute per API key on /ocr and /ocr/bulk. Requests with an unknown key are limited per IP instead, which throttles key guessing |
RATE_LIMIT_MAX |
120 |
Requests per minute per IP on everything else (/health, /docs) |
MAX_FILE_MB |
8 |
Largest accepted upload |
MAX_BULK_FILES |
5 |
Files per /ocr/bulk request |
MAX_IMAGE_MEGAPIXELS |
40 |
Rejects images that decode to more pixels than this (decompression bombs) |
MAX_QUEUE |
10 |
OCR jobs allowed to wait; beyond that the API answers 503 + Retry-After instead of letting a queue build up |
OCR_TIMEOUT_MS |
30000 |
Deadline per scan (504 when exceeded) |
TRUST_PROXY |
off | Set this behind Caddy/Nginx/a load balancer (true, a hop count like 1, or proxy IPs/CIDRs). Without it every client looks like the proxy's IP and per-IP limits are meaningless; with it set to true on a server reachable directly, clients could fake their IP |
CORS_ORIGINS |
open in dev, closed in production | Comma-separated browser origins allowed to call the API (* for any). Server-to-server callers (the npm/PHP clients) do not need CORS |
Uploads are validated by their actual bytes (PNG / JPEG / WEBP / BMP / TIFF), not the declared Content-Type. OCR responses are sent with Cache-Control: no-store since they contain personal data, and the service logs only the platform name and document type — never image contents or extracted text.
API
Full interactive docs (with a "try it out" file upload) are at http://localhost:3000/docs once the server is running.
POST /ocr
Headers: x-api-key: <your-key>
Body: multipart/form-data
| Field | Required | Description |
|---|---|---|
file |
Yes | Image file — PNG, JPEG, WEBP, BMP, or TIFF, max 10MB |
type |
No | ktp, ic, passport, or struk — enables structured field extraction |
Response
{
"text": "extracted text...",
"confidence": 91
}
With type set, the response also includes type and a fields object with whatever that document's parser could extract:
type |
Fields | Notes |
|---|---|---|
ktp |
provinsi, kabupatenKota, nik, nama, tempatLahir, tanggalLahir, tempatTglLahir, jenisKelamin, golDarah, alamat, rtRw, kelDesa, kecamatan, agama, statusPerkawinan, pekerjaan, kewarganegaraan, berlakuHingga | Images are preprocessed (grayscale, upscale, contrast) and read with the Indonesian model only. Labels are matched fuzzily and values snapped to known options. Birth date / gender missing from the OCR are derived from the NIK and listed in inferredFromNik. Still best with sharp, well-lit photos |
ic |
icNumber, jantina, tarikhLahir, tempatLahir, warganegara, agama, nama, alamat, poskod, negeri | Images are preprocessed and read in a layout-aware mode. IC number is pattern-matched (tolerates lost dashes); jantina, tarikhLahir and tempatLahir are derived from it. nama/alamat are best-effort since MyKad has no field labels: name = lines under the number, address = the lines after the gap |
passport |
countryCode, surname, givenNames, fullName, passportNumber, nationality, nationalityName, dateOfBirth, placeOfBirth, sex, dateOfIssue, expiryDate, issuingOffice, nik, mrzValid | Two OCR passes: the full page (visual zone) and the bottom strip read with the MRZ alphabet only. MRZ values are used when their check digits pass (mrzValid); otherwise the visual zone wins, so damaged MRZs and sample documents with filler data still give correct dates. Dates are ISO YYYY-MM-DD. nik, placeOfBirth, dateOfIssue and issuingOffice come from the visual zone only |
struk |
merchant, date, dateIso, time, items, subtotal, discount, tax, total, paid, change, paymentMethod | Amounts are normalised (40.500,00 → 40500, RM 12.50 → 12.50) and OCR zeros fixed (40.5OO). TOTAL ITEM/TOTAL QTY counts are not mistaken for the total. Item extraction is best-effort (name, price, optional quantity) since layouts vary per merchant; the summary fields are the reliable part. OCR uses the default settings — not yet tuned against real receipt photos |
Docker
docker compose up -d --build
This builds the image, starts the service on PORT (default 3000), and mounts:
- a named volume for the Tesseract language cache (
tessdata-cache), so traineddata isn't re-downloaded on every restart ./config/api-keys.jsonread-only into the container, so keys can be rotated without rebuilding
Project Structure
clients/
js/ # JavaScript / TypeScript SDK (NPM)
php/ # PHP & Laravel SDK (Composer)
src/
server.js # Fastify app setup, Swagger, graceful shutdown
config/apiKeys.js # Loads config/api-keys.json, falls back to a temp key
middleware/apiKey.js # x-api-key auth
routes/ocr.route.js # POST /ocr
services/ocr.service.js # Tesseract worker wrapper
parsers/ # Per-document-type field extraction
tests/ # Automated unit tests for document parsers
scripts/
generate-api-key.js # Generates and appends a new platform API key
Known Limitations
- Document-type parsers (KTP, IC, passport, struk) have only been validated against clean synthetic test images, not real-world photos (skew, blur, lighting). Regex patterns may need tuning against real samples.
- Struk parsing only extracts date and total — no line items.
- OCR runs synchronously per request; concurrent or very large uploads may be slow. An async job queue is a planned next step if throughput becomes an issue.