@ondewo/s2t-client-typescript 7.4.1 → 7.5.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.
@@ -0,0 +1,193 @@
1
+ /**
2
+ * Minimal structural type of the fetch Response fields this helper reads. Keeps the module
3
+ * self-contained (no DOM lib dependency) while still typing the injectable `fetchImpl`.
4
+ */
5
+ export interface TokenFetchResponse {
6
+ /** Whether the HTTP status is in the 2xx success range. */
7
+ ok: boolean;
8
+ /** The numeric HTTP status code of the response. */
9
+ status: number;
10
+ /**
11
+ * Read the response body as text.
12
+ *
13
+ * @returns A promise resolving to the raw response body string.
14
+ */
15
+ text(): Promise<string>;
16
+ }
17
+ /** Init object passed to the injectable fetch when POSTing to the token endpoint. */
18
+ export interface TokenFetchInit {
19
+ /** HTTP method (always `"POST"` for the token endpoint). */
20
+ method: string;
21
+ /** Request headers (Content-Type + Accept) as a plain string map. */
22
+ headers: Record<string, string>;
23
+ /** The `application/x-www-form-urlencoded` request body. */
24
+ body: string;
25
+ /**
26
+ * Optional undici dispatcher (Node only). The default transport attaches an insecure
27
+ * `Agent({ connect: { rejectUnauthorized: false } })` here when `verifySsl` is `false`; the global
28
+ * WHATWG fetch honours it. Never set on an injected `fetchImpl` and ignored in a browser bundle.
29
+ */
30
+ dispatcher?: unknown;
31
+ }
32
+ /**
33
+ * Injectable fetch signature (a subset of the global `fetch`) used by the token endpoint call.
34
+ *
35
+ * @param url - The token endpoint URL to POST to.
36
+ * @param init - The request method, headers, and form-encoded body.
37
+ * @returns A promise resolving to the structural {@link TokenFetchResponse}.
38
+ */
39
+ export type TokenFetch = (url: string, init: TokenFetchInit) => Promise<TokenFetchResponse>;
40
+ /** Options for the D18 headless-SDK offline-token login. */
41
+ export interface OfflineTokenLoginOptions {
42
+ /** Base Keycloak URL, e.g. "https://auth.example.com/auth" (trailing slash tolerated). */
43
+ keycloakUrl: string;
44
+ /** Realm name, e.g. "ondewo-ccai-platform". */
45
+ realm: string;
46
+ /** Public SDK client id, e.g. "ondewo-nlu-cai-sdk-public". NO client_secret (Q1). */
47
+ clientId: string;
48
+ /** 2FA-exempt technical-user email. */
49
+ username: string;
50
+ /** Technical-user password. */
51
+ password: string;
52
+ /** Optional cap (seconds) on how long the auto-refresh loop runs after login. */
53
+ tokenExpirationInS?: number;
54
+ /** Optional fetch override (tests inject a mock); defaults to the global fetch. */
55
+ fetchImpl?: TokenFetch;
56
+ /**
57
+ * Verify the Keycloak TLS certificate on the token-endpoint call. Default `true` (secure). Set
58
+ * `false` ONLY for a self-signed local Envoy (e.g. `https://localhost:12001/auth`). Node-only: it is
59
+ * ignored in a browser bundle (the browser owns TLS) and ignored when a custom `fetchImpl` is
60
+ * injected. When `false` under Node the default transport attaches an insecure undici dispatcher.
61
+ */
62
+ keycloakVerifySsl?: boolean;
63
+ /** Optional clock override returning epoch ms (tests); defaults to Date.now. */
64
+ nowInMs?: () => number;
65
+ }
66
+ /** Error raised on any token-endpoint or token-shape failure. */
67
+ export declare class TokenError extends Error {
68
+ /**
69
+ * Construct a `TokenError` with a fixed `name` of `"TokenError"`.
70
+ *
71
+ * @param message - Human-readable description of the token failure.
72
+ */
73
+ constructor(message: string);
74
+ }
75
+ /**
76
+ * The undici `Agent` options that switch TLS certificate verification OFF for the token request.
77
+ * Exported so the security-relevant `rejectUnauthorized: false` literal is pinned by a test rather than
78
+ * living as a bare literal that could be flipped without any test noticing.
79
+ */
80
+ export declare const INSECURE_AGENT_OPTIONS: {
81
+ connect: {
82
+ rejectUnauthorized: boolean;
83
+ };
84
+ };
85
+ /**
86
+ * Build the DEFAULT token transport (used only when no `fetchImpl` is injected). It delegates to the
87
+ * global WHATWG fetch, and -- when `verifySsl` is `false` under Node -- attaches an insecure undici
88
+ * dispatcher to the request init so the token POST skips certificate verification. With `verifySsl`
89
+ * `true` (the default) it is a plain pass-through to `globalThis.fetch`, i.e. unchanged behavior.
90
+ *
91
+ * @param verifySsl - Whether to verify the Keycloak TLS certificate; `false` opts into the insecure path.
92
+ * @returns A {@link TokenFetch} that resolves the global fetch at call time (honoring test overrides).
93
+ */
94
+ export declare function createDefaultTokenFetch(verifySsl: boolean): TokenFetch;
95
+ /**
96
+ * A live access-token holder backed by a bounded auto-refresh loop. Obtain one from {@link login};
97
+ * read {@link getAuthorizationHeader} for the gRPC `Authorization` metadata and call {@link stop} when done.
98
+ */
99
+ export declare class OfflineTokenProvider {
100
+ /** Pre-built OIDC token endpoint URL the provider POSTs to for both login and refresh. */
101
+ private readonly tokenEndpoint;
102
+ /** Public SDK client id sent as `client_id` (no `client_secret` -- Q1). */
103
+ private readonly clientId;
104
+ /** Optional cap (seconds) after which the auto-refresh loop stops; `undefined` means unbounded. */
105
+ private readonly tokenExpirationInS;
106
+ /** The injectable fetch used for every token request (defaults to the global `fetch`). */
107
+ private readonly fetchImpl;
108
+ /** Clock returning epoch milliseconds, used for deadline arithmetic (defaults to `Date.now`). */
109
+ private readonly nowInMs;
110
+ /** The current access token, or `null` before bootstrap / after the bounded loop lapses. */
111
+ private accessToken;
112
+ /** The newest offline refresh token, or `null` before bootstrap. */
113
+ private refreshToken;
114
+ /** Handle of the single armed refresh timer, or `null` when none is pending. */
115
+ private timer;
116
+ /** Whether {@link stop} has been called; suppresses any further refresh scheduling. */
117
+ private stopped;
118
+ /** Absolute epoch-ms deadline at which the loop stops, or `null` when unbounded. */
119
+ private deadlineInMs;
120
+ /** Optional callback invoked with the error of a failed background refresh. */
121
+ private onRefreshErrorHandler;
122
+ /**
123
+ * Initialize the provider from login options without performing any network call. Use {@link login}
124
+ * (which constructs and then {@link bootstrap}s) for the normal flow.
125
+ *
126
+ * @param options - The D18 headless-SDK offline-token login options.
127
+ */
128
+ constructor(options: OfflineTokenLoginOptions);
129
+ /**
130
+ * Perform the one-time ROPC login and arm the first refresh. Awaited by {@link login}.
131
+ *
132
+ * @param username - The 2FA-exempt technical-user email.
133
+ * @param password - The technical-user password.
134
+ * @returns A promise that resolves once the access token is stored and the first refresh is scheduled.
135
+ * @throws {@link TokenError} If the token endpoint fails, or when the response carries no usable
136
+ * `refresh_token` -- absent, not a string, or empty (i.e. the SDK client lacks directAccessGrants
137
+ * + the `offline_access` scope).
138
+ */
139
+ bootstrap(username: string, password: string): Promise<void>;
140
+ /**
141
+ * Exchange the offline refresh token for a fresh access token and re-arm the next refresh. No-ops
142
+ * once {@link stop} has been called or the bounded deadline has elapsed.
143
+ *
144
+ * @returns A promise that resolves once the refreshed token is stored and the next refresh is armed.
145
+ * @throws {@link TokenError} If the refresh token request fails or returns an invalid body; the
146
+ * rejection is routed to the {@link onRefreshError} handler by the firing timer.
147
+ */
148
+ private refresh;
149
+ /**
150
+ * Arm a single timer for the next refresh, clamped to the bounded deadline. Stops silently once
151
+ * `tokenExpirationInS` has elapsed (no further renewal -> access lapses -> re-login required).
152
+ *
153
+ * @param expiresInRaw - The `expires_in` (seconds) from the latest token response, or `undefined`;
154
+ * non-positive / missing values fall back to {@link MIN_REFRESH_DELAY_IN_S}.
155
+ */
156
+ private scheduleRefresh;
157
+ /**
158
+ * Register a callback invoked with the error of a failed background refresh (optional diagnostics).
159
+ * A later call replaces any previously registered handler.
160
+ *
161
+ * @param handler - Receives the rejection value of a failed background refresh.
162
+ */
163
+ onRefreshError(handler: (error: unknown) => void): void;
164
+ /**
165
+ * Read the current access token.
166
+ *
167
+ * @returns The current access token, or `null` before bootstrap / after the bounded loop has lapsed.
168
+ */
169
+ getAccessToken(): string | null;
170
+ /**
171
+ * Build the value for an `Authorization` gRPC metadata header.
172
+ *
173
+ * @returns The header value `Bearer <access_token>`.
174
+ * @throws {@link TokenError} If no access token is available (login not completed or already lapsed).
175
+ */
176
+ getAuthorizationHeader(): string;
177
+ /**
178
+ * Stop the auto-refresh loop and clear any pending timer. Idempotent; safe to call from any state.
179
+ * After this the access token is no longer renewed and will eventually lapse.
180
+ */
181
+ stop(): void;
182
+ }
183
+ /**
184
+ * One-time ROPC + offline_access login against the PUBLIC SDK client, returning a live token provider
185
+ * whose access token is auto-refreshed in the background until `tokenExpirationInS` elapses.
186
+ *
187
+ * @param options - The D18 headless-SDK offline-token login options; the five string fields
188
+ * (`keycloakUrl`, `realm`, `clientId`, `username`, `password`) are required and must be non-empty.
189
+ * @returns A promise resolving to a bootstrapped {@link OfflineTokenProvider} with its first refresh armed.
190
+ * @throws {@link TokenError} If `options` is missing, a required field is absent/empty, or the
191
+ * bootstrap login fails (see {@link OfflineTokenProvider.bootstrap}).
192
+ */
193
+ export declare function login(options: OfflineTokenLoginOptions): Promise<OfflineTokenProvider>;
@@ -0,0 +1,374 @@
1
+ "use strict";
2
+ // Copyright 2021-2026 ONDEWO GmbH
3
+ //
4
+ // Licensed under the Apache License, Version 2.0 (the "License");
5
+ // you may not use this file except in compliance with the License.
6
+ // You may obtain a copy of the License at
7
+ //
8
+ // http://www.apache.org/licenses/LICENSE-2.0
9
+ //
10
+ // Unless required by applicable law or agreed to in writing, software
11
+ // distributed under the License is distributed on an "AS IS" BASIS,
12
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ // See the License for the specific language governing permissions and
14
+ // limitations under the License.
15
+ //
16
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
17
+ if (k2 === undefined) k2 = k;
18
+ var desc = Object.getOwnPropertyDescriptor(m, k);
19
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
20
+ desc = { enumerable: true, get: function() { return m[k]; } };
21
+ }
22
+ Object.defineProperty(o, k2, desc);
23
+ }) : (function(o, m, k, k2) {
24
+ if (k2 === undefined) k2 = k;
25
+ o[k2] = m[k];
26
+ }));
27
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
28
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
29
+ }) : function(o, v) {
30
+ o["default"] = v;
31
+ });
32
+ var __importStar = (this && this.__importStar) || (function () {
33
+ var ownKeys = function(o) {
34
+ ownKeys = Object.getOwnPropertyNames || function (o) {
35
+ var ar = [];
36
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
37
+ return ar;
38
+ };
39
+ return ownKeys(o);
40
+ };
41
+ return function (mod) {
42
+ if (mod && mod.__esModule) return mod;
43
+ var result = {};
44
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
45
+ __setModuleDefault(result, mod);
46
+ return result;
47
+ };
48
+ })();
49
+ Object.defineProperty(exports, "__esModule", { value: true });
50
+ exports.OfflineTokenProvider = exports.INSECURE_AGENT_OPTIONS = exports.TokenError = void 0;
51
+ exports.createDefaultTokenFetch = createDefaultTokenFetch;
52
+ exports.login = login;
53
+ /**
54
+ * D18 headless-SDK auth helper (keycloak-migration-plan §7.8 + D18).
55
+ *
56
+ * One-time ROPC login (`grant_type=password`, `scope=offline_access`) against the PUBLIC SDK client
57
+ * `ondewo-nlu-cai-sdk-public` (no client_secret -- Q1), then a bounded background loop that refreshes
58
+ * the short-lived access token from the offline refresh token before it expires. The current access
59
+ * token is exposed for an `Authorization: Bearer <token>` gRPC metadata header. The refresh loop stops
60
+ * after `tokenExpirationInS` (if given) has elapsed since login.
61
+ *
62
+ * @packageDocumentation
63
+ */
64
+ /**
65
+ * Seconds of head-room subtracted from a token's `expires_in` so the refresh fires before the access
66
+ * token actually lapses (covers clock skew + the round-trip to Keycloak).
67
+ */
68
+ const REFRESH_SKEW_IN_S = 30;
69
+ /** Lower bound (seconds) for the scheduled refresh delay so a tiny/zero `expires_in` cannot spin a hot loop. */
70
+ const MIN_REFRESH_DELAY_IN_S = 1;
71
+ /** Error raised on any token-endpoint or token-shape failure. */
72
+ class TokenError extends Error {
73
+ /**
74
+ * Construct a `TokenError` with a fixed `name` of `"TokenError"`.
75
+ *
76
+ * @param message - Human-readable description of the token failure.
77
+ */
78
+ constructor(message) {
79
+ super(message);
80
+ this.name = 'TokenError';
81
+ }
82
+ }
83
+ exports.TokenError = TokenError;
84
+ /**
85
+ * Build the OIDC token endpoint URL for a realm, tolerating a trailing slash on `keycloakUrl` and an
86
+ * optional `/auth` relative path already baked into it.
87
+ *
88
+ * @param keycloakUrl - Base Keycloak URL (trailing slash tolerated).
89
+ * @param realm - Realm name; URL-encoded into the path.
90
+ * @returns The fully-qualified `.../realms/<realm>/protocol/openid-connect/token` endpoint URL.
91
+ */
92
+ function buildTokenEndpoint(keycloakUrl, realm) {
93
+ const base = keycloakUrl.replace(/\/+$/, '');
94
+ return `${base}/realms/${encodeURIComponent(realm)}/protocol/openid-connect/token`;
95
+ }
96
+ /**
97
+ * POST an `application/x-www-form-urlencoded` body to the token endpoint and return the parsed JSON.
98
+ *
99
+ * @param tokenEndpoint - The OIDC token endpoint URL (see {@link buildTokenEndpoint}).
100
+ * @param params - Form fields to URL-encode into the request body (grant type, client id, credentials).
101
+ * @param fetchImpl - The injectable fetch used to perform the request.
102
+ * @returns A promise resolving to the parsed {@link KeycloakTokenResponse}.
103
+ * @throws {@link TokenError} On a non-2xx response, an unparseable body, or a missing `access_token`.
104
+ */
105
+ async function postTokenRequest(tokenEndpoint, params, fetchImpl) {
106
+ const body = new URLSearchParams(params).toString();
107
+ const response = await fetchImpl(tokenEndpoint, {
108
+ method: 'POST',
109
+ headers: {
110
+ 'Content-Type': 'application/x-www-form-urlencoded',
111
+ Accept: 'application/json'
112
+ },
113
+ body
114
+ });
115
+ const text = await response.text();
116
+ if (!response.ok) {
117
+ throw new TokenError(`Keycloak token endpoint returned HTTP ${response.status}: ${text}`);
118
+ }
119
+ let parsed;
120
+ try {
121
+ parsed = JSON.parse(text);
122
+ }
123
+ catch {
124
+ throw new TokenError(`Keycloak token endpoint returned a non-JSON body: ${text}`);
125
+ }
126
+ if (typeof parsed.access_token !== 'string' || parsed.access_token.length === 0) {
127
+ throw new TokenError('Keycloak token response did not contain an access_token');
128
+ }
129
+ return parsed;
130
+ }
131
+ /**
132
+ * The undici `Agent` options that switch TLS certificate verification OFF for the token request.
133
+ * Exported so the security-relevant `rejectUnauthorized: false` literal is pinned by a test rather than
134
+ * living as a bare literal that could be flipped without any test noticing.
135
+ */
136
+ exports.INSECURE_AGENT_OPTIONS = {
137
+ connect: { rejectUnauthorized: false }
138
+ };
139
+ /** Cached insecure undici dispatcher (built once, reused) so `verifySsl:false` costs one Agent. */
140
+ let insecureNodeDispatcher;
141
+ /**
142
+ * Lazily build a cached undici `Agent` that skips TLS certificate verification -- the Node analog of
143
+ * Python's `requests.post(..., verify=False)`. Node-guarded and loaded via a dynamic `import("undici")`
144
+ * so a browser bundle never pulls in `undici` and the flag stays a hard no-op outside Node.
145
+ *
146
+ * @returns The insecure dispatcher under Node, or `undefined` in a browser (TLS is owned by the browser).
147
+ */
148
+ async function getInsecureNodeDispatcher() {
149
+ const nodeProcess = globalThis.process;
150
+ /* c8 ignore next 3 -- browser guard: not exercised under the Node test runner */
151
+ if (nodeProcess === undefined || nodeProcess.versions === undefined || nodeProcess.versions.node === undefined) {
152
+ return undefined;
153
+ }
154
+ if (insecureNodeDispatcher === undefined) {
155
+ const undiciModuleName = 'undici';
156
+ const undici = (await Promise.resolve(`${undiciModuleName}`).then(s => __importStar(require(s))));
157
+ insecureNodeDispatcher = new undici.Agent(exports.INSECURE_AGENT_OPTIONS);
158
+ }
159
+ return insecureNodeDispatcher;
160
+ }
161
+ /**
162
+ * Build the DEFAULT token transport (used only when no `fetchImpl` is injected). It delegates to the
163
+ * global WHATWG fetch, and -- when `verifySsl` is `false` under Node -- attaches an insecure undici
164
+ * dispatcher to the request init so the token POST skips certificate verification. With `verifySsl`
165
+ * `true` (the default) it is a plain pass-through to `globalThis.fetch`, i.e. unchanged behavior.
166
+ *
167
+ * @param verifySsl - Whether to verify the Keycloak TLS certificate; `false` opts into the insecure path.
168
+ * @returns A {@link TokenFetch} that resolves the global fetch at call time (honoring test overrides).
169
+ */
170
+ function createDefaultTokenFetch(verifySsl) {
171
+ return async (url, init) => {
172
+ const dispatcher = verifySsl ? undefined : await getInsecureNodeDispatcher();
173
+ const effectiveInit = dispatcher !== undefined ? { ...init, dispatcher } : init;
174
+ const globalFetch = globalThis.fetch;
175
+ return globalFetch(url, effectiveInit);
176
+ };
177
+ }
178
+ /**
179
+ * A live access-token holder backed by a bounded auto-refresh loop. Obtain one from {@link login};
180
+ * read {@link getAuthorizationHeader} for the gRPC `Authorization` metadata and call {@link stop} when done.
181
+ */
182
+ class OfflineTokenProvider {
183
+ /**
184
+ * Initialize the provider from login options without performing any network call. Use {@link login}
185
+ * (which constructs and then {@link bootstrap}s) for the normal flow.
186
+ *
187
+ * @param options - The D18 headless-SDK offline-token login options.
188
+ */
189
+ constructor(options) {
190
+ this.tokenEndpoint = buildTokenEndpoint(options.keycloakUrl, options.realm);
191
+ this.clientId = options.clientId;
192
+ this.tokenExpirationInS = options.tokenExpirationInS;
193
+ // A custom fetchImpl always wins (the verifySsl flag is ignored for injected transports); only the
194
+ // DEFAULT transport honors verifySsl, and only under Node. Absent/undefined verifySsl => secure (true).
195
+ const verifySsl = options.keycloakVerifySsl !== false;
196
+ this.fetchImpl = options.fetchImpl !== undefined ? options.fetchImpl : createDefaultTokenFetch(verifySsl);
197
+ this.nowInMs = options.nowInMs !== undefined ? options.nowInMs : Date.now;
198
+ this.accessToken = null;
199
+ this.refreshToken = null;
200
+ this.timer = null;
201
+ this.stopped = false;
202
+ this.deadlineInMs = null;
203
+ this.onRefreshErrorHandler = null;
204
+ }
205
+ /**
206
+ * Perform the one-time ROPC login and arm the first refresh. Awaited by {@link login}.
207
+ *
208
+ * @param username - The 2FA-exempt technical-user email.
209
+ * @param password - The technical-user password.
210
+ * @returns A promise that resolves once the access token is stored and the first refresh is scheduled.
211
+ * @throws {@link TokenError} If the token endpoint fails, or when the response carries no usable
212
+ * `refresh_token` -- absent, not a string, or empty (i.e. the SDK client lacks directAccessGrants
213
+ * + the `offline_access` scope).
214
+ */
215
+ async bootstrap(username, password) {
216
+ const tokenResponse = await postTokenRequest(this.tokenEndpoint, {
217
+ grant_type: 'password',
218
+ client_id: this.clientId,
219
+ username,
220
+ password,
221
+ scope: 'offline_access'
222
+ }, this.fetchImpl);
223
+ this.accessToken = tokenResponse.access_token;
224
+ // An empty string is rejected exactly like a missing token, mirroring the rotation guard in
225
+ // refresh(): a blank offline token would otherwise bootstrap a provider whose every renewal POSTs
226
+ // `refresh_token=` and fails, turning a clear login error into a silent expiry ~5 minutes later.
227
+ this.refreshToken =
228
+ typeof tokenResponse.refresh_token === 'string' && tokenResponse.refresh_token.length > 0
229
+ ? tokenResponse.refresh_token
230
+ : null;
231
+ if (this.refreshToken === null) {
232
+ throw new TokenError('Keycloak token response did not contain a refresh_token; the SDK client must have ' +
233
+ 'directAccessGrants + the offline_access scope (ondewo-nlu-cai-sdk-public)');
234
+ }
235
+ if (this.tokenExpirationInS !== undefined) {
236
+ const expirationInMs = this.tokenExpirationInS * 1000;
237
+ this.deadlineInMs = this.nowInMs() + expirationInMs;
238
+ }
239
+ this.scheduleRefresh(tokenResponse.expires_in);
240
+ }
241
+ /**
242
+ * Exchange the offline refresh token for a fresh access token and re-arm the next refresh. No-ops
243
+ * once {@link stop} has been called or the bounded deadline has elapsed.
244
+ *
245
+ * @returns A promise that resolves once the refreshed token is stored and the next refresh is armed.
246
+ * @throws {@link TokenError} If the refresh token request fails or returns an invalid body; the
247
+ * rejection is routed to the {@link onRefreshError} handler by the firing timer.
248
+ */
249
+ async refresh() {
250
+ /* c8 ignore next 3 -- unreachable: stop() always clears the only timer that calls refresh() */
251
+ if (this.stopped) {
252
+ return;
253
+ }
254
+ // Re-check the bounded deadline at fire time (not just at schedule time): once it has elapsed the
255
+ // loop stops with no further renewal -> the access token lapses -> re-login is required.
256
+ if (this.deadlineInMs !== null && this.nowInMs() >= this.deadlineInMs) {
257
+ this.stop();
258
+ return;
259
+ }
260
+ const tokenResponse = await postTokenRequest(this.tokenEndpoint, {
261
+ grant_type: 'refresh_token',
262
+ client_id: this.clientId,
263
+ refresh_token: this.refreshToken
264
+ }, this.fetchImpl);
265
+ this.accessToken = tokenResponse.access_token;
266
+ // Keycloak may rotate the offline refresh token; keep the newest one when present.
267
+ if (typeof tokenResponse.refresh_token === 'string' && tokenResponse.refresh_token.length > 0) {
268
+ this.refreshToken = tokenResponse.refresh_token;
269
+ }
270
+ this.scheduleRefresh(tokenResponse.expires_in);
271
+ }
272
+ /**
273
+ * Arm a single timer for the next refresh, clamped to the bounded deadline. Stops silently once
274
+ * `tokenExpirationInS` has elapsed (no further renewal -> access lapses -> re-login required).
275
+ *
276
+ * @param expiresInRaw - The `expires_in` (seconds) from the latest token response, or `undefined`;
277
+ * non-positive / missing values fall back to {@link MIN_REFRESH_DELAY_IN_S}.
278
+ */
279
+ scheduleRefresh(expiresInRaw) {
280
+ if (this.stopped) {
281
+ return;
282
+ }
283
+ const expiresInS = typeof expiresInRaw === 'number' && expiresInRaw > 0 ? expiresInRaw : MIN_REFRESH_DELAY_IN_S;
284
+ let delayInS = Math.max(expiresInS - REFRESH_SKEW_IN_S, MIN_REFRESH_DELAY_IN_S);
285
+ if (this.deadlineInMs !== null) {
286
+ const remainingInMs = this.deadlineInMs - this.nowInMs();
287
+ if (remainingInMs <= 0) {
288
+ this.stop();
289
+ return;
290
+ }
291
+ delayInS = Math.min(delayInS, remainingInMs / 1000);
292
+ }
293
+ this.timer = setTimeout(() => {
294
+ this.refresh().catch((refreshError) => {
295
+ // Swallow a transient refresh failure but surface it so the caller can react; the next
296
+ // gRPC call gets the stale (possibly expired) token and re-logs in on UNAUTHENTICATED.
297
+ if (this.onRefreshErrorHandler !== null) {
298
+ this.onRefreshErrorHandler(refreshError);
299
+ }
300
+ });
301
+ }, delayInS * 1000);
302
+ // Do not keep the event loop alive solely for the refresh timer.
303
+ /* c8 ignore next 3 -- the else branch is unreachable: Node's Timeout always exposes unref() */
304
+ if (typeof this.timer.unref === 'function') {
305
+ this.timer.unref();
306
+ }
307
+ }
308
+ /**
309
+ * Register a callback invoked with the error of a failed background refresh (optional diagnostics).
310
+ * A later call replaces any previously registered handler.
311
+ *
312
+ * @param handler - Receives the rejection value of a failed background refresh.
313
+ */
314
+ onRefreshError(handler) {
315
+ this.onRefreshErrorHandler = handler;
316
+ }
317
+ /**
318
+ * Read the current access token.
319
+ *
320
+ * @returns The current access token, or `null` before bootstrap / after the bounded loop has lapsed.
321
+ */
322
+ getAccessToken() {
323
+ return this.accessToken;
324
+ }
325
+ /**
326
+ * Build the value for an `Authorization` gRPC metadata header.
327
+ *
328
+ * @returns The header value `Bearer <access_token>`.
329
+ * @throws {@link TokenError} If no access token is available (login not completed or already lapsed).
330
+ */
331
+ getAuthorizationHeader() {
332
+ if (this.accessToken === null) {
333
+ throw new TokenError('No access token available; login() has not completed or has lapsed');
334
+ }
335
+ return `Bearer ${this.accessToken}`;
336
+ }
337
+ /**
338
+ * Stop the auto-refresh loop and clear any pending timer. Idempotent; safe to call from any state.
339
+ * After this the access token is no longer renewed and will eventually lapse.
340
+ */
341
+ stop() {
342
+ this.stopped = true;
343
+ if (this.timer !== null) {
344
+ clearTimeout(this.timer);
345
+ this.timer = null;
346
+ }
347
+ }
348
+ }
349
+ exports.OfflineTokenProvider = OfflineTokenProvider;
350
+ /**
351
+ * One-time ROPC + offline_access login against the PUBLIC SDK client, returning a live token provider
352
+ * whose access token is auto-refreshed in the background until `tokenExpirationInS` elapses.
353
+ *
354
+ * @param options - The D18 headless-SDK offline-token login options; the five string fields
355
+ * (`keycloakUrl`, `realm`, `clientId`, `username`, `password`) are required and must be non-empty.
356
+ * @returns A promise resolving to a bootstrapped {@link OfflineTokenProvider} with its first refresh armed.
357
+ * @throws {@link TokenError} If `options` is missing, a required field is absent/empty, or the
358
+ * bootstrap login fails (see {@link OfflineTokenProvider.bootstrap}).
359
+ */
360
+ async function login(options) {
361
+ if (options === undefined || options === null) {
362
+ throw new TokenError('login() requires an options object');
363
+ }
364
+ const requiredKeys = ['keycloakUrl', 'realm', 'clientId', 'username', 'password'];
365
+ for (const key of requiredKeys) {
366
+ const value = options[key];
367
+ if (typeof value !== 'string' || value.length === 0) {
368
+ throw new TokenError(`login() option "${key}" is required and must be a non-empty string`);
369
+ }
370
+ }
371
+ const provider = new OfflineTokenProvider(options);
372
+ await provider.bootstrap(options.username, options.password);
373
+ return provider;
374
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ondewo/s2t-client-typescript",
3
- "version": "7.4.1",
3
+ "version": "7.5.0",
4
4
  "description": "ONDEWO Speech to Text (S2T) Client library for Typescript",
5
5
  "author": "ONDEWO GmbH <office@ondewo.com>",
6
6
  "homepage": "https://ondewo.com",
package/public-api.d.ts CHANGED
@@ -1,4 +1,5 @@
1
+ export * from './api/google/protobuf/struct_pb.d';
2
+ export * from './api/google/protobuf/empty_pb.d';
1
3
  export * from './api/ondewo/s2t/speech-to-text_pb.d';
2
4
  export * from './api/ondewo/s2t/speech-to-text_grpc_web_pb.d';
3
- export * from './api/google/protobuf/empty_pb.d';
4
- export * from './api/google/protobuf/struct_pb.d';
5
+ export * from './auth/offlineTokenProvider';
package/public-api.js CHANGED
@@ -1,4 +1,5 @@
1
- export * from './api/ondewo/s2t/speech-to-text_pb';
2
- export * from './api/ondewo/s2t/speech-to-text_grpc_web_pb';
3
- export * from './api/google/protobuf/empty_pb';
4
1
  export * from './api/google/protobuf/struct_pb';
2
+ export * from './api/google/protobuf/empty_pb';
3
+ export * from './api/ondewo/s2t/speech-to-text_grpc_web_pb';
4
+ export * from './api/ondewo/s2t/speech-to-text_pb';
5
+ export * from './auth/offlineTokenProvider';