@healthier-business/hub-sdk 0.3.0 → 0.4.1
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/README.md +17 -3
- package/dist/cjs/browser/index.d.ts +2 -2
- package/dist/cjs/browser/mount.d.ts +2 -0
- package/dist/cjs/browser/mount.js +3 -0
- package/dist/cjs/client.d.ts +4 -1
- package/dist/cjs/client.js +4 -0
- package/dist/cjs/core/env.d.ts +15 -0
- package/dist/cjs/core/env.js +68 -0
- package/dist/cjs/embed/handler.d.ts +5 -1
- package/dist/cjs/embed/protocol.d.ts +6 -1
- package/dist/cjs/generated/types.d.ts +1 -1
- package/dist/cjs/index.d.ts +1 -1
- package/dist/cjs/index.js +2 -1
- package/dist/cjs/version.d.ts +1 -1
- package/dist/cjs/version.js +1 -1
- package/dist/cjs/webhooks.d.ts +36 -1
- package/dist/cjs/webhooks.js +48 -0
- package/dist/esm/browser/index.d.ts +2 -2
- package/dist/esm/browser/mount.d.ts +2 -0
- package/dist/esm/browser/mount.js +3 -0
- package/dist/esm/client.d.ts +4 -1
- package/dist/esm/client.js +5 -1
- package/dist/esm/core/env.d.ts +15 -0
- package/dist/esm/core/env.js +64 -0
- package/dist/esm/embed/handler.d.ts +5 -1
- package/dist/esm/embed/protocol.d.ts +6 -1
- package/dist/esm/generated/types.d.ts +1 -1
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/version.d.ts +1 -1
- package/dist/esm/version.js +1 -1
- package/dist/esm/webhooks.d.ts +36 -1
- package/dist/esm/webhooks.js +47 -0
- package/dist/iife/hb-embed.min.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -54,7 +54,7 @@ Create the client once and reuse it.
|
|
|
54
54
|
| Option | Default | |
|
|
55
55
|
| --- | --- | --- |
|
|
56
56
|
| `apiKey` | `HB_API_KEY` | Your key, `hbk_...`. A [sandbox](#sandbox) key starts `hbk_test_`. |
|
|
57
|
-
| `baseUrl` | `HB_BASE_URL`, then `https://hub.hbcompliance.co.uk` | A `hbk_test_` key needs the [sandbox](#sandbox) address, `https://dev.hbcompliance.co.uk/sandbox`. |
|
|
57
|
+
| `baseUrl` | `HB_BASE_URL`, then `https://hub.hbcompliance.co.uk` | A `hbk_test_` key needs the [sandbox](#sandbox) address, `https://dev.hbcompliance.co.uk/sandbox`. Your key and tokens are sent to this host, so the SDK warns once (through `logger.warn`, else `console.warn`) when it is not a `*.hbcompliance.co.uk` address or localhost, and keeps working. |
|
|
58
58
|
| `timeoutMs` | 30 000 | Per attempt. |
|
|
59
59
|
| `maxRetries` | 2 | See [Retries](#retries-timeouts-and-idempotency). |
|
|
60
60
|
| `tokenStore` | memory | See [Serverless](#serverless-and-token-storage). |
|
|
@@ -93,6 +93,8 @@ For anything the typed methods do not cover yet:
|
|
|
93
93
|
const body = await hb.request({ method: 'GET', path: '/api/v2/something-new', query: { a: 1 } });
|
|
94
94
|
```
|
|
95
95
|
|
|
96
|
+
`path` must start with `/` and may not contain `..` segments, `@`, a backslash or a scheme: the SDK throws a `ConfigError` before sending anything, so a path (for example one built from user input) can never send your key to another host.
|
|
97
|
+
|
|
96
98
|
## Pagination
|
|
97
99
|
|
|
98
100
|
A list method returns a `PagePromise`. `await` it for one page, or iterate it for every item:
|
|
@@ -118,7 +120,7 @@ Everything the Hub refuses is an `ApiError` with `status`, `code` (the stable `s
|
|
|
118
120
|
| `NotFoundError` (404), `ConflictError` (409) | |
|
|
119
121
|
| `EmbedAccessError` (409, a `ConflictError`) | An embed session was refused because the candidate's access is not in place. `error.access` is `{ state, payer, next }`. See [Access, payment and renewal](#access-payment-and-renewal). |
|
|
120
122
|
| `InsufficientCreditsError` (402) | Nothing was charged. |
|
|
121
|
-
| `RateLimitError` (429) | After the SDK ran out of retries. `retryAfterSeconds` is set. |
|
|
123
|
+
| `RateLimitError` (429) | After the SDK ran out of retries. `retryAfterSeconds` is set. Also `rate_limited` on `hb.trainingVerification.verifications.create` when more than 30 automatic (`request_type: 'auto'`) requests are submitted by one key in an hour: wait, then submit again. |
|
|
122
124
|
| `GoneError` (410) | For example `session_expired`. |
|
|
123
125
|
| `ServerError` (5xx) | Quote `requestId` to support. |
|
|
124
126
|
| `NetworkError` | No answer or a timeout. For a write the outcome is unknown: repeat it with the same idempotency key. |
|
|
@@ -217,7 +219,16 @@ app.post('/hooks/hub', express.raw({ type: 'application/json' }), (req, res) =>
|
|
|
217
219
|
});
|
|
218
220
|
```
|
|
219
221
|
|
|
220
|
-
`constructEvent(rawBody, headers, secret, { toleranceSeconds })` checks `X-Hub-Signature` (`sha256=` and the HMAC-SHA256 of `{X-Hub-Timestamp}.{raw body}`) in constant time, and rejects a timestamp more than 300 seconds from now (change it with `toleranceSeconds`). `headers` can be a Node headers object, a Fetch `Headers`, or `{ signature, timestamp }`. It throws `WebhookSignatureError` with a `reason` (`signature_mismatch`, `timestamp_outside_tolerance`, `malformed_header`, `missing_timestamp`, `invalid_body`). Pass the raw bytes, not parsed JSON. It is synchronous and needs no `node:crypto`, so it runs on Node, Bun, Deno and Workers.
|
|
222
|
+
`constructEvent(rawBody, headers, secret, { toleranceSeconds })` checks `X-Hub-Signature` (`sha256=` and the HMAC-SHA256 of `{X-Hub-Timestamp}.{raw body}`) in constant time, and rejects a timestamp more than 300 seconds from now (change it with `toleranceSeconds`). `headers` can be a Node headers object, a Fetch `Headers`, or `{ signature, timestamp }`. It throws `WebhookSignatureError` with a `reason` (`signature_mismatch`, `timestamp_outside_tolerance`, `malformed_header`, `missing_timestamp`, `invalid_body`). Pass the raw bytes, not parsed JSON. It is synchronous and needs no `node:crypto`, so it runs on Node, Bun, Deno and Workers. The signature check does not stop a **replay**: the Hub delivers at least once, a retry is signed afresh, and a captured delivery is valid again for 300 seconds. Handle each `event_id` (also sent as `X-Hub-Event-Id`) once. For a single process, `createEventDeduper()` does it:
|
|
223
|
+
|
|
224
|
+
```ts
|
|
225
|
+
import { createEventDeduper } from '@healthier-business/hub-sdk';
|
|
226
|
+
|
|
227
|
+
const deduper = createEventDeduper(); // remembers ids for 90 minutes (ttlSeconds), at most 10 000 (maxEntries)
|
|
228
|
+
// after constructEvent: if (deduper.isDuplicate(event.event_id)) return res.sendStatus(200);
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
It is in memory, so on serverless or with several instances keep the ids in a shared store instead (Redis, or a unique column in your database).
|
|
221
232
|
|
|
222
233
|
`hb.webhooks.sign(body, secret)` makes signed headers for your own tests.
|
|
223
234
|
|
|
@@ -227,6 +238,8 @@ Clients who run their own system can show Healthier Business content inside it.
|
|
|
227
238
|
|
|
228
239
|
**Set up once.** The API key needs the scope `online-training:embed:create` and/or `occupational-health:embed:create`, and your website's address (scheme, host and port, for example `https://learn.example.com`) must be added under **Developer > Embed** in Hub. A session is only created for a registered address.
|
|
229
240
|
|
|
241
|
+
**Always set `allowedOrigins` in production.** If you leave it out, the SDK trusts the `Origin` header of each request, so any website visited by a signed-in user of your system can ask your route for a session and show the frame, and your `authorize` callback is the only check left. (The default is unchanged so existing integrations keep working.)
|
|
242
|
+
|
|
230
243
|
**1. On your server**, make one route. You decide who is signed in; the browser never chooses the candidate.
|
|
231
244
|
|
|
232
245
|
```ts
|
|
@@ -289,6 +302,7 @@ Every event below is sent by the Hub frame. The callbacks (`onProgress`, `onComp
|
|
|
289
302
|
| `completed` | The learner finished the course. Final. | `{ courseId }`: the Online Training course id of the session. |
|
|
290
303
|
| `passed` / `failed` | The learner submitted the test. Final. | `{ score, passMark }`: both percentages, `score` with one decimal. The frame does not say how many attempts are left. |
|
|
291
304
|
| `submitted` | The OH form was submitted. Final. | `{ requestId }`: the numeric OH request id. |
|
|
305
|
+
| `test-requested` | **Course only.** The learner pressed a Take test button in a lesson. Not final: the course session stays open. Open the test with `createTestSession` for the same `courseId`. Sent by the browser, so use it to change the screen, not to decide anything. | `{ courseId, testId }`: the Online Training course id of the session, and the Hub test id. |
|
|
292
306
|
| `terms-accepted` | The candidate accepted the Hub terms on the first screen of the frame. Not final: the content follows. | `{ version, acceptedAt }`: the terms version and an ISO 8601 time. |
|
|
293
307
|
| `error` | The frame could not show the session, or a call was refused after it started. | `{ code }`, plus a plain-words `message` added by the SDK, and `details` (`{ state, payer, next }`) for the four access codes. See [Troubleshooting](#troubleshooting). |
|
|
294
308
|
| `token-expiring` | About 2 minutes before the frame's access ends. The SDK renews it for you; you only see the event. | `{ expires_at }`: ISO 8601. |
|
|
@@ -4,6 +4,6 @@ export { cleanAccessDetails, EMBED_ACCESS_CODES, embedErrorHint, isEmbedSession,
|
|
|
4
4
|
/** `HealthierBusiness.mount(element, options)` for the browser. It holds no API key and cannot make API calls. */
|
|
5
5
|
export declare const HealthierBusiness: {
|
|
6
6
|
readonly mount: typeof mount;
|
|
7
|
-
readonly version: "0.
|
|
7
|
+
readonly version: "0.4.1";
|
|
8
8
|
};
|
|
9
|
-
export declare const version = "0.
|
|
9
|
+
export declare const version = "0.4.1";
|
|
@@ -36,6 +36,8 @@ export interface MountOptions {
|
|
|
36
36
|
onPassed?: (data: EmbedEventMap['passed']) => void;
|
|
37
37
|
onFailed?: (data: EmbedEventMap['failed']) => void;
|
|
38
38
|
onSubmitted?: (data: EmbedEventMap['submitted']) => void;
|
|
39
|
+
/** The learner pressed a Take test button in a lesson: open that course's test (`createTestSession` with the same `courseId`). */
|
|
40
|
+
onTestRequested?: (data: EmbedEventMap['test-requested']) => void;
|
|
39
41
|
/** The candidate accepted the Hub terms in the frame. */
|
|
40
42
|
onTermsAccepted?: (data: EmbedEventMap['terms-accepted']) => void;
|
|
41
43
|
onError?: (error: EmbedEventMap['error']) => void;
|
package/dist/cjs/client.d.ts
CHANGED
|
@@ -11,7 +11,8 @@ export interface HealthierBusinessOptions {
|
|
|
11
11
|
apiKey?: string;
|
|
12
12
|
/**
|
|
13
13
|
* The Hub address. Defaults to `HB_BASE_URL`, then to production. Sandbox keys (`hbk_test_`) need the sandbox
|
|
14
|
-
* address shown on the developer portal.
|
|
14
|
+
* address shown on the developer portal. Your key and tokens are sent to this host: the SDK warns once (through
|
|
15
|
+
* `logger.warn`, else `console.warn`) when it is not a `hbcompliance.co.uk` address or localhost, and still works.
|
|
15
16
|
*/
|
|
16
17
|
baseUrl?: string;
|
|
17
18
|
/** Per-attempt timeout in milliseconds. Default 30 000. */
|
|
@@ -62,6 +63,8 @@ export declare class HealthierBusiness {
|
|
|
62
63
|
/**
|
|
63
64
|
* A call to any path of the API, for something the typed methods do not cover yet. Returns the parsed body.
|
|
64
65
|
* Writes get an Idempotency-Key automatically unless you pass `options.idempotencyKey`.
|
|
66
|
+
* `path` must start with `/` and may not contain `..` segments, `@`, a backslash or a scheme (a `ConfigError` is
|
|
67
|
+
* thrown before anything is sent), so a path can never send your key to another host.
|
|
65
68
|
*/
|
|
66
69
|
request<T = unknown>(req: {
|
|
67
70
|
method: HubRequest['method'];
|
package/dist/cjs/client.js
CHANGED
|
@@ -49,6 +49,7 @@ class HealthierBusiness {
|
|
|
49
49
|
this.environment = (0, env_js_1.detectEnvironment)(this.baseUrl, key);
|
|
50
50
|
this.keyPrefix = key.display;
|
|
51
51
|
const logger = options.logger ?? logger_js_1.silentLogger;
|
|
52
|
+
(0, env_js_1.warnIfUnexpectedHost)(this.baseUrl, (message) => (options.logger ? options.logger.warn(message) : console.warn(message)));
|
|
52
53
|
const userAgent = `healthier-business-hub-sdk-js/${version_js_1.VERSION}`;
|
|
53
54
|
this.tokens = new tokens_js_1.TokenManager({
|
|
54
55
|
apiKey,
|
|
@@ -92,12 +93,15 @@ class HealthierBusiness {
|
|
|
92
93
|
/**
|
|
93
94
|
* A call to any path of the API, for something the typed methods do not cover yet. Returns the parsed body.
|
|
94
95
|
* Writes get an Idempotency-Key automatically unless you pass `options.idempotencyKey`.
|
|
96
|
+
* `path` must start with `/` and may not contain `..` segments, `@`, a backslash or a scheme (a `ConfigError` is
|
|
97
|
+
* thrown before anything is sent), so a path can never send your key to another host.
|
|
95
98
|
*/
|
|
96
99
|
async request(req) {
|
|
97
100
|
return (await this.requestWithMeta(req)).body;
|
|
98
101
|
}
|
|
99
102
|
/** Like `request`, with the status, request id, rate limit and replay flag. */
|
|
100
103
|
async requestWithMeta(req) {
|
|
104
|
+
(0, env_js_1.assertSafeRequestPath)(req.path);
|
|
101
105
|
const write = req.method === 'POST' || req.method === 'PUT' || req.method === 'PATCH';
|
|
102
106
|
return this.http.send({
|
|
103
107
|
method: req.method,
|
package/dist/cjs/core/env.d.ts
CHANGED
|
@@ -10,3 +10,18 @@ export declare function inspectApiKey(apiKey: string): KeyInfo;
|
|
|
10
10
|
export declare function normaliseBaseUrl(raw: string): string;
|
|
11
11
|
export declare function detectEnvironment(baseUrl: string, key: KeyInfo): Environment;
|
|
12
12
|
export declare function readEnv(name: string): string | undefined;
|
|
13
|
+
/** For tests: forget which hosts were already warned about. */
|
|
14
|
+
export declare function resetBaseUrlWarnings(): void;
|
|
15
|
+
/** True for the Hub's own domain, `hbcompliance.co.uk` and its sub domains, and for local hosts. */
|
|
16
|
+
export declare function isKnownHubHost(hostname: string): boolean;
|
|
17
|
+
/**
|
|
18
|
+
* The API key and the tokens are sent to the base URL, so a host that is not the Hub (or localhost) is worth a warning:
|
|
19
|
+
* a wrong `HB_BASE_URL` would hand the key to that host. The client keeps working. Warns once per host and process.
|
|
20
|
+
* Returns true when it warned.
|
|
21
|
+
*/
|
|
22
|
+
export declare function warnIfUnexpectedHost(baseUrl: string, warn: (message: string) => void): boolean;
|
|
23
|
+
/**
|
|
24
|
+
* Checks the path given to `request()`: it must start with a single `/`, with no `..` segment (also when encoded), no
|
|
25
|
+
* `@`, no backslash, no scheme and no whitespace or control characters, so it can never change the host the key is sent to.
|
|
26
|
+
*/
|
|
27
|
+
export declare function assertSafeRequestPath(path: unknown): asserts path is string;
|
package/dist/cjs/core/env.js
CHANGED
|
@@ -5,6 +5,10 @@ exports.inspectApiKey = inspectApiKey;
|
|
|
5
5
|
exports.normaliseBaseUrl = normaliseBaseUrl;
|
|
6
6
|
exports.detectEnvironment = detectEnvironment;
|
|
7
7
|
exports.readEnv = readEnv;
|
|
8
|
+
exports.resetBaseUrlWarnings = resetBaseUrlWarnings;
|
|
9
|
+
exports.isKnownHubHost = isKnownHubHost;
|
|
10
|
+
exports.warnIfUnexpectedHost = warnIfUnexpectedHost;
|
|
11
|
+
exports.assertSafeRequestPath = assertSafeRequestPath;
|
|
8
12
|
const errors_js_1 = require("./errors.js");
|
|
9
13
|
exports.DEFAULT_BASE_URL = 'https://hub.hbcompliance.co.uk';
|
|
10
14
|
/** Sandbox keys start with `hbk_test_`; live keys (and older keys) with `hbk_`. */
|
|
@@ -44,3 +48,67 @@ function readEnv(name) {
|
|
|
44
48
|
const v = proc?.env?.[name];
|
|
45
49
|
return v && v.trim() !== '' ? v.trim() : undefined;
|
|
46
50
|
}
|
|
51
|
+
const warnedHosts = new Set();
|
|
52
|
+
/** For tests: forget which hosts were already warned about. */
|
|
53
|
+
function resetBaseUrlWarnings() {
|
|
54
|
+
warnedHosts.clear();
|
|
55
|
+
}
|
|
56
|
+
/** True for the Hub's own domain, `hbcompliance.co.uk` and its sub domains, and for local hosts. */
|
|
57
|
+
function isKnownHubHost(hostname) {
|
|
58
|
+
const h = hostname.toLowerCase();
|
|
59
|
+
return h === 'hbcompliance.co.uk' || h.endsWith('.hbcompliance.co.uk') || h === 'localhost' || h === '127.0.0.1' || h === '[::1]' || h.endsWith('.localhost');
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* The API key and the tokens are sent to the base URL, so a host that is not the Hub (or localhost) is worth a warning:
|
|
63
|
+
* a wrong `HB_BASE_URL` would hand the key to that host. The client keeps working. Warns once per host and process.
|
|
64
|
+
* Returns true when it warned.
|
|
65
|
+
*/
|
|
66
|
+
function warnIfUnexpectedHost(baseUrl, warn) {
|
|
67
|
+
const host = new URL(baseUrl).hostname;
|
|
68
|
+
if (isKnownHubHost(host) || warnedHosts.has(host))
|
|
69
|
+
return false;
|
|
70
|
+
warnedHosts.add(host);
|
|
71
|
+
warn(`Healthier Business SDK: the base URL host "${host}" is not a hbcompliance.co.uk address or localhost. Your API key and tokens are sent to that host. Check HB_BASE_URL / baseUrl unless this is intended (for example a proxy).`);
|
|
72
|
+
return true;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Checks the path given to `request()`: it must start with a single `/`, with no `..` segment (also when encoded), no
|
|
76
|
+
* `@`, no backslash, no scheme and no whitespace or control characters, so it can never change the host the key is sent to.
|
|
77
|
+
*/
|
|
78
|
+
function assertSafeRequestPath(path) {
|
|
79
|
+
const fail = (why) => {
|
|
80
|
+
throw new errors_js_1.ConfigError(`request({ path }) must be a path on the Hub such as "/api/v2/hub/candidates": ${why}.`);
|
|
81
|
+
};
|
|
82
|
+
if (typeof path !== 'string' || path === '')
|
|
83
|
+
return fail('it is empty');
|
|
84
|
+
if (!path.startsWith('/'))
|
|
85
|
+
return fail('it must start with "/"');
|
|
86
|
+
if (path.startsWith('//'))
|
|
87
|
+
return fail('it must not start with "//"');
|
|
88
|
+
// eslint-disable-next-line no-control-regex
|
|
89
|
+
if (/[\u0000-\u0020\u007f]/.test(path))
|
|
90
|
+
return fail('it contains whitespace or control characters');
|
|
91
|
+
if (path.includes('@'))
|
|
92
|
+
return fail('it must not contain "@"');
|
|
93
|
+
if (path.includes('\\'))
|
|
94
|
+
return fail('it must not contain a backslash');
|
|
95
|
+
const pathOnly = path.split(/[?#]/, 1)[0] ?? '';
|
|
96
|
+
if (/^[A-Za-z][A-Za-z0-9+.-]*:/.test(pathOnly) || pathOnly.includes('://'))
|
|
97
|
+
return fail('it must not contain a scheme');
|
|
98
|
+
let decoded = pathOnly;
|
|
99
|
+
for (let i = 0; i < 3; i++) {
|
|
100
|
+
try {
|
|
101
|
+
const next = decodeURIComponent(decoded);
|
|
102
|
+
if (next === decoded)
|
|
103
|
+
break;
|
|
104
|
+
decoded = next;
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
return fail('it is not correctly encoded');
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
if (decoded.includes('@') || decoded.includes('\\'))
|
|
111
|
+
return fail('it must not contain "@" or a backslash, also when encoded');
|
|
112
|
+
if (decoded.split('/').some((segment) => segment === '..'))
|
|
113
|
+
return fail('it must not contain ".." segments');
|
|
114
|
+
}
|
|
@@ -34,7 +34,11 @@ export interface EmbedHandlerOptions {
|
|
|
34
34
|
/**
|
|
35
35
|
* The websites that may show the frame, for example ["https://portal.example.com"]. The session is tied to the
|
|
36
36
|
* `Origin` the browser sent, which must be in this list. With one entry and no Origin header, that entry is used.
|
|
37
|
-
*
|
|
37
|
+
*
|
|
38
|
+
* SET THIS IN PRODUCTION. Without this option the request's own `Origin` header is trusted, which means any website
|
|
39
|
+
* whose visitor is signed in to your system can ask for a session and show the frame; the only protection left is your
|
|
40
|
+
* `authorize` callback, which must then check that the signed-in person is entitled to what they ask for. The default
|
|
41
|
+
* is kept so that existing integrations keep working.
|
|
38
42
|
*/
|
|
39
43
|
allowedOrigins?: string[];
|
|
40
44
|
/** Remember who each session was made for, so a refresh by somebody else is refused. Default: memory. */
|
|
@@ -19,7 +19,7 @@ export interface EmbedSession {
|
|
|
19
19
|
/** The one website origin allowed to show this frame. */
|
|
20
20
|
allowedOrigin: string;
|
|
21
21
|
}
|
|
22
|
-
export type EmbedEventName = 'ready' | 'progress' | 'completed' | 'passed' | 'failed' | 'submitted' | 'terms-accepted' | 'error' | 'token-expiring';
|
|
22
|
+
export type EmbedEventName = 'ready' | 'progress' | 'completed' | 'passed' | 'failed' | 'submitted' | 'test-requested' | 'terms-accepted' | 'error' | 'token-expiring';
|
|
23
23
|
/**
|
|
24
24
|
* The codes the Hub answers with (HTTP 409) when it will not create a session because the candidate's training access is not in
|
|
25
25
|
* place. Each carries `details` (see `EmbedAccessDetails`).
|
|
@@ -77,6 +77,11 @@ export interface EmbedEventMap {
|
|
|
77
77
|
score: number;
|
|
78
78
|
passMark: number;
|
|
79
79
|
};
|
|
80
|
+
/** Course only: the learner pressed a Take test button in a lesson. `courseId` is the Online Training course id you created the session with; open that course's test (`createTestSession` with the same `courseId`). Not final: the course session stays open. */
|
|
81
|
+
'test-requested': {
|
|
82
|
+
courseId: number;
|
|
83
|
+
testId: number;
|
|
84
|
+
};
|
|
80
85
|
/** The OH form was submitted: `requestId` is the numeric Occupational Health request id. Final. */
|
|
81
86
|
submitted: {
|
|
82
87
|
requestId: number;
|
|
@@ -2956,7 +2956,7 @@ export type TvVerification = {
|
|
|
2956
2956
|
notify_email: string | null;
|
|
2957
2957
|
/** The Hub candidate this verification is linked to: the `candidate_ref` you sent, else, when a candidate of your own account was matched, theirs. Null otherwise. A candidate of another account is never shown. */
|
|
2958
2958
|
candidate_ref: string | null;
|
|
2959
|
-
/** The outcome, once the status is final (`verified`, `not_found`, `rejected` or `failed`); null while it is `pending` or `processing`. `matched` is true only for `verified`. `provider` names the agency
|
|
2959
|
+
/** The outcome, once the status is final (`verified`, `not_found`, `rejected` or `failed`); null while it is `pending` or `processing`. `matched` is true only for `verified`. `provider` names the agency named on the… */
|
|
2960
2960
|
result: {
|
|
2961
2961
|
/** True when the certificate was verified (`status` `verified`); false for `not_found`, `rejected` and `failed`. */
|
|
2962
2962
|
matched: boolean;
|
package/dist/cjs/index.d.ts
CHANGED
|
@@ -6,7 +6,7 @@ export type { Logger } from './core/logger.js';
|
|
|
6
6
|
export type { RequestOptions } from './core/manifest.js';
|
|
7
7
|
export { PagePromise, type PageBody } from './core/pagination.js';
|
|
8
8
|
export { MemoryTokenStore, type StoredTokens, type TokenStore } from './core/tokens.js';
|
|
9
|
-
export { WEBHOOK_EVENT_TYPES, constructEvent, signWebhook, verifyWebhook, type ConstructEventOptions, type HubWebhookEvent, type WebhookEventType, type WebhookEvents, type WebhookHeaders } from './webhooks.js';
|
|
9
|
+
export { WEBHOOK_EVENT_TYPES, constructEvent, createEventDeduper, type EventDeduper, type EventDeduperOptions, signWebhook, verifyWebhook, type ConstructEventOptions, type HubWebhookEvent, type WebhookEventType, type WebhookEvents, type WebhookHeaders } from './webhooks.js';
|
|
10
10
|
export type * as Types from './generated/types.js';
|
|
11
11
|
export type * from './generated/resources.js';
|
|
12
12
|
export { VERSION } from './version.js';
|
package/dist/cjs/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.accessStartResult = exports.embedErrorHint = exports.EMBED_ACCESS_CODES = exports.VERSION = exports.verifyWebhook = exports.signWebhook = exports.constructEvent = exports.WEBHOOK_EVENT_TYPES = exports.MemoryTokenStore = exports.PagePromise = exports.HubFile = exports.NEXT_HINTS = exports.CODE_HINTS = exports.WebhookSignatureError = exports.WebhookEventsNotApprovedError = exports.ValidationError = exports.ServerError = exports.RateLimitError = exports.PermissionError = exports.NotFoundError = exports.NetworkError = exports.isWebhookEventsNotApprovedError = exports.isEmbedAccessError = exports.isApiAccessError = exports.InsufficientCreditsError = exports.HubError = exports.GoneError = exports.EmbedError = exports.EmbedAccessError = exports.ConflictError = exports.ConfigError = exports.AuthThrottledError = exports.AuthenticationError = exports.ApiError = exports.ApiAccessError = exports.API_ACCESS_CODES = exports.AbortedError = exports.HealthierBusiness = void 0;
|
|
3
|
+
exports.accessStartResult = exports.embedErrorHint = exports.EMBED_ACCESS_CODES = exports.VERSION = exports.verifyWebhook = exports.signWebhook = exports.createEventDeduper = exports.constructEvent = exports.WEBHOOK_EVENT_TYPES = exports.MemoryTokenStore = exports.PagePromise = exports.HubFile = exports.NEXT_HINTS = exports.CODE_HINTS = exports.WebhookSignatureError = exports.WebhookEventsNotApprovedError = exports.ValidationError = exports.ServerError = exports.RateLimitError = exports.PermissionError = exports.NotFoundError = exports.NetworkError = exports.isWebhookEventsNotApprovedError = exports.isEmbedAccessError = exports.isApiAccessError = exports.InsufficientCreditsError = exports.HubError = exports.GoneError = exports.EmbedError = exports.EmbedAccessError = exports.ConflictError = exports.ConfigError = exports.AuthThrottledError = exports.AuthenticationError = exports.ApiError = exports.ApiAccessError = exports.API_ACCESS_CODES = exports.AbortedError = exports.HealthierBusiness = void 0;
|
|
4
4
|
var client_js_1 = require("./client.js");
|
|
5
5
|
Object.defineProperty(exports, "HealthierBusiness", { enumerable: true, get: function () { return client_js_1.HealthierBusiness; } });
|
|
6
6
|
var errors_js_1 = require("./core/errors.js");
|
|
@@ -39,6 +39,7 @@ Object.defineProperty(exports, "MemoryTokenStore", { enumerable: true, get: func
|
|
|
39
39
|
var webhooks_js_1 = require("./webhooks.js");
|
|
40
40
|
Object.defineProperty(exports, "WEBHOOK_EVENT_TYPES", { enumerable: true, get: function () { return webhooks_js_1.WEBHOOK_EVENT_TYPES; } });
|
|
41
41
|
Object.defineProperty(exports, "constructEvent", { enumerable: true, get: function () { return webhooks_js_1.constructEvent; } });
|
|
42
|
+
Object.defineProperty(exports, "createEventDeduper", { enumerable: true, get: function () { return webhooks_js_1.createEventDeduper; } });
|
|
42
43
|
Object.defineProperty(exports, "signWebhook", { enumerable: true, get: function () { return webhooks_js_1.signWebhook; } });
|
|
43
44
|
Object.defineProperty(exports, "verifyWebhook", { enumerable: true, get: function () { return webhooks_js_1.verifyWebhook; } });
|
|
44
45
|
var version_js_1 = require("./version.js");
|
package/dist/cjs/version.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const VERSION = "0.
|
|
1
|
+
export declare const VERSION = "0.4.1";
|
package/dist/cjs/version.js
CHANGED
package/dist/cjs/webhooks.d.ts
CHANGED
|
@@ -7,7 +7,11 @@ import type { HubWebhookEvent } from './generated/events.js';
|
|
|
7
7
|
*/
|
|
8
8
|
export { WEBHOOK_EVENT_TYPES } from './generated/events.js';
|
|
9
9
|
export type { HubWebhookEvent, WebhookEventType, WebhookEvents } from './generated/events.js';
|
|
10
|
-
/**
|
|
10
|
+
/**
|
|
11
|
+
* What the Hub sends with every delivery: `X-Hub-Signature` and `X-Hub-Timestamp` (and `X-Hub-Event-Id`). The signature
|
|
12
|
+
* check stops forged and stale deliveries only: the Hub delivers at least once and a retry is signed afresh, so also handle
|
|
13
|
+
* each `event_id` once (see `createEventDeduper`, or keep the ids in your own store).
|
|
14
|
+
*/
|
|
11
15
|
export type WebhookHeaders = {
|
|
12
16
|
signature: string;
|
|
13
17
|
timestamp: string | number;
|
|
@@ -40,3 +44,34 @@ export interface WebhookHelpersApi {
|
|
|
40
44
|
export declare class WebhookHelpers {
|
|
41
45
|
api(): WebhookHelpersApi;
|
|
42
46
|
}
|
|
47
|
+
export interface EventDeduperOptions {
|
|
48
|
+
/**
|
|
49
|
+
* How long an event id is remembered, in seconds. Default 5400 (90 minutes): longer than the signature tolerance
|
|
50
|
+
* (300 seconds) and than the Hub's retries (up to about 80 minutes). A delivery carries a fresh timestamp on every
|
|
51
|
+
* attempt, so the signature check alone cannot tell a retry or a replay of a captured request from a new event.
|
|
52
|
+
*/
|
|
53
|
+
ttlSeconds?: number;
|
|
54
|
+
/** The most ids kept; the oldest go first. Default 10 000. */
|
|
55
|
+
maxEntries?: number;
|
|
56
|
+
/** For tests: the current time in milliseconds. */
|
|
57
|
+
now?: () => number;
|
|
58
|
+
}
|
|
59
|
+
export interface EventDeduper {
|
|
60
|
+
/** True when this event id was seen within the window (a duplicate: skip it). Otherwise remembers it and answers false. */
|
|
61
|
+
isDuplicate(eventId: string): boolean;
|
|
62
|
+
/** The id from `X-Hub-Event-Id`, or undefined when the header is missing. */
|
|
63
|
+
eventIdOf(headers: WebhookHeaders): string | undefined;
|
|
64
|
+
/** How many ids are remembered now. */
|
|
65
|
+
readonly size: number;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* An in-memory memory of the event ids already handled, keyed on the `X-Hub-Event-Id` header (the `event_id` of the body).
|
|
69
|
+
* The Hub delivers at least once, and a captured delivery can be sent again inside the 300 second tolerance, so handle each
|
|
70
|
+
* id once. In memory means per process: on serverless or with several instances keep the ids in a shared store (Redis,
|
|
71
|
+
* a unique database column) instead; this helper is for a single process and for tests.
|
|
72
|
+
*
|
|
73
|
+
* const deduper = createEventDeduper();
|
|
74
|
+
* const event = hb.webhooks.constructEvent(rawBody, req.headers, secret);
|
|
75
|
+
* if (deduper.isDuplicate(event.event_id)) return res.sendStatus(200);
|
|
76
|
+
*/
|
|
77
|
+
export declare function createEventDeduper(options?: EventDeduperOptions): EventDeduper;
|
package/dist/cjs/webhooks.js
CHANGED
|
@@ -4,6 +4,7 @@ exports.WebhookHelpers = exports.WEBHOOK_EVENT_TYPES = void 0;
|
|
|
4
4
|
exports.signWebhook = signWebhook;
|
|
5
5
|
exports.constructEvent = constructEvent;
|
|
6
6
|
exports.verifyWebhook = verifyWebhook;
|
|
7
|
+
exports.createEventDeduper = createEventDeduper;
|
|
7
8
|
const errors_js_1 = require("./core/errors.js");
|
|
8
9
|
const sha256_js_1 = require("./core/sha256.js");
|
|
9
10
|
/**
|
|
@@ -106,3 +107,50 @@ class WebhookHelpers {
|
|
|
106
107
|
}
|
|
107
108
|
}
|
|
108
109
|
exports.WebhookHelpers = WebhookHelpers;
|
|
110
|
+
/**
|
|
111
|
+
* An in-memory memory of the event ids already handled, keyed on the `X-Hub-Event-Id` header (the `event_id` of the body).
|
|
112
|
+
* The Hub delivers at least once, and a captured delivery can be sent again inside the 300 second tolerance, so handle each
|
|
113
|
+
* id once. In memory means per process: on serverless or with several instances keep the ids in a shared store (Redis,
|
|
114
|
+
* a unique database column) instead; this helper is for a single process and for tests.
|
|
115
|
+
*
|
|
116
|
+
* const deduper = createEventDeduper();
|
|
117
|
+
* const event = hb.webhooks.constructEvent(rawBody, req.headers, secret);
|
|
118
|
+
* if (deduper.isDuplicate(event.event_id)) return res.sendStatus(200);
|
|
119
|
+
*/
|
|
120
|
+
function createEventDeduper(options = {}) {
|
|
121
|
+
const ttl = (options.ttlSeconds ?? 5400) * 1000;
|
|
122
|
+
const max = options.maxEntries ?? 10_000;
|
|
123
|
+
const now = options.now ?? Date.now;
|
|
124
|
+
const seen = new Map();
|
|
125
|
+
const prune = (at) => {
|
|
126
|
+
for (const [id, until] of seen) {
|
|
127
|
+
if (until > at)
|
|
128
|
+
break;
|
|
129
|
+
seen.delete(id);
|
|
130
|
+
}
|
|
131
|
+
while (seen.size > max) {
|
|
132
|
+
const oldest = seen.keys().next().value;
|
|
133
|
+
if (oldest === undefined)
|
|
134
|
+
break;
|
|
135
|
+
seen.delete(oldest);
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
return {
|
|
139
|
+
isDuplicate(eventId) {
|
|
140
|
+
if (typeof eventId !== 'string' || eventId === '')
|
|
141
|
+
return false;
|
|
142
|
+
const at = now();
|
|
143
|
+
prune(at);
|
|
144
|
+
if ((seen.get(eventId) ?? 0) > at)
|
|
145
|
+
return true;
|
|
146
|
+
seen.delete(eventId);
|
|
147
|
+
seen.set(eventId, at + ttl);
|
|
148
|
+
prune(at);
|
|
149
|
+
return false;
|
|
150
|
+
},
|
|
151
|
+
eventIdOf: (headers) => headerValue(headers, 'x-hub-event-id'),
|
|
152
|
+
get size() {
|
|
153
|
+
return seen.size;
|
|
154
|
+
},
|
|
155
|
+
};
|
|
156
|
+
}
|
|
@@ -4,6 +4,6 @@ export { cleanAccessDetails, EMBED_ACCESS_CODES, embedErrorHint, isEmbedSession,
|
|
|
4
4
|
/** `HealthierBusiness.mount(element, options)` for the browser. It holds no API key and cannot make API calls. */
|
|
5
5
|
export declare const HealthierBusiness: {
|
|
6
6
|
readonly mount: typeof mount;
|
|
7
|
-
readonly version: "0.
|
|
7
|
+
readonly version: "0.4.1";
|
|
8
8
|
};
|
|
9
|
-
export declare const version = "0.
|
|
9
|
+
export declare const version = "0.4.1";
|
|
@@ -36,6 +36,8 @@ export interface MountOptions {
|
|
|
36
36
|
onPassed?: (data: EmbedEventMap['passed']) => void;
|
|
37
37
|
onFailed?: (data: EmbedEventMap['failed']) => void;
|
|
38
38
|
onSubmitted?: (data: EmbedEventMap['submitted']) => void;
|
|
39
|
+
/** The learner pressed a Take test button in a lesson: open that course's test (`createTestSession` with the same `courseId`). */
|
|
40
|
+
onTestRequested?: (data: EmbedEventMap['test-requested']) => void;
|
|
39
41
|
/** The candidate accepted the Hub terms in the frame. */
|
|
40
42
|
onTermsAccepted?: (data: EmbedEventMap['terms-accepted']) => void;
|
|
41
43
|
onError?: (error: EmbedEventMap['error']) => void;
|
package/dist/esm/client.d.ts
CHANGED
|
@@ -11,7 +11,8 @@ export interface HealthierBusinessOptions {
|
|
|
11
11
|
apiKey?: string;
|
|
12
12
|
/**
|
|
13
13
|
* The Hub address. Defaults to `HB_BASE_URL`, then to production. Sandbox keys (`hbk_test_`) need the sandbox
|
|
14
|
-
* address shown on the developer portal.
|
|
14
|
+
* address shown on the developer portal. Your key and tokens are sent to this host: the SDK warns once (through
|
|
15
|
+
* `logger.warn`, else `console.warn`) when it is not a `hbcompliance.co.uk` address or localhost, and still works.
|
|
15
16
|
*/
|
|
16
17
|
baseUrl?: string;
|
|
17
18
|
/** Per-attempt timeout in milliseconds. Default 30 000. */
|
|
@@ -62,6 +63,8 @@ export declare class HealthierBusiness {
|
|
|
62
63
|
/**
|
|
63
64
|
* A call to any path of the API, for something the typed methods do not cover yet. Returns the parsed body.
|
|
64
65
|
* Writes get an Idempotency-Key automatically unless you pass `options.idempotencyKey`.
|
|
66
|
+
* `path` must start with `/` and may not contain `..` segments, `@`, a backslash or a scheme (a `ConfigError` is
|
|
67
|
+
* thrown before anything is sent), so a path can never send your key to another host.
|
|
65
68
|
*/
|
|
66
69
|
request<T = unknown>(req: {
|
|
67
70
|
method: HubRequest['method'];
|
package/dist/esm/client.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ConfigError, HubError } from './core/errors.js';
|
|
2
|
-
import { DEFAULT_BASE_URL, detectEnvironment, inspectApiKey, normaliseBaseUrl, readEnv } from './core/env.js';
|
|
2
|
+
import { DEFAULT_BASE_URL, assertSafeRequestPath, detectEnvironment, inspectApiKey, normaliseBaseUrl, readEnv, warnIfUnexpectedHost } from './core/env.js';
|
|
3
3
|
import { containsFile } from './core/files.js';
|
|
4
4
|
import { HttpClient } from './core/http.js';
|
|
5
5
|
import { uuid } from './core/ids.js';
|
|
@@ -46,6 +46,7 @@ export class HealthierBusiness {
|
|
|
46
46
|
this.environment = detectEnvironment(this.baseUrl, key);
|
|
47
47
|
this.keyPrefix = key.display;
|
|
48
48
|
const logger = options.logger ?? silentLogger;
|
|
49
|
+
warnIfUnexpectedHost(this.baseUrl, (message) => (options.logger ? options.logger.warn(message) : console.warn(message)));
|
|
49
50
|
const userAgent = `healthier-business-hub-sdk-js/${VERSION}`;
|
|
50
51
|
this.tokens = new TokenManager({
|
|
51
52
|
apiKey,
|
|
@@ -89,12 +90,15 @@ export class HealthierBusiness {
|
|
|
89
90
|
/**
|
|
90
91
|
* A call to any path of the API, for something the typed methods do not cover yet. Returns the parsed body.
|
|
91
92
|
* Writes get an Idempotency-Key automatically unless you pass `options.idempotencyKey`.
|
|
93
|
+
* `path` must start with `/` and may not contain `..` segments, `@`, a backslash or a scheme (a `ConfigError` is
|
|
94
|
+
* thrown before anything is sent), so a path can never send your key to another host.
|
|
92
95
|
*/
|
|
93
96
|
async request(req) {
|
|
94
97
|
return (await this.requestWithMeta(req)).body;
|
|
95
98
|
}
|
|
96
99
|
/** Like `request`, with the status, request id, rate limit and replay flag. */
|
|
97
100
|
async requestWithMeta(req) {
|
|
101
|
+
assertSafeRequestPath(req.path);
|
|
98
102
|
const write = req.method === 'POST' || req.method === 'PUT' || req.method === 'PATCH';
|
|
99
103
|
return this.http.send({
|
|
100
104
|
method: req.method,
|
package/dist/esm/core/env.d.ts
CHANGED
|
@@ -10,3 +10,18 @@ export declare function inspectApiKey(apiKey: string): KeyInfo;
|
|
|
10
10
|
export declare function normaliseBaseUrl(raw: string): string;
|
|
11
11
|
export declare function detectEnvironment(baseUrl: string, key: KeyInfo): Environment;
|
|
12
12
|
export declare function readEnv(name: string): string | undefined;
|
|
13
|
+
/** For tests: forget which hosts were already warned about. */
|
|
14
|
+
export declare function resetBaseUrlWarnings(): void;
|
|
15
|
+
/** True for the Hub's own domain, `hbcompliance.co.uk` and its sub domains, and for local hosts. */
|
|
16
|
+
export declare function isKnownHubHost(hostname: string): boolean;
|
|
17
|
+
/**
|
|
18
|
+
* The API key and the tokens are sent to the base URL, so a host that is not the Hub (or localhost) is worth a warning:
|
|
19
|
+
* a wrong `HB_BASE_URL` would hand the key to that host. The client keeps working. Warns once per host and process.
|
|
20
|
+
* Returns true when it warned.
|
|
21
|
+
*/
|
|
22
|
+
export declare function warnIfUnexpectedHost(baseUrl: string, warn: (message: string) => void): boolean;
|
|
23
|
+
/**
|
|
24
|
+
* Checks the path given to `request()`: it must start with a single `/`, with no `..` segment (also when encoded), no
|
|
25
|
+
* `@`, no backslash, no scheme and no whitespace or control characters, so it can never change the host the key is sent to.
|
|
26
|
+
*/
|
|
27
|
+
export declare function assertSafeRequestPath(path: unknown): asserts path is string;
|
package/dist/esm/core/env.js
CHANGED
|
@@ -37,3 +37,67 @@ export function readEnv(name) {
|
|
|
37
37
|
const v = proc?.env?.[name];
|
|
38
38
|
return v && v.trim() !== '' ? v.trim() : undefined;
|
|
39
39
|
}
|
|
40
|
+
const warnedHosts = new Set();
|
|
41
|
+
/** For tests: forget which hosts were already warned about. */
|
|
42
|
+
export function resetBaseUrlWarnings() {
|
|
43
|
+
warnedHosts.clear();
|
|
44
|
+
}
|
|
45
|
+
/** True for the Hub's own domain, `hbcompliance.co.uk` and its sub domains, and for local hosts. */
|
|
46
|
+
export function isKnownHubHost(hostname) {
|
|
47
|
+
const h = hostname.toLowerCase();
|
|
48
|
+
return h === 'hbcompliance.co.uk' || h.endsWith('.hbcompliance.co.uk') || h === 'localhost' || h === '127.0.0.1' || h === '[::1]' || h.endsWith('.localhost');
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* The API key and the tokens are sent to the base URL, so a host that is not the Hub (or localhost) is worth a warning:
|
|
52
|
+
* a wrong `HB_BASE_URL` would hand the key to that host. The client keeps working. Warns once per host and process.
|
|
53
|
+
* Returns true when it warned.
|
|
54
|
+
*/
|
|
55
|
+
export function warnIfUnexpectedHost(baseUrl, warn) {
|
|
56
|
+
const host = new URL(baseUrl).hostname;
|
|
57
|
+
if (isKnownHubHost(host) || warnedHosts.has(host))
|
|
58
|
+
return false;
|
|
59
|
+
warnedHosts.add(host);
|
|
60
|
+
warn(`Healthier Business SDK: the base URL host "${host}" is not a hbcompliance.co.uk address or localhost. Your API key and tokens are sent to that host. Check HB_BASE_URL / baseUrl unless this is intended (for example a proxy).`);
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Checks the path given to `request()`: it must start with a single `/`, with no `..` segment (also when encoded), no
|
|
65
|
+
* `@`, no backslash, no scheme and no whitespace or control characters, so it can never change the host the key is sent to.
|
|
66
|
+
*/
|
|
67
|
+
export function assertSafeRequestPath(path) {
|
|
68
|
+
const fail = (why) => {
|
|
69
|
+
throw new ConfigError(`request({ path }) must be a path on the Hub such as "/api/v2/hub/candidates": ${why}.`);
|
|
70
|
+
};
|
|
71
|
+
if (typeof path !== 'string' || path === '')
|
|
72
|
+
return fail('it is empty');
|
|
73
|
+
if (!path.startsWith('/'))
|
|
74
|
+
return fail('it must start with "/"');
|
|
75
|
+
if (path.startsWith('//'))
|
|
76
|
+
return fail('it must not start with "//"');
|
|
77
|
+
// eslint-disable-next-line no-control-regex
|
|
78
|
+
if (/[\u0000-\u0020\u007f]/.test(path))
|
|
79
|
+
return fail('it contains whitespace or control characters');
|
|
80
|
+
if (path.includes('@'))
|
|
81
|
+
return fail('it must not contain "@"');
|
|
82
|
+
if (path.includes('\\'))
|
|
83
|
+
return fail('it must not contain a backslash');
|
|
84
|
+
const pathOnly = path.split(/[?#]/, 1)[0] ?? '';
|
|
85
|
+
if (/^[A-Za-z][A-Za-z0-9+.-]*:/.test(pathOnly) || pathOnly.includes('://'))
|
|
86
|
+
return fail('it must not contain a scheme');
|
|
87
|
+
let decoded = pathOnly;
|
|
88
|
+
for (let i = 0; i < 3; i++) {
|
|
89
|
+
try {
|
|
90
|
+
const next = decodeURIComponent(decoded);
|
|
91
|
+
if (next === decoded)
|
|
92
|
+
break;
|
|
93
|
+
decoded = next;
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
return fail('it is not correctly encoded');
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
if (decoded.includes('@') || decoded.includes('\\'))
|
|
100
|
+
return fail('it must not contain "@" or a backslash, also when encoded');
|
|
101
|
+
if (decoded.split('/').some((segment) => segment === '..'))
|
|
102
|
+
return fail('it must not contain ".." segments');
|
|
103
|
+
}
|
|
@@ -34,7 +34,11 @@ export interface EmbedHandlerOptions {
|
|
|
34
34
|
/**
|
|
35
35
|
* The websites that may show the frame, for example ["https://portal.example.com"]. The session is tied to the
|
|
36
36
|
* `Origin` the browser sent, which must be in this list. With one entry and no Origin header, that entry is used.
|
|
37
|
-
*
|
|
37
|
+
*
|
|
38
|
+
* SET THIS IN PRODUCTION. Without this option the request's own `Origin` header is trusted, which means any website
|
|
39
|
+
* whose visitor is signed in to your system can ask for a session and show the frame; the only protection left is your
|
|
40
|
+
* `authorize` callback, which must then check that the signed-in person is entitled to what they ask for. The default
|
|
41
|
+
* is kept so that existing integrations keep working.
|
|
38
42
|
*/
|
|
39
43
|
allowedOrigins?: string[];
|
|
40
44
|
/** Remember who each session was made for, so a refresh by somebody else is refused. Default: memory. */
|
|
@@ -19,7 +19,7 @@ export interface EmbedSession {
|
|
|
19
19
|
/** The one website origin allowed to show this frame. */
|
|
20
20
|
allowedOrigin: string;
|
|
21
21
|
}
|
|
22
|
-
export type EmbedEventName = 'ready' | 'progress' | 'completed' | 'passed' | 'failed' | 'submitted' | 'terms-accepted' | 'error' | 'token-expiring';
|
|
22
|
+
export type EmbedEventName = 'ready' | 'progress' | 'completed' | 'passed' | 'failed' | 'submitted' | 'test-requested' | 'terms-accepted' | 'error' | 'token-expiring';
|
|
23
23
|
/**
|
|
24
24
|
* The codes the Hub answers with (HTTP 409) when it will not create a session because the candidate's training access is not in
|
|
25
25
|
* place. Each carries `details` (see `EmbedAccessDetails`).
|
|
@@ -77,6 +77,11 @@ export interface EmbedEventMap {
|
|
|
77
77
|
score: number;
|
|
78
78
|
passMark: number;
|
|
79
79
|
};
|
|
80
|
+
/** Course only: the learner pressed a Take test button in a lesson. `courseId` is the Online Training course id you created the session with; open that course's test (`createTestSession` with the same `courseId`). Not final: the course session stays open. */
|
|
81
|
+
'test-requested': {
|
|
82
|
+
courseId: number;
|
|
83
|
+
testId: number;
|
|
84
|
+
};
|
|
80
85
|
/** The OH form was submitted: `requestId` is the numeric Occupational Health request id. Final. */
|
|
81
86
|
submitted: {
|
|
82
87
|
requestId: number;
|
|
@@ -2956,7 +2956,7 @@ export type TvVerification = {
|
|
|
2956
2956
|
notify_email: string | null;
|
|
2957
2957
|
/** The Hub candidate this verification is linked to: the `candidate_ref` you sent, else, when a candidate of your own account was matched, theirs. Null otherwise. A candidate of another account is never shown. */
|
|
2958
2958
|
candidate_ref: string | null;
|
|
2959
|
-
/** The outcome, once the status is final (`verified`, `not_found`, `rejected` or `failed`); null while it is `pending` or `processing`. `matched` is true only for `verified`. `provider` names the agency
|
|
2959
|
+
/** The outcome, once the status is final (`verified`, `not_found`, `rejected` or `failed`); null while it is `pending` or `processing`. `matched` is true only for `verified`. `provider` names the agency named on the… */
|
|
2960
2960
|
result: {
|
|
2961
2961
|
/** True when the certificate was verified (`status` `verified`); false for `not_found`, `rejected` and `failed`. */
|
|
2962
2962
|
matched: boolean;
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -6,7 +6,7 @@ export type { Logger } from './core/logger.js';
|
|
|
6
6
|
export type { RequestOptions } from './core/manifest.js';
|
|
7
7
|
export { PagePromise, type PageBody } from './core/pagination.js';
|
|
8
8
|
export { MemoryTokenStore, type StoredTokens, type TokenStore } from './core/tokens.js';
|
|
9
|
-
export { WEBHOOK_EVENT_TYPES, constructEvent, signWebhook, verifyWebhook, type ConstructEventOptions, type HubWebhookEvent, type WebhookEventType, type WebhookEvents, type WebhookHeaders } from './webhooks.js';
|
|
9
|
+
export { WEBHOOK_EVENT_TYPES, constructEvent, createEventDeduper, type EventDeduper, type EventDeduperOptions, signWebhook, verifyWebhook, type ConstructEventOptions, type HubWebhookEvent, type WebhookEventType, type WebhookEvents, type WebhookHeaders } from './webhooks.js';
|
|
10
10
|
export type * as Types from './generated/types.js';
|
|
11
11
|
export type * from './generated/resources.js';
|
|
12
12
|
export { VERSION } from './version.js';
|
package/dist/esm/index.js
CHANGED
|
@@ -3,7 +3,7 @@ export { AbortedError, API_ACCESS_CODES, ApiAccessError, ApiError, Authenticatio
|
|
|
3
3
|
export { HubFile } from './core/files.js';
|
|
4
4
|
export { PagePromise } from './core/pagination.js';
|
|
5
5
|
export { MemoryTokenStore } from './core/tokens.js';
|
|
6
|
-
export { WEBHOOK_EVENT_TYPES, constructEvent, signWebhook, verifyWebhook } from './webhooks.js';
|
|
6
|
+
export { WEBHOOK_EVENT_TYPES, constructEvent, createEventDeduper, signWebhook, verifyWebhook } from './webhooks.js';
|
|
7
7
|
export { VERSION } from './version.js';
|
|
8
8
|
export { EMBED_ACCESS_CODES, embedErrorHint } from './embed/protocol.js';
|
|
9
9
|
export { accessStartResult } from './access.js';
|
package/dist/esm/version.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const VERSION = "0.
|
|
1
|
+
export declare const VERSION = "0.4.1";
|
package/dist/esm/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const VERSION = '0.
|
|
1
|
+
export const VERSION = '0.4.1';
|
package/dist/esm/webhooks.d.ts
CHANGED
|
@@ -7,7 +7,11 @@ import type { HubWebhookEvent } from './generated/events.js';
|
|
|
7
7
|
*/
|
|
8
8
|
export { WEBHOOK_EVENT_TYPES } from './generated/events.js';
|
|
9
9
|
export type { HubWebhookEvent, WebhookEventType, WebhookEvents } from './generated/events.js';
|
|
10
|
-
/**
|
|
10
|
+
/**
|
|
11
|
+
* What the Hub sends with every delivery: `X-Hub-Signature` and `X-Hub-Timestamp` (and `X-Hub-Event-Id`). The signature
|
|
12
|
+
* check stops forged and stale deliveries only: the Hub delivers at least once and a retry is signed afresh, so also handle
|
|
13
|
+
* each `event_id` once (see `createEventDeduper`, or keep the ids in your own store).
|
|
14
|
+
*/
|
|
11
15
|
export type WebhookHeaders = {
|
|
12
16
|
signature: string;
|
|
13
17
|
timestamp: string | number;
|
|
@@ -40,3 +44,34 @@ export interface WebhookHelpersApi {
|
|
|
40
44
|
export declare class WebhookHelpers {
|
|
41
45
|
api(): WebhookHelpersApi;
|
|
42
46
|
}
|
|
47
|
+
export interface EventDeduperOptions {
|
|
48
|
+
/**
|
|
49
|
+
* How long an event id is remembered, in seconds. Default 5400 (90 minutes): longer than the signature tolerance
|
|
50
|
+
* (300 seconds) and than the Hub's retries (up to about 80 minutes). A delivery carries a fresh timestamp on every
|
|
51
|
+
* attempt, so the signature check alone cannot tell a retry or a replay of a captured request from a new event.
|
|
52
|
+
*/
|
|
53
|
+
ttlSeconds?: number;
|
|
54
|
+
/** The most ids kept; the oldest go first. Default 10 000. */
|
|
55
|
+
maxEntries?: number;
|
|
56
|
+
/** For tests: the current time in milliseconds. */
|
|
57
|
+
now?: () => number;
|
|
58
|
+
}
|
|
59
|
+
export interface EventDeduper {
|
|
60
|
+
/** True when this event id was seen within the window (a duplicate: skip it). Otherwise remembers it and answers false. */
|
|
61
|
+
isDuplicate(eventId: string): boolean;
|
|
62
|
+
/** The id from `X-Hub-Event-Id`, or undefined when the header is missing. */
|
|
63
|
+
eventIdOf(headers: WebhookHeaders): string | undefined;
|
|
64
|
+
/** How many ids are remembered now. */
|
|
65
|
+
readonly size: number;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* An in-memory memory of the event ids already handled, keyed on the `X-Hub-Event-Id` header (the `event_id` of the body).
|
|
69
|
+
* The Hub delivers at least once, and a captured delivery can be sent again inside the 300 second tolerance, so handle each
|
|
70
|
+
* id once. In memory means per process: on serverless or with several instances keep the ids in a shared store (Redis,
|
|
71
|
+
* a unique database column) instead; this helper is for a single process and for tests.
|
|
72
|
+
*
|
|
73
|
+
* const deduper = createEventDeduper();
|
|
74
|
+
* const event = hb.webhooks.constructEvent(rawBody, req.headers, secret);
|
|
75
|
+
* if (deduper.isDuplicate(event.event_id)) return res.sendStatus(200);
|
|
76
|
+
*/
|
|
77
|
+
export declare function createEventDeduper(options?: EventDeduperOptions): EventDeduper;
|
package/dist/esm/webhooks.js
CHANGED
|
@@ -98,3 +98,50 @@ export class WebhookHelpers {
|
|
|
98
98
|
};
|
|
99
99
|
}
|
|
100
100
|
}
|
|
101
|
+
/**
|
|
102
|
+
* An in-memory memory of the event ids already handled, keyed on the `X-Hub-Event-Id` header (the `event_id` of the body).
|
|
103
|
+
* The Hub delivers at least once, and a captured delivery can be sent again inside the 300 second tolerance, so handle each
|
|
104
|
+
* id once. In memory means per process: on serverless or with several instances keep the ids in a shared store (Redis,
|
|
105
|
+
* a unique database column) instead; this helper is for a single process and for tests.
|
|
106
|
+
*
|
|
107
|
+
* const deduper = createEventDeduper();
|
|
108
|
+
* const event = hb.webhooks.constructEvent(rawBody, req.headers, secret);
|
|
109
|
+
* if (deduper.isDuplicate(event.event_id)) return res.sendStatus(200);
|
|
110
|
+
*/
|
|
111
|
+
export function createEventDeduper(options = {}) {
|
|
112
|
+
const ttl = (options.ttlSeconds ?? 5400) * 1000;
|
|
113
|
+
const max = options.maxEntries ?? 10_000;
|
|
114
|
+
const now = options.now ?? Date.now;
|
|
115
|
+
const seen = new Map();
|
|
116
|
+
const prune = (at) => {
|
|
117
|
+
for (const [id, until] of seen) {
|
|
118
|
+
if (until > at)
|
|
119
|
+
break;
|
|
120
|
+
seen.delete(id);
|
|
121
|
+
}
|
|
122
|
+
while (seen.size > max) {
|
|
123
|
+
const oldest = seen.keys().next().value;
|
|
124
|
+
if (oldest === undefined)
|
|
125
|
+
break;
|
|
126
|
+
seen.delete(oldest);
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
return {
|
|
130
|
+
isDuplicate(eventId) {
|
|
131
|
+
if (typeof eventId !== 'string' || eventId === '')
|
|
132
|
+
return false;
|
|
133
|
+
const at = now();
|
|
134
|
+
prune(at);
|
|
135
|
+
if ((seen.get(eventId) ?? 0) > at)
|
|
136
|
+
return true;
|
|
137
|
+
seen.delete(eventId);
|
|
138
|
+
seen.set(eventId, at + ttl);
|
|
139
|
+
prune(at);
|
|
140
|
+
return false;
|
|
141
|
+
},
|
|
142
|
+
eventIdOf: (headers) => headerValue(headers, 'x-hub-event-id'),
|
|
143
|
+
get size() {
|
|
144
|
+
return seen.size;
|
|
145
|
+
},
|
|
146
|
+
};
|
|
147
|
+
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var HealthierBusiness=(function(y){"use strict";const I=[...["course_access_required","payment_pending","renewal_approval_required","access_expired"],"course_not_pending"],W=["not_started","payment_pending","awaiting_approval","expired"],$=["start_access","pay","await_approval","renew"];function M(o){const e=typeof o=="object"&&o!==null?o:{},h={};return typeof e.state=="string"&&W.includes(e.state)&&(h.state=e.state),(e.payer==="client"||e.payer==="candidate")&&(h.payer=e.payer),typeof e.next=="string"&&$.includes(e.next)&&(h.next=e.next),h}const X={token_used:"The launch token was already used. A token works once: create or refresh the session and mount again.",token_invalid:"The launch token is not valid for this session. Make sure getSession returns the session your server just created or refreshed.",token_expired:"The launch token expired (it lasts 5 minutes and is renewed on refresh). Create or refresh the session and mount again.",frame_invalid:"The frame was not opened by the SDK. Show it only with HealthierBusiness.mount(), not with your own iframe.",origin_not_allowed:"This website is not the one the session was created for, or it is not registered. Add it under Developer > Embed in Hub and pass the same origin when your server creates the session.",not_allowed:"The content can only be opened through the SDK from the website the session was created for.",session_expired:"The session timed out (60 minutes without a refresh, 12 hours at most). Create a new session.",session_finished:"The session is complete. Create a new session if the person needs it again.",not_found:"The session does not exist (any more). Create a new session.",network:"The frame could not reach the Hub. Check the connection and try again.",frame_timeout:"The frame did not start. Common causes: the session expired or finished, the website is not allowed to show it, or the session was created for another origin.",origin_mismatch:"The session was created for a different origin than this page. Pass this page's origin when your server creates the session.",session_failed:"Your server route did not return a session. Check its response in the network tab.",session_changed:"Refreshing returned a different session. Your route must call hb.embed.refresh(sessionId) for a refresh.",token_refresh_failed:"Renewing the launch token failed twice. Check that your refresh route works and that the person is still signed in.",init_failed:"The frame could not be started with the token.",terms_required:"The candidate has not accepted the terms. The frame shows them first; nothing else can be used until they accept (watch for the terms-accepted event).",access_expired:"The candidate's access has ended. Renew it (accessStart, or the renewal calls when renewals need approval), then create a new session.",course_access_required:"The candidate's access has not been started. Start it with hb.onlineTraining.candidates.accessStart() on your server, then create the session again.",payment_pending:"The candidate has a payment link that is not paid yet. Ask them to pay it, then create the session again.",renewal_approval_required:"A renewal waits for approval. Approve it (renewalApprove or in Hub), then create the session again.",course_not_pending:"The candidate has already completed this course. Only courses still to do can be opened."};function b(o){return X[o]}function Y(o){if(typeof o!="object"||o===null)return!1;const e=o;return e.hb!==1?!1:e.type==="ready"?typeof e.nonce=="string"&&e.nonce.length>0&&e.nonce.length<=200:e.type==="event"?typeof e.name=="string":e.type==="resize"?typeof e.height=="number"&&Number.isFinite(e.height):e.type==="scroll-top"}function K(o){if(typeof o!="object"||o===null)return!1;const e=o;return typeof e.sessionId=="string"&&(e.kind==="course"||e.kind==="test"||e.kind==="oh_form")&&typeof e.launchToken=="string"&&typeof e.frameUrl=="string"&&(typeof e.expiresAt=="string"||e.expiresAt===null)&&typeof e.sessionExpiresAt=="string"&&typeof e.allowedOrigin=="string"}const D="allow-scripts allow-same-origin allow-forms allow-downloads allow-popups allow-popups-to-escape-sandbox",z="fullscreen; picture-in-picture; encrypted-media",G={course:"Course",test:"Test",oh_form:"Occupational health form"},J=100,Q=3e4;function R(o){let e;try{e=new URL(o.frameUrl)}catch{throw new Error("The session has no valid frameUrl.")}const h=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname.endsWith(".localhost")||e.hostname.endsWith(".test");if(e.protocol!=="https:"&&!(e.protocol==="http:"&&h))throw new Error("The frame must be served over https.");return e.origin}function H(o){const{endpoint:e,kind:h,courseId:d,formShortcode:C,fetchInit:u}=o;if(!e||!h)throw new Error("mount needs either getSession, or endpoint and kind.");return async({reason:l,sessionId:a})=>{const g=await fetch(e,{credentials:"same-origin",...u,method:"POST",headers:{"content-type":"application/json",...u==null?void 0:u.headers},body:JSON.stringify(l==="refresh"?{action:"refresh",sessionId:a}:{action:"create",kind:h,courseId:d,formShortcode:C})}),s=await g.json().catch(()=>({}));if(!g.ok){const f=typeof s.message=="string"?s.message:`Your server answered HTTP ${g.status}.`,w=typeof s.error=="string"&&I.includes(s.error)?s.error:void 0;throw Object.assign(new Error(f),w?{code:w,details:M(s.details)}:{})}return s}}function Z(o,e){var q;const h=o.ownerDocument,d=h.defaultView,C=(q=e.getSession)!=null?q:H(e),u=new Map;let l=!1,a,g="",s,f,w,j=0,A=!1,N,x;const P=new Promise((n,t)=>{N=n,x=t});P.catch(()=>{});const _=(n,t)=>{var c,T,k,E,S,i,m,v,U,V;if(l)return;const r=t!=null?t:{};switch((c=e.onEvent)==null||c.call(e,{name:n,data:t}),n){case"ready":(T=e.onReady)==null||T.call(e);break;case"progress":(k=e.onProgress)==null||k.call(e,r);break;case"completed":(E=e.onCompleted)==null||E.call(e,r);break;case"passed":(S=e.onPassed)==null||S.call(e,r);break;case"failed":(i=e.onFailed)==null||i.call(e,r);break;case"submitted":(m=e.onSubmitted)==null||m.call(e,r);break;case"terms-accepted":(v=e.onTermsAccepted)==null||v.call(e,r);break;case"error":(U=e.onError)==null||U.call(e,r);break}(V=u.get(n))==null||V.forEach(re=>re(r))},p=(n,t,r)=>{d.clearTimeout(f),x(new Error(t)),_("error",{code:n,message:t||b(n),...r?{details:r}:{}})},B=()=>{var n;d.clearTimeout(f),f=d.setTimeout(()=>p("frame_timeout",b("frame_timeout")),(n=e.readyTimeoutMs)!=null?n:2e4)},F=n=>{var t;(t=s==null?void 0:s.contentWindow)==null||t.postMessage(n,g)},O=async n=>{const t=await C(n);if(!K(t))throw new Error("getSession must return the session your server got from the SDK.");return t},te=()=>w||(w=(async()=>{let n;for(let t=0;t<2;t++)try{const r=await O({reason:"refresh",sessionId:a==null?void 0:a.sessionId});if(l)return;if(r.sessionId!==(a==null?void 0:a.sessionId)||R(r)!==g){p("session_changed","The refresh returned a different session. Your route must call hb.embed.refresh(sessionId).");return}a=r,F({hb:1,type:"token",token:r.launchToken});return}catch(r){if(n=r,l)return;await new Promise(c=>setTimeout(c,1500))}l||_("error",{code:"token_refresh_failed",message:n instanceof Error?n.message:"Could not renew the session."})})().finally(()=>{w=void 0}),w),L=n=>{var r,c,T,k,E,S;if(l||!s||n.source!==s.contentWindow||n.origin!==g||!Y(n.data))return;const t=n.data;if(t.type==="ready")j+=1,A=!1,d.clearTimeout(f),(async()=>{try{let i=a==null?void 0:a.launchToken;const m=a!=null&&a.expiresAt?Date.parse(a.expiresAt)<=Date.now():!1;if(j>1||m){const v=await O({reason:"refresh",sessionId:a==null?void 0:a.sessionId});if(l)return;a=v,i=v.launchToken}F({hb:1,type:"init",nonce:t.nonce,token:i}),B()}catch(i){p("init_failed",i instanceof Error?i.message:"Could not start the frame.")}})();else if(t.type==="resize"){if(e.height===void 0||e.height==="auto"){const i=Math.min(Q,Math.max((r=e.minHeight)!=null?r:320,Math.ceil(t.height)));s&&(s.style.height=`${Math.max(J,i)}px`)}}else if(t.type==="scroll-top"){if(s&&((c=e.onScrollTop)==null?void 0:c.call(e,s))!==!1&&e.scrollIntoView!==!1&&s.getBoundingClientRect().top<0){const i=typeof d.matchMedia=="function"&&d.matchMedia("(prefers-reduced-motion: reduce)").matches;s.scrollIntoView({block:"start",behavior:i?"auto":"smooth"})}}else if(t.type==="event"){if(t.name==="token-expiring"){_("token-expiring",t.data),te();return}if(t.name==="ready"){if(d.clearTimeout(f),A)return;A=!0,N()}else if(t.name==="error"){const i=(T=t.data)!=null?T:{},m=typeof i.code=="string"?i.code:"error";d.clearTimeout(f),A||x(new Error((E=(k=i.message)!=null?k:b(m))!=null?E:m)),_("error",{...typeof t.data=="object"&&t.data?t.data:{},code:m,message:(S=i.message)!=null?S:b(m)});return}_(t.name,t.data)}};return d.addEventListener("message",L),(async()=>{var n,t;try{const r=await O({reason:"initial"});if(l)return;if(g=R(r),r.allowedOrigin!==d.location.origin){p("origin_mismatch",`This session was created for ${r.allowedOrigin} but this page is ${d.location.origin}. Pass the right origin when your server creates the session.`);return}a=r,s=h.createElement("iframe"),s.setAttribute("sandbox",D),s.setAttribute("allow",z),s.setAttribute("allowfullscreen",""),s.setAttribute("referrerpolicy","origin"),s.setAttribute("title",(n=e.title)!=null?n:G[r.kind]),s.setAttribute("scrolling",typeof e.height=="number"?"auto":"no"),s.style.cssText="display:block;width:100%;border:0;background:#fff;color-scheme:light;",s.style.height=`${typeof e.height=="number"?e.height:(t=e.minHeight)!=null?t:320}px`,B(),s.src=r.frameUrl,o.appendChild(s)}catch(r){const c=r==null?void 0:r.code;if(typeof c=="string"&&I.includes(c)){p(c,r.message||b(c)||c,M(r.details));return}p("session_failed",r instanceof Error?r.message:"Could not get a session from your server.")}})(),{destroy(){l||(l=!0,d.removeEventListener("message",L),d.clearTimeout(f),u.clear(),s==null||s.remove(),s=void 0)},on(n,t){var c;const r=(c=u.get(n))!=null?c:new Set;return r.add(t),u.set(n,r),()=>r.delete(t)},off(n,t){var r;(r=u.get(n))==null||r.delete(t)},ready:P,get session(){return a},get destroyed(){return l}}}const ee="0.3.0";return y.SANDBOX=D,y.mount=Z,y.sessionFetcher=H,y.version=ee,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"}),y})({});
|
|
1
|
+
var HealthierBusiness=(function(y){"use strict";const I=[...["course_access_required","payment_pending","renewal_approval_required","access_expired"],"course_not_pending"],$=["not_started","payment_pending","awaiting_approval","expired"],X=["start_access","pay","await_approval","renew"];function M(o){const e=typeof o=="object"&&o!==null?o:{},h={};return typeof e.state=="string"&&$.includes(e.state)&&(h.state=e.state),(e.payer==="client"||e.payer==="candidate")&&(h.payer=e.payer),typeof e.next=="string"&&X.includes(e.next)&&(h.next=e.next),h}const Y={token_used:"The launch token was already used. A token works once: create or refresh the session and mount again.",token_invalid:"The launch token is not valid for this session. Make sure getSession returns the session your server just created or refreshed.",token_expired:"The launch token expired (it lasts 5 minutes and is renewed on refresh). Create or refresh the session and mount again.",frame_invalid:"The frame was not opened by the SDK. Show it only with HealthierBusiness.mount(), not with your own iframe.",origin_not_allowed:"This website is not the one the session was created for, or it is not registered. Add it under Developer > Embed in Hub and pass the same origin when your server creates the session.",not_allowed:"The content can only be opened through the SDK from the website the session was created for.",session_expired:"The session timed out (60 minutes without a refresh, 12 hours at most). Create a new session.",session_finished:"The session is complete. Create a new session if the person needs it again.",not_found:"The session does not exist (any more). Create a new session.",network:"The frame could not reach the Hub. Check the connection and try again.",frame_timeout:"The frame did not start. Common causes: the session expired or finished, the website is not allowed to show it, or the session was created for another origin.",origin_mismatch:"The session was created for a different origin than this page. Pass this page's origin when your server creates the session.",session_failed:"Your server route did not return a session. Check its response in the network tab.",session_changed:"Refreshing returned a different session. Your route must call hb.embed.refresh(sessionId) for a refresh.",token_refresh_failed:"Renewing the launch token failed twice. Check that your refresh route works and that the person is still signed in.",init_failed:"The frame could not be started with the token.",terms_required:"The candidate has not accepted the terms. The frame shows them first; nothing else can be used until they accept (watch for the terms-accepted event).",access_expired:"The candidate's access has ended. Renew it (accessStart, or the renewal calls when renewals need approval), then create a new session.",course_access_required:"The candidate's access has not been started. Start it with hb.onlineTraining.candidates.accessStart() on your server, then create the session again.",payment_pending:"The candidate has a payment link that is not paid yet. Ask them to pay it, then create the session again.",renewal_approval_required:"A renewal waits for approval. Approve it (renewalApprove or in Hub), then create the session again.",course_not_pending:"The candidate has already completed this course. Only courses still to do can be opened."};function b(o){return Y[o]}function K(o){if(typeof o!="object"||o===null)return!1;const e=o;return e.hb!==1?!1:e.type==="ready"?typeof e.nonce=="string"&&e.nonce.length>0&&e.nonce.length<=200:e.type==="event"?typeof e.name=="string":e.type==="resize"?typeof e.height=="number"&&Number.isFinite(e.height):e.type==="scroll-top"}function z(o){if(typeof o!="object"||o===null)return!1;const e=o;return typeof e.sessionId=="string"&&(e.kind==="course"||e.kind==="test"||e.kind==="oh_form")&&typeof e.launchToken=="string"&&typeof e.frameUrl=="string"&&(typeof e.expiresAt=="string"||e.expiresAt===null)&&typeof e.sessionExpiresAt=="string"&&typeof e.allowedOrigin=="string"}const R="allow-scripts allow-same-origin allow-forms allow-downloads allow-popups allow-popups-to-escape-sandbox",G="fullscreen; picture-in-picture; encrypted-media",J={course:"Course",test:"Test",oh_form:"Occupational health form"},Q=100,Z=3e4;function D(o){let e;try{e=new URL(o.frameUrl)}catch{throw new Error("The session has no valid frameUrl.")}const h=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname.endsWith(".localhost")||e.hostname.endsWith(".test");if(e.protocol!=="https:"&&!(e.protocol==="http:"&&h))throw new Error("The frame must be served over https.");return e.origin}function H(o){const{endpoint:e,kind:h,courseId:d,formShortcode:C,fetchInit:u}=o;if(!e||!h)throw new Error("mount needs either getSession, or endpoint and kind.");return async({reason:l,sessionId:a})=>{const g=await fetch(e,{credentials:"same-origin",...u,method:"POST",headers:{"content-type":"application/json",...u==null?void 0:u.headers},body:JSON.stringify(l==="refresh"?{action:"refresh",sessionId:a}:{action:"create",kind:h,courseId:d,formShortcode:C})}),s=await g.json().catch(()=>({}));if(!g.ok){const f=typeof s.message=="string"?s.message:`Your server answered HTTP ${g.status}.`,w=typeof s.error=="string"&&I.includes(s.error)?s.error:void 0;throw Object.assign(new Error(f),w?{code:w,details:M(s.details)}:{})}return s}}function ee(o,e){var L;const h=o.ownerDocument,d=h.defaultView,C=(L=e.getSession)!=null?L:H(e),u=new Map;let l=!1,a,g="",s,f,w,j=0,A=!1,N,x;const P=new Promise((n,r)=>{N=n,x=r});P.catch(()=>{});const _=(n,r)=>{var c,T,k,E,S,i,m,v,U,V,W;if(l)return;const t=r!=null?r:{};switch((c=e.onEvent)==null||c.call(e,{name:n,data:r}),n){case"ready":(T=e.onReady)==null||T.call(e);break;case"progress":(k=e.onProgress)==null||k.call(e,t);break;case"completed":(E=e.onCompleted)==null||E.call(e,t);break;case"passed":(S=e.onPassed)==null||S.call(e,t);break;case"failed":(i=e.onFailed)==null||i.call(e,t);break;case"submitted":(m=e.onSubmitted)==null||m.call(e,t);break;case"test-requested":(v=e.onTestRequested)==null||v.call(e,t);break;case"terms-accepted":(U=e.onTermsAccepted)==null||U.call(e,t);break;case"error":(V=e.onError)==null||V.call(e,t);break}(W=u.get(n))==null||W.forEach(se=>se(t))},p=(n,r,t)=>{d.clearTimeout(f),x(new Error(r)),_("error",{code:n,message:r||b(n),...t?{details:t}:{}})},B=()=>{var n;d.clearTimeout(f),f=d.setTimeout(()=>p("frame_timeout",b("frame_timeout")),(n=e.readyTimeoutMs)!=null?n:2e4)},q=n=>{var r;(r=s==null?void 0:s.contentWindow)==null||r.postMessage(n,g)},O=async n=>{const r=await C(n);if(!z(r))throw new Error("getSession must return the session your server got from the SDK.");return r},re=()=>w||(w=(async()=>{let n;for(let r=0;r<2;r++)try{const t=await O({reason:"refresh",sessionId:a==null?void 0:a.sessionId});if(l)return;if(t.sessionId!==(a==null?void 0:a.sessionId)||D(t)!==g){p("session_changed","The refresh returned a different session. Your route must call hb.embed.refresh(sessionId).");return}a=t,q({hb:1,type:"token",token:t.launchToken});return}catch(t){if(n=t,l)return;await new Promise(c=>setTimeout(c,1500))}l||_("error",{code:"token_refresh_failed",message:n instanceof Error?n.message:"Could not renew the session."})})().finally(()=>{w=void 0}),w),F=n=>{var t,c,T,k,E,S;if(l||!s||n.source!==s.contentWindow||n.origin!==g||!K(n.data))return;const r=n.data;if(r.type==="ready")j+=1,A=!1,d.clearTimeout(f),(async()=>{try{let i=a==null?void 0:a.launchToken;const m=a!=null&&a.expiresAt?Date.parse(a.expiresAt)<=Date.now():!1;if(j>1||m){const v=await O({reason:"refresh",sessionId:a==null?void 0:a.sessionId});if(l)return;a=v,i=v.launchToken}q({hb:1,type:"init",nonce:r.nonce,token:i}),B()}catch(i){p("init_failed",i instanceof Error?i.message:"Could not start the frame.")}})();else if(r.type==="resize"){if(e.height===void 0||e.height==="auto"){const i=Math.min(Z,Math.max((t=e.minHeight)!=null?t:320,Math.ceil(r.height)));s&&(s.style.height=`${Math.max(Q,i)}px`)}}else if(r.type==="scroll-top"){if(s&&((c=e.onScrollTop)==null?void 0:c.call(e,s))!==!1&&e.scrollIntoView!==!1&&s.getBoundingClientRect().top<0){const i=typeof d.matchMedia=="function"&&d.matchMedia("(prefers-reduced-motion: reduce)").matches;s.scrollIntoView({block:"start",behavior:i?"auto":"smooth"})}}else if(r.type==="event"){if(r.name==="token-expiring"){_("token-expiring",r.data),re();return}if(r.name==="ready"){if(d.clearTimeout(f),A)return;A=!0,N()}else if(r.name==="error"){const i=(T=r.data)!=null?T:{},m=typeof i.code=="string"?i.code:"error";d.clearTimeout(f),A||x(new Error((E=(k=i.message)!=null?k:b(m))!=null?E:m)),_("error",{...typeof r.data=="object"&&r.data?r.data:{},code:m,message:(S=i.message)!=null?S:b(m)});return}_(r.name,r.data)}};return d.addEventListener("message",F),(async()=>{var n,r;try{const t=await O({reason:"initial"});if(l)return;if(g=D(t),t.allowedOrigin!==d.location.origin){p("origin_mismatch",`This session was created for ${t.allowedOrigin} but this page is ${d.location.origin}. Pass the right origin when your server creates the session.`);return}a=t,s=h.createElement("iframe"),s.setAttribute("sandbox",R),s.setAttribute("allow",G),s.setAttribute("allowfullscreen",""),s.setAttribute("referrerpolicy","origin"),s.setAttribute("title",(n=e.title)!=null?n:J[t.kind]),s.setAttribute("scrolling",typeof e.height=="number"?"auto":"no"),s.style.cssText="display:block;width:100%;border:0;background:#fff;color-scheme:light;",s.style.height=`${typeof e.height=="number"?e.height:(r=e.minHeight)!=null?r:320}px`,B(),s.src=t.frameUrl,o.appendChild(s)}catch(t){const c=t==null?void 0:t.code;if(typeof c=="string"&&I.includes(c)){p(c,t.message||b(c)||c,M(t.details));return}p("session_failed",t instanceof Error?t.message:"Could not get a session from your server.")}})(),{destroy(){l||(l=!0,d.removeEventListener("message",F),d.clearTimeout(f),u.clear(),s==null||s.remove(),s=void 0)},on(n,r){var c;const t=(c=u.get(n))!=null?c:new Set;return t.add(r),u.set(n,t),()=>t.delete(r)},off(n,r){var t;(t=u.get(n))==null||t.delete(r)},ready:P,get session(){return a},get destroyed(){return l}}}const te="0.4.1";return y.SANDBOX=R,y.mount=ee,y.sessionFetcher=H,y.version=te,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"}),y})({});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@healthier-business/hub-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.1",
|
|
4
4
|
"description": "The official JavaScript and TypeScript SDK for the Healthier Business Hub API v2: automatic tokens, typed resources for every portal, signed webhooks and embeddable courses, tests and OH forms.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Sanchit Patil",
|