// Check Share Code API client for TypeScript and JavaScript: right to work, right to rent, // immigration status, driving licence and SIA licence checks // (https://checksharecode.co.uk/docs/clients). // // One file, no dependencies. Copy it into your project: // curl -O https://checksharecode.co.uk/clients/checksharecode.ts // It needs fetch and Web Crypto, so it runs on Node 20+, Deno, Bun, Cloudflare Workers and // Supabase Edge Functions. Keep your API key on your server: never ship it to a browser. // // const csc = new CheckShareCode(process.env.CHECKSHARECODE_API_KEY); // const result = await csc.rightToWork({ // share_code: 'AB1CD2EF3', date_of_birth: '1990-01-01', company_name: 'Acme Ltd', // }); // // What it does for you: sends the key, waits out BUSY and retries TIMEOUT and INTERNAL // (never a driving licence check whose code may have been used), sends Northern Ireland // licence numbers to their own endpoint, polls asynchronous checks, and verifies webhooks. // Keys starting rtw_test_ get the sandbox's fixed answers, free; rtw_live_ keys run real // checks. Every field is described at https://checksharecode.co.uk/openapi.json. export const CLIENT_VERSION = '2026-11-23'; // ---- Requests --------------------------------------------------------------------------- export interface RightToWorkRequest { /** The 9 characters the person got from gov.uk/prove-right-to-work. */ share_code: string; /** YYYY-MM-DD. */ date_of_birth: string; /** The employer, as gov.uk records it on the check. */ company_name: string; } export interface RightToRentRequest { share_code: string; date_of_birth: string; /** The landlord's or letting agent's name. */ checker_name: string; checker_type: 'landlord' | 'agent'; } export type ImmigrationPurpose = | 'driving_licence' | 'student_loan' | 'education_or_training' | 'health_insurance_card' | 'personal_finance' | 'homelessness_or_council_housing' | 'travel' | 'other'; export interface ImmigrationStatusRequest { /** An S code, from gov.uk/view-prove-immigration-status. */ share_code: string; date_of_birth: string; company_name: string; job_title: string; purpose: ImmigrationPurpose; /** With purpose `other` only: the reason, in your words. */ other_purpose?: string; } export interface DrivingLicenceRequest { /** * A GB licence number (all 16 characters, or the last 8) or a Northern Ireland one * (8 digits). Northern Ireland numbers go to DVA's check, the rest to DVLA's. */ licence_number: string; /** The 8 character code the driver made at gov.uk/view-driving-licence (or nidirect). */ check_code: string; } export interface SiaLicenceRequest { /** The 16 digits on the front of a Security Industry Authority licence. */ licence_number: string; } export type CheckName = | 'right_to_work' | 'right_to_rent' | 'immigration_status' | 'driving_licence' | 'sia_licence'; export interface CheckRequests { right_to_work: RightToWorkRequest; right_to_rent: RightToRentRequest; immigration_status: ImmigrationStatusRequest; driving_licence: DrivingLicenceRequest; sia_licence: SiaLicenceRequest; } // ---- Responses -------------------------------------------------------------------------- export interface RightToWorkResponse { outcome: 'ACCEPTED' | 'REJECTED'; title: 'Right to work' | 'Right to rent'; name: string; date_of_birth: string; details: string; /** @deprecated Always null. */ nationality: string | null; /** @deprecated Always null. */ permission_type: string | null; start_date: string | null; expiry_date: string | null; /** When to check again; null when their permission has no end. */ recheck_date: string | null; conditions: string[]; restrictions: string[]; /** Right to work only; null for right to rent and REJECTED. */ requires_sponsorship: boolean | null; /** Right to work only; null for right to rent and REJECTED. */ student_visa: boolean | null; reference: string | null; company_name: string | null; check_date: string | null; share_code: string; /** data:image/jpeg;base64,... */ photo_data_url: string | null; /** data:application/pdf;base64,... gov.uk's own result PDF. */ pdf_data_url: string | null; checked_at: string; free_checks_remaining?: number; } /** Right to rent answers in the same shape as right to work. */ export type RightToRentResponse = RightToWorkResponse; export interface ImmigrationStatusResponse { outcome: 'ACCEPTED'; title: 'Immigration status'; name: string; date_of_birth: string | null; nationality: string | null; status: string; valid_from: string | null; /** Null when there is no limit on how long they can stay. */ valid_until: string | null; activities: string[]; restrictions: string[]; reference: string | null; company_name: string | null; job_title: string | null; purpose: string | null; check_date: string | null; share_code: string; photo_data_url: string | null; pdf_data_url: string | null; checked_at: string; free_checks_remaining?: number; } export interface LicenceEndorsement { /** As shown: GB's "SP30", "DR10"; Northern Ireland's "50 08 201" or "TOT UP". */ code: string; description: string | null; /** Our grouping of a GB code ("drink", "speeding"...); null for codes we don't know. */ category: string | null; offence_date: string | null; /** A court that bans often gives 0: never judge an offence by its points. */ points: number; points_expired: boolean | null; points_expiry_date: string | null; removal_date: string | null; } export interface LicenceEntitlement { category: string; kind: 'full' | 'provisional'; valid_from: string | null; valid_to: string | null; automatic_only: boolean; restrictions: { code: string; text: string }[]; description: string | null; } export interface DrivingLicenceResponse { outcome: 'ACCEPTED'; title: 'Driving licence'; issuer: 'DVLA' | 'DVA'; name: string; driving_status: string; licence_number_last8: string; issue_number: string | null; licence_valid_from: string | null; licence_valid_to: string | null; offences: number; points: number; has_penalties: boolean; /** [] when there are none; null when the record has penalties we could not read whole. */ endorsements: LicenceEndorsement[] | null; automatic_only: boolean; entitlements: LicenceEntitlement[]; flags: { code: string; severity: 'high' | 'medium' }[]; viewed_at: string | null; /** Northern Ireland (DVA) only. */ date_of_birth?: string | null; /** Northern Ireland (DVA) only. */ address?: string | null; pdf_data_url: string | null; checked_at: string; free_checks_remaining?: number; } /** What the Security Industry Authority's register of licence holders showed. */ export interface SiaLicenceResponse { outcome: 'ACCEPTED'; title: 'SIA licence'; licence_number: string; first_name: string; surname: string; role: 'front_line' | 'non_front_line' | 'other'; role_label: string; sector: | 'door_supervision' | 'security_guarding' | 'close_protection' | 'public_space_surveillance' | 'key_holding' | 'cash_and_valuables_in_transit' | 'vehicle_immobilisation' | 'other'; sector_label: string; status: 'active' | 'expired' | 'revoked' | 'suspended' | 'unknown'; status_label: string; status_date: string | null; status_explanation: string | null; expiry_date: string | null; conditions: string[]; source: string; checked_at: string; free_checks_remaining?: number; } export interface CheckResponses { right_to_work: RightToWorkResponse; right_to_rent: RightToRentResponse; immigration_status: ImmigrationStatusResponse; driving_licence: DrivingLicenceResponse; sia_licence: SiaLicenceResponse; } export type CheckResponse = | RightToWorkResponse | ImmigrationStatusResponse | DrivingLicenceResponse | SiaLicenceResponse; /** On a driving licence error: whether DVLA or DVA has seen the check code. */ export type CheckCodeUsed = boolean | 'unknown'; export interface ApiError { code: string; message: string; /** This code's section of https://checksharecode.co.uk/docs/errors: what to do. */ docs_url?: string; request_id?: string; /** INVALID_INPUT: the request field the refusal is about. */ field?: string; upgrade_url?: string; add_card_url?: string; claim_url?: string; upgrade_urls?: Record; check_code_used?: CheckCodeUsed; first_check?: string; } export interface AsyncCheck { /** chk_... */ id: string; status: 'queued' | 'running' | 'succeeded' | 'failed'; mode: 'live' | 'test'; client_reference: string | null; callback_url: string | null; attempts: number; /** The result once `status` is succeeded; null again once purged, 7 days after. */ result: R | null; /** The error once `status` is failed. */ error: ApiError | null; result_expires_at: string | null; result_expired: boolean; created_at: string; completed_at: string | null; } export interface WebhookEvent { type: 'check.succeeded' | 'check.failed' | 'check.test'; created_at: string; /** The asynchronous check, as GET returns it. */ data: AsyncCheck; } // ---- Errors ----------------------------------------------------------------------------- /** * Any refusal from the API. Switch on `code` (INVALID_INPUT, NOT_FOUND, SHARE_CODE_UNUSABLE, * CHECK_CODE_UNUSABLE, QUOTA_EXCEEDED...): https://checksharecode.co.uk/docs/api/check#errors. */ export class CheckShareCodeError extends Error { readonly code: string; readonly status: number; /** Driving licence errors: false means send the same code again; true or "unknown", ask the driver for a new one. */ readonly checkCodeUsed: CheckCodeUsed | undefined; /** Seconds the API asked you to wait (BUSY, RATE_LIMITED). */ readonly retryAfter: number | undefined; /** X-Request-Id: quote it when you contact us. */ readonly requestId: string | undefined; /** The whole error, with upgrade_url, claim_url and the like when present. */ readonly error: ApiError; constructor(status: number, error: ApiError, retryAfter?: number, requestId?: string) { super(`${error.code}: ${error.message}`); this.name = 'CheckShareCodeError'; this.code = error.code; this.status = status; this.checkCodeUsed = error.check_code_used; this.retryAfter = retryAfter; this.requestId = requestId; this.error = error; } } /** * Whether the same request may be sent again. BUSY, TIMEOUT, INTERNAL and RATE_LIMITED may, * except a driving licence check whose code DVLA or DVA may have seen: a code works once. */ export function isRetryable(err: CheckShareCodeError, check: CheckName): boolean { if (!['BUSY', 'TIMEOUT', 'INTERNAL', 'RATE_LIMITED'].includes(err.code)) return false; if (check === 'driving_licence') return err.checkCodeUsed === false || err.checkCodeUsed === undefined; return true; } // ---- The client ------------------------------------------------------------------------- export interface ClientOptions { /** Default https://api.checksharecode.co.uk. */ baseUrl?: string; /** Per request. A live check usually takes 15 to 40 seconds. Default 60000. */ timeoutMs?: number; /** Tries per check, the first included. Default 3; 1 turns retries off. */ maxAttempts?: number; } export interface AsyncOptions { /** Where to post the result (https); else your account's default webhook URL, if any. */ callback_url?: string; /** Your own id for the check, echoed back. Never applicant data. */ client_reference?: string; /** Sending the same key again returns the first check instead of a new one. Made for you if absent. */ idempotencyKey?: string; } export interface WaitOptions { /** Between polls. Default 3000. */ intervalMs?: number; /** Give up after this long. Default 600000 (10 minutes). */ timeoutMs?: number; } const PATHS: Record = { right_to_work: '/v1/check/right-to-work', right_to_rent: '/v1/check/right-to-rent', immigration_status: '/v1/check/immigration-status', driving_licence: '/v1/check/driving-licence', sia_licence: '/v1/check/sia-licence', }; const NI_LICENCE_PATH = '/v1/check/driving-licence-ni'; // The longest Retry-After worth waiting for in a request; longer ones are thrown. const MAX_WAIT_S = 30; /** Northern Ireland licence numbers are 8 digits; GB ones always have a letter in their last 8. */ function pathFor(check: CheckName, body: object): string { if (check !== 'driving_licence') return PATHS[check]; const n = String((body as DrivingLicenceRequest).licence_number ?? '').replace(/\s/g, ''); return /^\d{8}$/.test(n) ? NI_LICENCE_PATH : PATHS.driving_licence; } const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); export class CheckShareCode { readonly baseUrl: string; private readonly apiKey: string; private readonly timeoutMs: number; private readonly maxAttempts: number; constructor(apiKey: string | undefined, options: ClientOptions = {}) { if (!apiKey) throw new Error( 'CheckShareCode: no API key (get one at https://checksharecode.co.uk/signup)', ); this.apiKey = apiKey; this.baseUrl = (options.baseUrl ?? 'https://api.checksharecode.co.uk').replace(/\/+$/, ''); this.timeoutMs = options.timeoutMs ?? 60_000; this.maxAttempts = Math.max(1, options.maxAttempts ?? 3); } /** "test" for a sandbox key (rtw_test_), "live" for a live one (rtw_live_). */ get mode(): 'live' | 'test' { return this.apiKey.startsWith('rtw_test_') ? 'test' : 'live'; } rightToWork(body: RightToWorkRequest): Promise { return this.check('right_to_work', body); } rightToRent(body: RightToRentRequest): Promise { return this.check('right_to_rent', body); } immigrationStatus(body: ImmigrationStatusRequest): Promise { return this.check('immigration_status', body); } /** * A check code works once. On CHECK_CODE_UNUSABLE, or an error whose `checkCodeUsed` is * true or "unknown", ask the driver for a new code; when it is false, send the same again. */ drivingLicence(body: DrivingLicenceRequest): Promise { return this.check('driving_licence', body); } /** A licence not on the register is a NOT_FOUND error. */ siaLicence(body: SiaLicenceRequest): Promise { return this.check('sia_licence', body); } /** Runs a check and waits for its answer, retrying what may be retried. */ async check(check: C, body: CheckRequests[C]): Promise { return this.withRetries(check, () => this.request('POST', pathFor(check, body), body)); } /** * Queues a check and answers at once (202). Get the result from `waitForCheck`, `getCheck`, * or your webhook. Live checks that take longer than your request can wait belong here. */ async startCheck( check: C, body: CheckRequests[C], options: AsyncOptions = {}, ): Promise> { const { idempotencyKey = crypto.randomUUID(), ...rest } = options; return this.withRetries(check, () => this.request( 'POST', `${pathFor(check, body)}/async`, { ...body, ...rest }, { 'idempotency-key': idempotencyKey, }, ), ); } /** An asynchronous check, by its id (chk_...). */ getCheck(id: string): Promise { return this.request('GET', `${PATHS.right_to_work}/async/${encodeURIComponent(id)}`); } /** Polls until the check has succeeded or failed, and returns it. */ async waitForCheck(id: string, options: WaitOptions = {}): Promise { const interval = options.intervalMs ?? 3000; const deadline = Date.now() + (options.timeoutMs ?? 600_000); for (;;) { const job = await this.getCheck(id); if (job.status === 'succeeded' || job.status === 'failed') return job; if (Date.now() + interval > deadline) { throw new Error(`CheckShareCode: check ${id} still ${job.status} after waiting`); } await sleep(interval); } } private async withRetries(check: CheckName, send: () => Promise): Promise { for (let attempt = 1; ; attempt++) { try { return await send(); } catch (err) { if (!(err instanceof CheckShareCodeError) || attempt >= this.maxAttempts) throw err; if (!isRetryable(err, check)) throw err; const wait = err.retryAfter ?? 2 * attempt; if (wait > MAX_WAIT_S) throw err; await sleep(wait * 1000); } } } private async request( method: 'GET' | 'POST', path: string, body?: unknown, headers: Record = {}, ): Promise { const res = await fetch(`${this.baseUrl}${path}`, { method, headers: { authorization: `Bearer ${this.apiKey}`, accept: 'application/json', ...(body === undefined ? {} : { 'content-type': 'application/json' }), ...headers, }, body: body === undefined ? null : JSON.stringify(body), signal: AbortSignal.timeout(this.timeoutMs), }); const text = await res.text(); let json: unknown = null; try { json = text ? JSON.parse(text) : null; } catch { // Not JSON: a proxy's error page, handled below. } if (res.ok) return json as T; // Not our JSON (a proxy's page): never retried, since it can't say whether a // driving licence code was used. const error = (json as { error?: ApiError } | null)?.error ?? { code: 'UNEXPECTED_RESPONSE', message: `HTTP ${res.status}: ${text.slice(0, 200)}`, }; const retryAfter = Number(res.headers.get('retry-after')); throw new CheckShareCodeError( res.status, error, Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter : undefined, res.headers.get('x-request-id') ?? undefined, ); } } // ---- Webhooks --------------------------------------------------------------------------- export class WebhookVerificationError extends Error { constructor(message: string) { super(message); this.name = 'WebhookVerificationError'; } } type HeaderSource = Headers | Record; function header(headers: HeaderSource, name: string): string | undefined { if (typeof (headers as Headers).get === 'function') return (headers as Headers).get(name) ?? undefined; const record = headers as Record; const key = Object.keys(record).find((k) => k.toLowerCase() === name); const value = key === undefined ? undefined : record[key]; return Array.isArray(value) ? value[0] : value; } function fromBase64(s: string): Uint8Array { const bin = atob(s); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; } /** * Checks a webhook's Standard Webhooks signature with your whsec_ secret (on /app/webhooks, * one for live and one for sandbox) and returns the event. Pass the raw body (a string, or * the Buffer of express.raw), exactly as it arrived: parsing and re-serialising the JSON * breaks the signature. Throws * WebhookVerificationError for a bad signature or a timestamp over 5 minutes out, so a * captured request can't be replayed. Answer 2xx within 10 seconds; the same event can * arrive more than once (dedupe on the webhook-id header). */ export async function verifyWebhook( secret: string, headers: HeaderSource, body: string | Uint8Array, options: { toleranceSeconds?: number; now?: Date } = {}, ): Promise { const id = header(headers, 'webhook-id'); const timestamp = header(headers, 'webhook-timestamp'); const signatures = header(headers, 'webhook-signature'); if (!id || !timestamp || !signatures) throw new WebhookVerificationError('missing webhook headers'); const sent = Number(timestamp); const now = Math.floor((options.now ?? new Date()).getTime() / 1000); if (!Number.isInteger(sent) || Math.abs(now - sent) > (options.toleranceSeconds ?? 300)) { throw new WebhookVerificationError('timestamp too old or too new'); } const key = await crypto.subtle.importKey( 'raw', fromBase64(secret.replace(/^whsec_/, '')), { name: 'HMAC', hash: 'SHA-256' }, false, ['verify'], ); // Sign the bytes as they arrived: decoding them first could change them. const raw = typeof body === 'string' ? new TextEncoder().encode(body) : body; const prefix = new TextEncoder().encode(`${id}.${timestamp}.`); const signed = new Uint8Array(prefix.length + raw.length); signed.set(prefix); signed.set(raw, prefix.length); for (const part of signatures.split(' ')) { const [version, mac] = part.split(','); if (version !== 'v1' || !mac) continue; let given: Uint8Array; try { given = fromBase64(mac); } catch { continue; } // crypto.subtle.verify compares in constant time. if (await crypto.subtle.verify('HMAC', key, given, signed)) return JSON.parse(new TextDecoder().decode(raw)) as WebhookEvent; } throw new WebhookVerificationError('no valid signature'); }