@patientos/public-sdk
v0.2.2
Published
Typed browser/node client for the PatientOS public booking + service-request API (/api/public).
Downloads
1,333
Maintainers
Readme
@patientos/public-sdk
A small, typed, zero-dependency client for the PatientOS public API
(/api/public/*). Embed it on a clinic's own website to run the patient-facing
flows — appointment booking and service requests (e.g. an online medical
certificate) — against the clinic's receptionist domain.
It works in the browser and in Node (SSR / tests). The transport, auth headers, token plumbing, and the error contract live in one place so each call is a thin, typed method.
Install
bun add @patientos/public-sdkQuick start
import { createPatientOSClient } from '@patientos/public-sdk'
const client = createPatientOSClient({
baseUrl: 'https://clinic.example.com', // the clinic's receptionist domain
publishableKey: 'rcp_pk_…', // the registered origin's publishable key
})
// 1. List what the clinic offers (non-PHI, cacheable).
const services = await client.listServices()
const cert = services.find((s) => s.key === 'medical-certificate')!
// 2. Establish the visitor's identity → a claim token, held by the client.
await client.startSession({ fullName: 'Pat Demo', phone: '+61400111222' })
// 3. Start the request, capture answers (with a LIVE safety-gate preview), submit.
const { requestId } = await client.startRequest({ serviceKey: cert.key })
const { gate } = await client.saveAnswers(requestId, { reason: 'Flu', days_off: 2 })
if (gate?.verdict === 'escalate') {/* show the red-flag message, stop */}
const { status } = await client.submitRequest(requestId) // 'awaiting_slot' once the fee is HELD
// 4. Pick a slot, hold it, and book.
const { slots } = await client.getAvailability({ appointmentTypeId: cert.appointmentTypeId! })
const slot = slots[0]
const hold = await client.createHold({
practitionerId: slot.practitionerId,
appointmentTypeId: cert.appointmentTypeId!,
slotStart: slot.start,
serviceRequestId: requestId,
})
const booked = await client.bookRequest(requestId, {
practitionerId: slot.practitionerId,
slotStart: slot.start,
holdId: hold.holdId,
holderToken: hold.holderToken,
})
// Verify a certificate later (tenant-less — the token is the credential).
const result = await client.verify('…token from the QR code…')Capturing identity (Medicare, consent, address)
Between saveAnswers and submitRequest, the funnel can stage three identity
fields onto the request. Each lands in the request's own landing zone and is
flushed to the durable patient (Medicare number, primary address) or a first-class
consent record when the request materialises (the ready / pre-auth elevation).
None of them block the funnel — they are optional steps, so a widget can gather
what it has and move on.
// Medicare — 'captured' | 'deferred' | 'skipped'. A captured card is
// check-digit-validated server-side; deferred/skipped carry no card fields.
await client.saveMedicare(requestId, { status: 'captured', number: '2222222201', irn: '1', expiry: '08/2027' })
// (Medicare is skippable — the patient can defer it; the flow proceeds regardless.)
// Consent — record BEFORE submit. Submit flushes the staged consent (with the
// Medicare + address) onto the patient at materialisation, so the signature must
// already be on the request. The consent IP is captured server-side (not sent).
await client.saveConsent(requestId, { policyHash: 'sha256:…', signatureName: 'Pat Demo' })
// Address — the visitor PICKS one; you never send address fields (see below).
const { suggestions } = await client.suggestAddress('1 Test St Sydney')
await client.saveAddress(requestId, {
address: suggestions[0].label,
placeId: suggestions[0].placeId,
})All three return { ok: true } on success and are claim-gated (they act on the
visitor's OWN request). A validation failure is a thrown PatientOSApiError: a bad
Medicare number → invalid_medicare (400); an address Google will not confirm →
invalid_address (400); a missing policyHash/signatureName → invalid_request
(400).
Addresses are picked, not typed (BREAKING in 0.2.0)
saveAddress used to take { line1, suburb, state, postcode }. It now takes a
reference to a Google suggestion — { address, placeId } — and the server
resolves the components itself.
- await client.saveAddress(requestId, { line1: '1 Test St', suburb: 'Sydney', state: 'NSW', postcode: '2000' })
+ const { suggestions } = await client.suggestAddress('1 Test St Sydney')
+ await client.saveAddress(requestId, { address: suggestions[0].label, placeId: suggestions[0].placeId })Why the break rather than a compatible addition. A client that can post address components is a client that can store an address nobody verified — and the record would still be labelled as verified. Accepting both shapes would have kept that door open, so there is deliberately only one way in.
You do not need a Google API key, and your domain does NOT go in the Google
Console. suggestAddress and resolveAddress proxy through the PatientOS API
using a key held server-side in Australia; your origin is already registered,
because that is how your publishable key resolves your clinic.
Two calls, matching how people actually type:
// As they type — debounce ~300ms. Returns nothing under 3 characters, and each
// call is a billed lookup, so do not fire it per keystroke.
const { suggestions } = await client.suggestAddress(query)
// When autocomplete finds nothing (rural properties, new subdivisions), confirm
// what they typed. NOT a manual-entry escape: an address Google will not confirm
// comes back with no `address`, and there is no way to store one that fails.
const { address } = await client.resolveAddress(typed)
if (address) await client.saveAddress(requestId, { address: address.formattedAddress })Both also answer { disabled: true } when the clinic has no key configured. That is
a dev-only state — production refuses to start without one — and it means "lookup is
off", NOT "fall back to your own address fields": there is no way to store an address
Google has not confirmed.
Lookups are AU-only and rate-limited per origin + IP.
Cancelling a request
Before the consult starts, the patient can cancel — this cancels any booked appointment and releases any held card pre-auth (a BPOINT Reversal, so no money is captured):
const { status, released } = await client.cancelRequest(requestId)
// status === 'cancelled'; released === true when a held pre-auth was reversed.Cancellable while the request is pre-consult — draft / payment_required /
awaiting_slot / payment_failed, or ready with a future (not-yet-started)
appointment. Once the consult has started or the outcome document has issued it is
refused with a 409 (not_cancellable). cancelRequest is idempotent — a
second cancel of an already-cancelled request also returns 'cancelled'
(released: false).
Paying for a request (BPOINT card entry + 3DS)
A paid service reports payment_required from submitRequest. There are two
ways to place the pre-auth fee hold:
payRequest(requestId)— a single-shot that opens and authorises the hold in one call. Use it with a clinic's mock provider (dev/e2e) or when no card iframe is needed. It cannot do real card entry (no card is attached).payInit→payAuthenticate→payConfirm— the real card flow (PAT-335). The card PAN is tokenised client-side against a single-use gateway AuthKey and never touches the receptionist server.
// 1. Open the pre-auth → get the client artefacts (the AuthKey to tokenise a card).
const init = await client.payInit(requestId)
// init.providerKey is 'mock' | 'bpoint'; init.amount is the fee (dollars string).
// 2. Tokenise the card CLIENT-SIDE. Loading the gateway script is YOUR job — this
// SDK is zero-dependency plain HTTP and only moves the tokens. For BPOINT, load
// https://www.bpoint.com.au/rest/clientscripts/api.js and attach the card to the
// AuthKey with the BPOINT JS (iframe-fields / attachPaymentMethod). The PAN
// stays in the browser ⟶ BPOINT; it is NEVER posted to PatientOS.
window.BPOINT.txn.authkey.attachPaymentMethod(init.clientArtifacts.authKey!, { card }, onDone)
// 3. Run the 3DS card check.
let auth = await client.payAuthenticate(requestId)
if (auth.status === 'requires_action') {
// Mount auth.clientArtifacts.iframeUrl in an <iframe>; verify postMessage
// event.origin === auth.clientArtifacts.iframeOrigin. On 'AuthenticationComplete':
auth = await client.payAuthenticate(requestId) // → 'authenticated'
}
if (auth.status === 'payment_failed') {/* card check failed — start over */}
// 4. Authorise the held pre-auth → advances the request.
const confirmed = await client.payConfirm(requestId)
// 'awaiting_slot' (scheduled) | 'ready' (on-demand/direct-issue) | 'payment_failed'
// | 'payment_pending' (in-doubt) | 'requires_action' (3DS still outstanding).payInit is idempotent — a component remount / page refresh reuses the live
session's AuthKey (init.reused === true) rather than spending a fresh one.
payConfirm also runs a defensive 3DS preflight, so it returns requires_action
(charging nothing) if you call it before completing the challenge.
How auth works
Tenant resolution is by the Origin header + publishable key, never a
session. The clinic registers each embedding origin and issues it a publishable
key (safe to ship to the browser). Requests from an unregistered origin are
refused, and the response carries no PHI.
- In the browser, the
Originheader is set by the browser automatically. - In Node / SSR / tests, pass
originso the request carries one:createPatientOSClient({ baseUrl, publishableKey, origin: 'https://clinic.example.com', fetch })
The claim token (from startSession) is held on the client and attached to
request-scoped calls as x-rcp-claim-token — including cancelRequest (a visitor
may only cancel their OWN request; a foreign claim gets a 404). Persist it across
reloads with getClaimToken() / setClaimToken(). Hold tokens (from
createHold) are passed back into bookRequest / releaseHold.
Bot protection (Cloudflare Turnstile)
A clinic can put a Cloudflare Turnstile challenge in front of the anonymous
funnel (the receptionist sets a server-side TURNSTILE_SECRET_KEY). When it does,
startSession must carry a Turnstile token or the receptionist refuses it:
await client.startSession({
fullName: 'Pat Demo',
phone: '+61400111222',
turnstileToken, // the cf-turnstile-response from the widget on YOUR page
})Rendering the widget and obtaining the token is the embedding site's job. Load
https://challenges.cloudflare.com/turnstile/v0/api.js and render the widget with
the clinic's public site key (safe to ship to the browser); read the resulting
cf-turnstile-response token and pass it as turnstileToken. This SDK is
zero-dependency and only forwards the token — the secret key never leaves the
receptionist server.
A receptionist enforcing Turnstile rejects a missing token with
captcha_required (400) and an invalid one with captcha_failed (403); when
the clinic is not enforcing Turnstile, turnstileToken is ignored (safe to
omit). Only startSession is gated — every later step (answers, submit, pay,
book) rides the claim token that a verified session mints.
Errors
Every non-2xx response is a stable { error: "<code>" } — never internal text or
PHI. The SDK surfaces that as a thrown PatientOSApiError (.status,
.code, .path); branch on err.code ('unknown_service',
'origin_not_registered', 'slot_taken', 'captcha_required',
'captcha_failed', …). A pre-HTTP failure (network down, CORS block, abort)
throws PatientOSTransportError.
Example site
examples/booking-widget is a runnable "clinic website" that embeds this SDK to
drive the full medical-certificate flow. It's served on :3000 (a seeded
registered origin) and is exercised in a real browser by
apps/web/tests/e2e/sdk-widget.spec.ts, which proves the cross-origin path
(CORS preflight, ACAO reflection, the whole flow) against the live worker.
Not yet included (next cut)
This package is the headless client — the foundation. Planned on top of it:
embed.js— a single<script>tag that auto-mounts a prebuilt widget (no build step on the clinic's side).- Builder components — React
Booking/CertRequestcomponents for the in-app website builder. - A question-set schema read.
GET /servicesreturns a service'squestionSetIdbut not the question definitions, so a widget can't yet render an arbitrary clinic's intake form generically — the example hard-codes the med-cert questions to match the seed. A publicGET /services/:key(or a question-set read) that returns the non-PHI question schema is the unlock.
