@esushealth/sdk 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Esus Health
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,150 @@
1
- # Temporary Holding Version
1
+ # Esus SDK for TypeScript
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Server integrations and app user sessions for Esus Health.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install @esushealth/sdk
9
+ ```
10
+
11
+ Requires Node.js 22 or later and ES modules. Keep API keys and session tokens on the server. Start with synthetic data.
12
+
13
+ ## Work with a patient
14
+
15
+ Authorize the caller in your application before making clinical requests. An API key grants the integration its own permissions.
16
+
17
+ ```ts
18
+ import { createServiceClient } from "@esushealth/sdk/server";
19
+
20
+ const esus = createServiceClient({ url, organizationId, apiKey });
21
+ await esus.validateConnection();
22
+ const created = await esus.fhir.create("Patient", {
23
+ name: [{ family: "Synthetic" }],
24
+ });
25
+ const { patient, etag } = await esus.fhir.read("Patient", created.id);
26
+ ```
27
+
28
+ Use `fhir.search` to search any resource in `fhirResources`. API-key clients support search, read, create, update, both PATCH formats, delete, history, and version reads. SMART clients default to reads. Set `enableWrites: true` when the integration expects write permissions; Esus checks the token's grant on every request.
29
+
30
+ FHIR can read and update the current `Organization`. Create and delete organizations through organization management.
31
+
32
+ Use `validateConnection({ resources: ["Patient", "Observation"] })` to confirm permissions by resource. The API can still restrict individual records by consent or patient launch context.
33
+
34
+ Use `fhir.operation` for registered operations such as `fhir.operation("GET /fhir/Patient/:id/$everything", { params: { id } })`. The response includes the status, headers, and body. Bulk export downloads return a readable NDJSON stream. Pass an abort signal to cancel the download while reading it. SMART can call `Patient/$everything` with a wildcard read grant. A patient-scoped grant still limits the request to the launch patient.
35
+
36
+ Esus bulk exports contain FHIR resources in NDJSON and require dedicated export permissions. The kickoff returns a `Content-Location` header. Extract the job ID and pass it to the SDK's status and download operations. Both kickoff routes export within the organization. The `patient` filter is currently unsupported.
37
+
38
+ ## Public status and plans
39
+
40
+ Use `createPublicClient({ url })` to read health and the published plan catalog without credentials. `health.ready()` returns the readiness payload and its HTTP status, including `503` for a critical outage. Use `health.history({ days: 90, bucket: "1d" })` for a daily history. Buckets of one or five minutes allow up to 31 days.
41
+
42
+ ## Organization operations
43
+
44
+ Use `service.organization` with a server API key. `audit.searchEvents()` and `audit.emailLog()` accept filters and return an opaque `nextCursor`. The email log includes delivery metadata such as the recipient, template, status, and timestamps. Both operations require `AuditEvent.read`.
45
+
46
+ The offset-based `audit.searchLogs()`, `audit.forPatient()`, and `audit.forUser()` use the same scope. The `entity` filter accepts a resource type or an ID.
47
+
48
+ Use `billing.plan()`, `billing.usage()`, `billing.usageHistory()`, and `billing.quota()` with `Billing.read`. A limit of `-1` means unlimited.
49
+
50
+ Use `cors.list()` and `cors.replace({ origins })` with `Organization.update`. Replacement applies the full list to the organization configured for this client.
51
+
52
+ Register and manage clients with `smartApps` and the applicable `SmartApp` scopes. Keep the client secret returned by `smartApps.create()` in server-side secret storage. The API returns it once.
53
+
54
+ ## Tenant app management
55
+
56
+ Use `service.tenantApps` from your server with a key granted the required `TenantApp` actions. `list()` returns both the public sign-in ID and the internal UUID. Pass the internal UUID to `forApp(id)` to configure the app, onboard users, manage application roles, or send and track invitations. The public ID can identify the app for an app-scoped key. Scope management to your own authorized callers and use the narrowest API key permissions.
57
+
58
+ Listing apps requires `TenantApp.read`, linking a user to a record requires `TenantApp.update`, and assigning a role or sending an invitation requires `TenantApp.create`.
59
+
60
+ App roles and their assignments belong to the organization. Use role permissions in your application's UI and authorization. Esus applies its own access rules and clinical consent requirements.
61
+
62
+ Bulk invitations report individual successes and failures. Resending an invitation replaces its ID and its link. Use `app.invitations.list()` to find the current ID before revoking it.
63
+
64
+ ## App user sessions
65
+
66
+ Use `createAppSessionClient({ url, appId })` for password login, MFA, refresh, profile, and logout. This API is experimental. Your application manages token storage and coordinates concurrent refresh requests. Persist both rotated tokens after a successful refresh.
67
+
68
+ The same client handles account email. Use `signUp` to create an app user and check `emailVerificationRequired`. Use `requestEmailCode` and `verifyEmail` for verification, or `requestEmailCode` and `confirmPasswordReset` for password recovery. Email changes require an app user's access token and use `requestEmailChange` followed by `confirmEmailChange`. Pass the Turnstile token when required by the app's anti-abuse settings. An accepted code request returns a generic response.
69
+
70
+ Use `verifyInvitation(inviteToken)` to validate an invitation for this app before rendering the signup form. Pass the same token to `signUp` with the invited email and password.
71
+
72
+ For Google sign-in, enable Google for the tenant app and add your app's callback to its redirect allowlist. Redirect the browser to `app.googleSignInUrl(callbackUrl)`. In the callback, pass the returned code to `app.exchangeGoogleCode(code)` on your server. Esus binds the code to the app that issued it and accepts it once. Handle the resulting session or MFA challenge the same way as password sign-in.
73
+
74
+ Use the app user's access token with `listSessions`, `revokeSession`, and `revokeAllSessions` to manage active devices. The account methods also support profile updates, password changes, and deletion with the proof required by Esus.
75
+
76
+ ## Account security
77
+
78
+ Use `app.mfa.setup` and `app.mfa.enable` to enroll an authenticator. Show the setup secret and recovery codes only to the signed-in user. Use `app.mfa.status` to read the current state, `app.mfa.regenerateRecoveryCodes` to replace codes, and `app.mfa.disable` with the required password and code. Use `requestAccountDeletionCode` when the account deletion flow requires email proof.
79
+
80
+ Enable WebAuthn in your Esus tenant app settings. Use `app.passkeys.startRegistration` or `app.passkeys.startLogin` to get the ceremony options from your server. Pass the options through your app to the browser, use the WebAuthn credential API, and send the credential JSON to `completeRegistration` or `completeLogin` on the server. The app user session is required for registration, listing, and removing keys. Registration also requires account step-up. [WebAuthn specification](https://www.w3.org/TR/webauthn-3/)
81
+
82
+ ## Linked patient records
83
+
84
+ Use the same app session client to read the user's linked Patient or Practitioner and search the current patient's records. The API resolves the patient from the signed-in user.
85
+
86
+ ```ts
87
+ const profile = await app.records.profile(accessToken);
88
+ const { resources } = await app.records.search(accessToken, "Observation", { _count: 20 });
89
+ ```
90
+
91
+ Use `patientPortalResources` to discover supported searches. The current user can review consent through `records.search(accessToken, "Consent")` and revoke their own consent through `records.revokeConsent`.
92
+
93
+ ## Files
94
+
95
+ Authorize the action in your application, then use a server API key with `File.create`, `File.read`, or `File.delete` as needed.
96
+
97
+ ```ts
98
+ const uploaded = await esus.files.upload(file);
99
+ const { body, headers } = await esus.files.download(uploaded.id);
100
+ return new Response(body, { headers: {
101
+ "content-type": headers.get("content-type")!,
102
+ "content-disposition": headers.get("content-disposition")!,
103
+ } });
104
+ ```
105
+
106
+ Store the returned file ID for downloads and deletion. The download uses a stream and carries the API's attachment headers. The request timeout covers the wait for response headers. Pass an abort signal to cancel the download after it starts.
107
+
108
+ ## Queue and pharmacy
109
+
110
+ Use the service client with a server API key. Queue board, waiting list, and statistics need `Queue.read`. Check-in, call, start, complete, and no-show need `Queue.create`. Pharmacy stock, low-stock, and expiring queries need `Pharmacy.read`. Restock, dispense, and adjustments need `Pharmacy.create`. Check the caller's permissions in your application before running these actions.
111
+
112
+ ```ts
113
+ const board = await esus.queue.board({ locationId });
114
+ const inventory = await esus.pharmacy.stock({ locationId, medicationId });
115
+ ```
116
+
117
+ ## Receive webhooks
118
+
119
+ Register the callback in your tenant app's webhook settings. Keep the signing secret in your server configuration. Use the internal app UUID shown in the webhook configuration for `appId`.
120
+
121
+ ```ts
122
+ import { verifyWebhook } from "@esushealth/sdk/server";
123
+
124
+ const body = new Uint8Array(await request.arrayBuffer());
125
+ const verified = await verifyWebhook(request.headers, body, { appId, secret });
126
+ if (!verified) return new Response(null, { status: 401 });
127
+
128
+ await applyEventOnce(verified.deliveryId, verified.event);
129
+ return new Response(null, { status: 204 });
130
+ ```
131
+
132
+ Read the original request bytes before parsing JSON. Base routing on the signed event's `type`. Persist `deliveryId` together with processing so retries are idempotent. The signature accepts a five-minute time window by default.
133
+
134
+ ## Manage webhook subscriptions
135
+
136
+ Use `esus.webhooks(appId)` on a service client. Grant the API key only the `TenantApp` permissions the integration needs. Use the app's internal UUID in the service client configuration for an app-scoped key.
137
+
138
+ ```ts
139
+ const hooks = esus.webhooks(appId);
140
+ const subscription = await hooks.create({ url: callbackUrl, events: ["user.created"] });
141
+ await storeSigningSecret(subscription.secret);
142
+ const { deliveryId } = await hooks.ping(subscription.id);
143
+ const recent = await hooks.deliveries(subscription.id, { limit: 10 });
144
+ ```
145
+
146
+ Read subscriptions with `list` and `get`. Use `update(id, { rotateSecret: true })` to rotate the secret and `delete` to remove a subscription. Save the secret immediately when creating or rotating a subscription. Reads omit it.
147
+
148
+ ## License
149
+
150
+ [MIT](LICENSE) · [Esus Health](https://esus.health)
@@ -0,0 +1,225 @@
1
+ import { type IntegrationInputs, type IntegrationResults, type PatientPortalResource } from "./integration-contract.js";
2
+ import { type FhirSearchFilters } from "./fhir.js";
3
+ import { type RequestOptions, type TransportOptions } from "./transport.js";
4
+ export type AppSession = Readonly<{
5
+ accessToken: string;
6
+ refreshToken: string;
7
+ expiresIn: number;
8
+ tokenType: "Bearer";
9
+ }>;
10
+ export type MfaChallenge = Readonly<{
11
+ mfaRequired: true;
12
+ mfaToken: string;
13
+ expiresIn: number;
14
+ }>;
15
+ type AppRole = Readonly<{
16
+ name: string;
17
+ isStaff: boolean;
18
+ permissions: readonly {
19
+ resource: string;
20
+ action: string;
21
+ }[];
22
+ }>;
23
+ export type AppUser = Readonly<{
24
+ id: string;
25
+ email: string;
26
+ firstName: string | null;
27
+ lastName: string | null;
28
+ avatarUrl: string | null;
29
+ emailVerified: boolean;
30
+ patientId: string | null;
31
+ practitionerId: string | null;
32
+ isActive: boolean;
33
+ lastLoginAt: string | null;
34
+ createdAt: string;
35
+ roles: readonly AppRole[];
36
+ }>;
37
+ type AppSessionOptions = Omit<TransportOptions, "organizationId"> & {
38
+ appId: string;
39
+ };
40
+ type AppRequestOptions = RequestOptions & {
41
+ userAgent?: string;
42
+ };
43
+ type EmailRequestOptions = AppRequestOptions & {
44
+ turnstileToken?: string;
45
+ };
46
+ type AppPost<Path extends string> = IntegrationInputs[`POST /v1/auth/${Path}` & keyof IntegrationInputs];
47
+ type SessionList = IntegrationResults["GET /v1/auth/sessions"]["body"];
48
+ export type AppSessionDevice = SessionList["sessions"][number];
49
+ export type AppPasskey = IntegrationResults["POST /v1/auth/me/webauthn/register/verify"]["body"];
50
+ export type AppInvitation = IntegrationResults["GET /v1/auth/user-invite/:token"]["body"];
51
+ type PortalFilters<R extends PatientPortalResource> = Omit<FhirSearchFilters<R>, "patient" | "subject">;
52
+ /** Server-side client. The host application owns token persistence and refresh coordination. */
53
+ export declare function createAppSessionClient(options: AppSessionOptions): {
54
+ verifyInvitation(token: string, options?: AppRequestOptions): Promise<AppInvitation>;
55
+ signUp(input: AppPost<"signup">, options?: EmailRequestOptions): Promise<{
56
+ appUserId: string;
57
+ emailVerificationRequired: boolean;
58
+ }>;
59
+ requestEmailCode(input: AppPost<"otp/request">, options?: EmailRequestOptions): Promise<{
60
+ message: string;
61
+ }>;
62
+ verifyEmail(input: AppPost<"email/verify">, options?: AppRequestOptions): Promise<{
63
+ userId: string;
64
+ }>;
65
+ confirmPasswordReset(input: AppPost<"password/reset/confirm">, options?: AppRequestOptions): Promise<void>;
66
+ requestEmailChange(accessToken: string, input: AppPost<"email/change">, options?: AppRequestOptions): Promise<void>;
67
+ confirmEmailChange(accessToken: string, code: AppPost<"email/change/verify">["code"], options?: AppRequestOptions): Promise<void>;
68
+ signInWithPassword(credentials: {
69
+ email: string;
70
+ password: string;
71
+ }, options?: AppRequestOptions): Promise<Readonly<{
72
+ accessToken: string;
73
+ refreshToken: string;
74
+ expiresIn: number;
75
+ tokenType: "Bearer";
76
+ }> | Readonly<{
77
+ mfaRequired: true;
78
+ mfaToken: string;
79
+ expiresIn: number;
80
+ }>>;
81
+ googleSignInUrl(returnTo: string): URL;
82
+ exchangeGoogleCode(code: AppPost<"google/exchange">["code"], options?: AppRequestOptions): Promise<Readonly<{
83
+ accessToken: string;
84
+ refreshToken: string;
85
+ expiresIn: number;
86
+ tokenType: "Bearer";
87
+ }> | Readonly<{
88
+ mfaRequired: true;
89
+ mfaToken: string;
90
+ expiresIn: number;
91
+ }>>;
92
+ verifyMfa(challenge: {
93
+ mfaToken: string;
94
+ code: string;
95
+ }, options?: AppRequestOptions): Promise<Readonly<{
96
+ accessToken: string;
97
+ refreshToken: string;
98
+ expiresIn: number;
99
+ tokenType: "Bearer";
100
+ }>>;
101
+ mfa: {
102
+ status(accessToken: string, options?: AppRequestOptions): Promise<{
103
+ enabled: boolean;
104
+ recoveryCodesRemaining: number;
105
+ }>;
106
+ setup(accessToken: string, input: AppPost<"mfa/setup">, options?: AppRequestOptions): Promise<{
107
+ secret: string;
108
+ otpauthUri: string;
109
+ }>;
110
+ enable(accessToken: string, input: AppPost<"mfa/enable">, options?: AppRequestOptions): Promise<{
111
+ recoveryCodes: string[];
112
+ }>;
113
+ disable(accessToken: string, input: AppPost<"mfa/disable">, options?: AppRequestOptions): Promise<void>;
114
+ regenerateRecoveryCodes(accessToken: string, input: AppPost<"mfa/recovery-codes/regenerate">, options?: AppRequestOptions): Promise<{
115
+ recoveryCodes: string[];
116
+ }>;
117
+ };
118
+ passkeys: {
119
+ startLogin(input?: AppPost<"webauthn/login/options">, options?: AppRequestOptions): Promise<PublicKeyCredentialRequestOptionsJSON>;
120
+ completeLogin(input: AppPost<"webauthn/login/verify">, options?: AppRequestOptions): Promise<Readonly<{
121
+ accessToken: string;
122
+ refreshToken: string;
123
+ expiresIn: number;
124
+ tokenType: "Bearer";
125
+ }>>;
126
+ startRegistration(accessToken: string, input: AppPost<"me/webauthn/register/options">, options?: AppRequestOptions): Promise<PublicKeyCredentialCreationOptionsJSON>;
127
+ completeRegistration(accessToken: string, input: AppPost<"me/webauthn/register/verify">, options?: AppRequestOptions): Promise<{
128
+ readonly id: string;
129
+ readonly label: string | null;
130
+ readonly deviceType: string | null;
131
+ readonly backedUp: boolean;
132
+ readonly createdAt: string;
133
+ readonly lastUsedAt: string | null;
134
+ }>;
135
+ list(accessToken: string, options?: AppRequestOptions): Promise<{
136
+ readonly id: string;
137
+ readonly label: string | null;
138
+ readonly deviceType: string | null;
139
+ readonly backedUp: boolean;
140
+ readonly createdAt: string;
141
+ readonly lastUsedAt: string | null;
142
+ }[]>;
143
+ remove(accessToken: string, id: string, options?: AppRequestOptions): Promise<void>;
144
+ };
145
+ refreshSession(refreshToken: string, options?: AppRequestOptions): Promise<Readonly<{
146
+ accessToken: string;
147
+ refreshToken: string;
148
+ expiresIn: number;
149
+ tokenType: "Bearer";
150
+ }>>;
151
+ getUser(accessToken: string, options?: AppRequestOptions): Promise<Readonly<{
152
+ id: string;
153
+ email: string;
154
+ firstName: string | null;
155
+ lastName: string | null;
156
+ avatarUrl: string | null;
157
+ emailVerified: boolean;
158
+ patientId: string | null;
159
+ practitionerId: string | null;
160
+ isActive: boolean;
161
+ lastLoginAt: string | null;
162
+ createdAt: string;
163
+ roles: readonly AppRole[];
164
+ }>>;
165
+ updateUser(accessToken: string, input: IntegrationInputs["PATCH /v1/auth/me"], options?: AppRequestOptions): Promise<Readonly<{
166
+ id: string;
167
+ email: string;
168
+ firstName: string | null;
169
+ lastName: string | null;
170
+ avatarUrl: string | null;
171
+ emailVerified: boolean;
172
+ patientId: string | null;
173
+ practitionerId: string | null;
174
+ isActive: boolean;
175
+ lastLoginAt: string | null;
176
+ createdAt: string;
177
+ roles: readonly AppRole[];
178
+ }>>;
179
+ changePassword(accessToken: string, input: IntegrationInputs["POST /v1/auth/password/change"], options?: AppRequestOptions): Promise<void>;
180
+ deleteAccount(accessToken: string, proof: IntegrationInputs["DELETE /v1/auth/me"], options?: AppRequestOptions): Promise<void>;
181
+ requestAccountDeletionCode(accessToken: string, options?: AppRequestOptions): Promise<void>;
182
+ listSessions(accessToken: string, options?: AppRequestOptions): Promise<SessionList>;
183
+ revokeSession(accessToken: string, sessionId: string, options?: AppRequestOptions): Promise<void>;
184
+ revokeAllSessions(accessToken: string, options?: AppRequestOptions): Promise<void>;
185
+ records: {
186
+ profile(accessToken: string, options?: AppRequestOptions): Promise<{
187
+ kind: "none";
188
+ resource: null;
189
+ } | {
190
+ kind: "patient";
191
+ resource: import("./fhir.js").Patient;
192
+ } | {
193
+ kind: "practitioner";
194
+ resource: Readonly<{
195
+ resourceType: "Practitioner";
196
+ id: string;
197
+ meta?: Readonly<{
198
+ versionId?: string;
199
+ lastUpdated?: string;
200
+ }>;
201
+ }> & {
202
+ readonly active?: boolean;
203
+ readonly identifier?: import("./fhir-contract.js").FhirCreateInputs["Practitioner"]["identifier"];
204
+ readonly name?: import("./fhir-contract.js").FhirCreateInputs["Practitioner"]["name"];
205
+ readonly telecom?: import("./fhir-contract.js").FhirCreateInputs["Practitioner"]["telecom"];
206
+ readonly gender?: string;
207
+ readonly birthDate?: string;
208
+ readonly address?: import("./fhir-contract.js").FhirCreateInputs["Practitioner"]["address"];
209
+ readonly qualification?: import("./fhir-contract.js").FhirCreateInputs["Practitioner"]["qualification"];
210
+ readonly communication?: import("./fhir-contract.js").FhirCreateInputs["Practitioner"]["communication"];
211
+ } & Readonly<Record<string, unknown>>;
212
+ }>;
213
+ read<R extends "Patient" | "Practitioner">(accessToken: string, kind: R, options?: AppRequestOptions): Promise<{
214
+ resource: import("./fhir.js").FhirResource<R>;
215
+ etag: string | null;
216
+ }>;
217
+ search<R extends PatientPortalResource>(accessToken: string, kind: R, filters?: PortalFilters<NoInfer<R>>, options?: AppRequestOptions): Promise<{
218
+ resources: import("./fhir.js").FhirResource<R>[];
219
+ total: number | undefined;
220
+ }>;
221
+ revokeConsent(accessToken: string, id: string, options?: AppRequestOptions): Promise<void>;
222
+ };
223
+ signOut(session: Pick<AppSession, "accessToken" | "refreshToken">, options?: AppRequestOptions): Promise<void>;
224
+ };
225
+ export {};