@plasgos/oidc-client 0.0.0-stage → 0.1.0-next.2

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.
Files changed (47) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/LICENSE +15 -0
  3. package/README.md +145 -2
  4. package/dist/index.cjs +884 -0
  5. package/dist/index.cjs.map +1 -0
  6. package/dist/index.d.cts +33 -0
  7. package/dist/index.d.ts +33 -0
  8. package/dist/index.js +860 -0
  9. package/dist/index.js.map +1 -0
  10. package/dist/service.cjs +432 -0
  11. package/dist/service.cjs.map +1 -0
  12. package/dist/service.d.cts +88 -0
  13. package/dist/service.d.ts +88 -0
  14. package/dist/service.js +419 -0
  15. package/dist/service.js.map +1 -0
  16. package/dist/session.cjs +601 -0
  17. package/dist/session.cjs.map +1 -0
  18. package/dist/session.d.cts +289 -0
  19. package/dist/session.d.ts +289 -0
  20. package/dist/session.js +568 -0
  21. package/dist/session.js.map +1 -0
  22. package/dist/types-JE0OMyoi.d.cts +375 -0
  23. package/dist/types-JE0OMyoi.d.ts +375 -0
  24. package/docs/consumers.md +90 -0
  25. package/docs/contoh-hitungcuan.md +255 -0
  26. package/docs/contoh-plaslink.md +244 -0
  27. package/docs/error.md +428 -0
  28. package/docs/examples/auth-verify-readme.ts +18 -0
  29. package/docs/examples/config-error.ts +24 -0
  30. package/docs/examples/env.ts +99 -0
  31. package/docs/examples/failure-log.ts +18 -0
  32. package/docs/examples/login-client.ts +46 -0
  33. package/docs/examples/login-flow.ts +186 -0
  34. package/docs/examples/plaslink-connect.ts +48 -0
  35. package/docs/examples/readme.ts +60 -0
  36. package/docs/examples/service-client.ts +105 -0
  37. package/docs/examples/session-store.ts +53 -0
  38. package/docs/examples/webhook-express.ts +46 -0
  39. package/docs/examples/webhook-fetch.ts +60 -0
  40. package/docs/examples/webhook-nestjs.ts +59 -0
  41. package/docs/examples/webhook-testing.ts +60 -0
  42. package/docs/examples/webhook-verifier.ts +143 -0
  43. package/docs/login-web.md +618 -0
  44. package/docs/memulai.md +339 -0
  45. package/docs/server-ke-server.md +275 -0
  46. package/docs/webhook.md +625 -0
  47. package/package.json +67 -3
@@ -0,0 +1,88 @@
1
+ import { Environment, ServiceScope } from '@plasgos/auth-shared';
2
+ export { ConfigError, Environment, OidcError, OidcErrorReason, OidcUpstream, ServiceScope } from '@plasgos/auth-shared';
3
+ import { e as OidcFetch, d as OidcFailureEvent } from './types-JE0OMyoi.cjs';
4
+ export { f as OidcOperation } from './types-JE0OMyoi.cjs';
5
+
6
+ /**
7
+ * Options of `createServiceClient`. Values usually come from `process.env`; every problem is
8
+ * reported at once in one `ConfigError`, by field name and never by value.
9
+ *
10
+ * @example
11
+ * const options: ServiceClientOptions = {
12
+ * environment: "production",
13
+ * issuer: "https://accounts.plasgos.co.id",
14
+ * apiUrl: "https://api.plasgos.co.id",
15
+ * clientId: process.env.PLASGOS_SERVICE_CLIENT_ID ?? "",
16
+ * clientSecret: process.env.PLASGOS_SERVICE_CLIENT_SECRET ?? "",
17
+ * scopes: ["platform:self.read", "payments:read", "payments:write"],
18
+ * };
19
+ */
20
+ interface ServiceClientOptions {
21
+ /** `"sandbox"` or `"production"`; checked against `issuer`, `resource`, `backchannelUrl` and `apiUrl`. */
22
+ environment: Environment;
23
+ /** Bare origin of the provider. */
24
+ issuer: string;
25
+ /** Origin `/oidc/token` is called on; `http:` allowed (internal network). Default: `issuer`. */
26
+ backchannelUrl?: string | undefined;
27
+ /** Bare origin `client.fetch` calls: the API host, or the internal Plasgos server origin; `http:` allowed. */
28
+ apiUrl: string;
29
+ /** Client id of the app's service client. */
30
+ clientId: string;
31
+ /** Sent only as `client_secret_basic`, to the token endpoint. */
32
+ clientSecret: string;
33
+ /** Service scopes, at least one; a user scope is refused. */
34
+ scopes: readonly ServiceScope[];
35
+ /** Audience of the token. Default: `DEFAULT_AUDIENCES.platform`. */
36
+ resource?: string | undefined;
37
+ /** Sandbox only: `http:` for the issuer. */
38
+ allowInsecureHttp?: boolean | undefined;
39
+ /** Milliseconds, 1 to 60 000 each. Defaults: `tokenMs` 10 000 (token call), `requestMs` 10 000 (each `fetch` attempt). */
40
+ timeouts?: {
41
+ tokenMs?: number | undefined;
42
+ requestMs?: number | undefined;
43
+ } | undefined;
44
+ /** Default: the global `fetch`. */
45
+ fetch?: OidcFetch | undefined;
46
+ /** Receives one event per failure (`service_token`, `service_request`); safe to log. */
47
+ onFailure?: ((event: OidcFailureEvent) => void) | undefined;
48
+ }
49
+ /**
50
+ * What `createServiceClient` returns.
51
+ *
52
+ * @example
53
+ * const res = await plasgos.fetch("/v5/service/payments", {
54
+ * method: "POST",
55
+ * headers: { "Content-Type": "application/json" },
56
+ * body: JSON.stringify(payment),
57
+ * });
58
+ * if (!res.ok) throw new Error(`payments answered ${String(res.status)}`);
59
+ */
60
+ interface ServiceClient {
61
+ /** The `environment` the client was created with. */
62
+ readonly environment: Environment;
63
+ /** The client id the client was created with. */
64
+ readonly clientId: string;
65
+ /** A cached access token; a new one is requested 60 s before expiry. */
66
+ getToken(): Promise<string>;
67
+ /** `fetch(apiUrl + path)` with `Authorization: Bearer`; one retry on 401 invalid_token; `redirect: "manual"` unless the caller sets `redirect`. */
68
+ fetch(path: string, init?: RequestInit): Promise<Response>;
69
+ }
70
+ /**
71
+ * A server-to-server client: `client_credentials` tokens of a service client, cached, and a
72
+ * `fetch` that carries the token to the Plasgos API.
73
+ *
74
+ * @example
75
+ * const plasgos = createServiceClient({
76
+ * environment: "production",
77
+ * issuer: "https://accounts.plasgos.co.id",
78
+ * apiUrl: "https://api.plasgos.co.id",
79
+ * clientId: process.env.PLASGOS_SERVICE_CLIENT_ID ?? "",
80
+ * clientSecret: process.env.PLASGOS_SERVICE_CLIENT_SECRET ?? "",
81
+ * scopes: ["platform:self.read"],
82
+ * });
83
+ * const res = await plasgos.fetch("/v5/service/me");
84
+ */
85
+ declare function createServiceClient(options: ServiceClientOptions): ServiceClient;
86
+
87
+ export { OidcFailureEvent, OidcFetch, createServiceClient };
88
+ export type { ServiceClient, ServiceClientOptions };
@@ -0,0 +1,88 @@
1
+ import { Environment, ServiceScope } from '@plasgos/auth-shared';
2
+ export { ConfigError, Environment, OidcError, OidcErrorReason, OidcUpstream, ServiceScope } from '@plasgos/auth-shared';
3
+ import { e as OidcFetch, d as OidcFailureEvent } from './types-JE0OMyoi.js';
4
+ export { f as OidcOperation } from './types-JE0OMyoi.js';
5
+
6
+ /**
7
+ * Options of `createServiceClient`. Values usually come from `process.env`; every problem is
8
+ * reported at once in one `ConfigError`, by field name and never by value.
9
+ *
10
+ * @example
11
+ * const options: ServiceClientOptions = {
12
+ * environment: "production",
13
+ * issuer: "https://accounts.plasgos.co.id",
14
+ * apiUrl: "https://api.plasgos.co.id",
15
+ * clientId: process.env.PLASGOS_SERVICE_CLIENT_ID ?? "",
16
+ * clientSecret: process.env.PLASGOS_SERVICE_CLIENT_SECRET ?? "",
17
+ * scopes: ["platform:self.read", "payments:read", "payments:write"],
18
+ * };
19
+ */
20
+ interface ServiceClientOptions {
21
+ /** `"sandbox"` or `"production"`; checked against `issuer`, `resource`, `backchannelUrl` and `apiUrl`. */
22
+ environment: Environment;
23
+ /** Bare origin of the provider. */
24
+ issuer: string;
25
+ /** Origin `/oidc/token` is called on; `http:` allowed (internal network). Default: `issuer`. */
26
+ backchannelUrl?: string | undefined;
27
+ /** Bare origin `client.fetch` calls: the API host, or the internal Plasgos server origin; `http:` allowed. */
28
+ apiUrl: string;
29
+ /** Client id of the app's service client. */
30
+ clientId: string;
31
+ /** Sent only as `client_secret_basic`, to the token endpoint. */
32
+ clientSecret: string;
33
+ /** Service scopes, at least one; a user scope is refused. */
34
+ scopes: readonly ServiceScope[];
35
+ /** Audience of the token. Default: `DEFAULT_AUDIENCES.platform`. */
36
+ resource?: string | undefined;
37
+ /** Sandbox only: `http:` for the issuer. */
38
+ allowInsecureHttp?: boolean | undefined;
39
+ /** Milliseconds, 1 to 60 000 each. Defaults: `tokenMs` 10 000 (token call), `requestMs` 10 000 (each `fetch` attempt). */
40
+ timeouts?: {
41
+ tokenMs?: number | undefined;
42
+ requestMs?: number | undefined;
43
+ } | undefined;
44
+ /** Default: the global `fetch`. */
45
+ fetch?: OidcFetch | undefined;
46
+ /** Receives one event per failure (`service_token`, `service_request`); safe to log. */
47
+ onFailure?: ((event: OidcFailureEvent) => void) | undefined;
48
+ }
49
+ /**
50
+ * What `createServiceClient` returns.
51
+ *
52
+ * @example
53
+ * const res = await plasgos.fetch("/v5/service/payments", {
54
+ * method: "POST",
55
+ * headers: { "Content-Type": "application/json" },
56
+ * body: JSON.stringify(payment),
57
+ * });
58
+ * if (!res.ok) throw new Error(`payments answered ${String(res.status)}`);
59
+ */
60
+ interface ServiceClient {
61
+ /** The `environment` the client was created with. */
62
+ readonly environment: Environment;
63
+ /** The client id the client was created with. */
64
+ readonly clientId: string;
65
+ /** A cached access token; a new one is requested 60 s before expiry. */
66
+ getToken(): Promise<string>;
67
+ /** `fetch(apiUrl + path)` with `Authorization: Bearer`; one retry on 401 invalid_token; `redirect: "manual"` unless the caller sets `redirect`. */
68
+ fetch(path: string, init?: RequestInit): Promise<Response>;
69
+ }
70
+ /**
71
+ * A server-to-server client: `client_credentials` tokens of a service client, cached, and a
72
+ * `fetch` that carries the token to the Plasgos API.
73
+ *
74
+ * @example
75
+ * const plasgos = createServiceClient({
76
+ * environment: "production",
77
+ * issuer: "https://accounts.plasgos.co.id",
78
+ * apiUrl: "https://api.plasgos.co.id",
79
+ * clientId: process.env.PLASGOS_SERVICE_CLIENT_ID ?? "",
80
+ * clientSecret: process.env.PLASGOS_SERVICE_CLIENT_SECRET ?? "",
81
+ * scopes: ["platform:self.read"],
82
+ * });
83
+ * const res = await plasgos.fetch("/v5/service/me");
84
+ */
85
+ declare function createServiceClient(options: ServiceClientOptions): ServiceClient;
86
+
87
+ export { OidcFailureEvent, OidcFetch, createServiceClient };
88
+ export type { ServiceClient, ServiceClientOptions };
@@ -0,0 +1,419 @@
1
+ // src/service/client.ts
2
+ import {
3
+ ConfigError as ConfigError2,
4
+ DEFAULT_AUDIENCES,
5
+ OidcError as OidcError3,
6
+ PRODUCTION_ISSUER as PRODUCTION_ISSUER2,
7
+ environmentProblems as environmentProblems2,
8
+ parseAudience as parseAudience2,
9
+ parseIssuer as parseIssuer2,
10
+ serviceScopeProblems
11
+ } from "@plasgos/auth-shared";
12
+
13
+ // src/core/config.ts
14
+ import {
15
+ ConfigError,
16
+ PRODUCTION_ISSUER,
17
+ environmentProblems,
18
+ parseAudience,
19
+ parseIssuer,
20
+ userScopeProblems
21
+ } from "@plasgos/auth-shared";
22
+ var MAX_TIMEOUT_MS = 6e4;
23
+ var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
24
+ var isBlank = (value) => typeof value === "string" && value.trim() === "";
25
+ var distinctScopes = (scopes) => Object.freeze([...new Set(Array.isArray(scopes) ? scopes.filter((scope) => typeof scope === "string") : [])]);
26
+ var globalFetch = (input, init) => globalThis.fetch(input, init);
27
+ function parsed(problems, parse) {
28
+ try {
29
+ return parse();
30
+ } catch (error) {
31
+ if (!(error instanceof ConfigError)) throw error;
32
+ problems.push(...error.problems);
33
+ return void 0;
34
+ }
35
+ }
36
+ function timeoutsOf(problems, raw, defaults) {
37
+ const given = raw ?? {};
38
+ if (!isObject(given)) problems.push("timeouts must be an object");
39
+ const resolved = { ...defaults };
40
+ for (const name of Object.keys(defaults)) {
41
+ const value = isObject(given) ? given[name] : void 0;
42
+ if (value === void 0) continue;
43
+ if (typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= MAX_TIMEOUT_MS) {
44
+ resolved[name] = value;
45
+ } else {
46
+ problems.push(`timeouts.${name} must be an integer from 1 to ${String(MAX_TIMEOUT_MS)}`);
47
+ }
48
+ }
49
+ return resolved;
50
+ }
51
+
52
+ // src/core/failure.ts
53
+ var PLAIN = /^[\w.:-]{1,128}$/;
54
+ var PLAIN_PATH = /^\/[\w./~-]{0,255}$/;
55
+ var plain = (value) => value !== null && PLAIN.test(value) ? value : null;
56
+ var pathOnly = (path) => {
57
+ if (path === null) return null;
58
+ const bare = path.split(/[?#]/, 1)[0] ?? "";
59
+ return PLAIN_PATH.test(bare) ? bare : null;
60
+ };
61
+ function sanitizeEvent(event) {
62
+ return {
63
+ environment: event.environment,
64
+ operation: event.operation,
65
+ reason: event.reason,
66
+ method: plain(event.method),
67
+ path: pathOnly(event.path),
68
+ status: Number.isInteger(event.status) ? event.status : null,
69
+ requestId: plain(event.requestId),
70
+ providerError: plain(event.providerError)
71
+ };
72
+ }
73
+ var ignore = () => void 0;
74
+ function report(hook, event) {
75
+ if (hook === void 0) return;
76
+ try {
77
+ const run = hook;
78
+ const result = run(sanitizeEvent(event));
79
+ if (result instanceof Promise) result.catch(ignore);
80
+ } catch {
81
+ }
82
+ }
83
+
84
+ // src/core/token.ts
85
+ import { OIDC_PATHS, OidcError as OidcError2, basicAuthHeader } from "@plasgos/auth-shared";
86
+
87
+ // src/core/http.ts
88
+ import { OidcError } from "@plasgos/auth-shared";
89
+ var MAX_RESPONSE_BYTES = 16384;
90
+ var ignore2 = () => void 0;
91
+ var isRedirect = (res) => res.type === "opaqueredirect" || res.status >= 300 && res.status < 400;
92
+ async function send(url, init, options) {
93
+ const { method, path } = options.call;
94
+ const controller = new AbortController();
95
+ const timer = setTimeout(() => {
96
+ controller.abort();
97
+ }, options.timeoutMs);
98
+ const done = () => {
99
+ clearTimeout(timer);
100
+ };
101
+ let res;
102
+ try {
103
+ res = await options.fetch(url, { ...init, redirect: "manual", signal: controller.signal });
104
+ } catch {
105
+ done();
106
+ throw new OidcError("unavailable", { method, path, status: null, requestId: null });
107
+ }
108
+ if (isRedirect(res)) {
109
+ done();
110
+ await res.body?.cancel().catch(ignore2);
111
+ const at = upstreamOf(method, path, res);
112
+ throw new OidcError("provider_error", res.status === 0 ? { ...at, status: null } : at);
113
+ }
114
+ return { res, done, timedOut: () => controller.signal.aborted };
115
+ }
116
+ async function readCappedBody(res, maxBytes) {
117
+ const declared = Number(res.headers.get("content-length") ?? "0");
118
+ if (declared > maxBytes) {
119
+ await res.body?.cancel().catch(ignore2);
120
+ return { kind: "too_large" };
121
+ }
122
+ const chunks = [];
123
+ let size = 0;
124
+ try {
125
+ const reader = res.body?.getReader();
126
+ while (reader !== void 0) {
127
+ const chunk = await reader.read();
128
+ const value = chunk.value;
129
+ if (chunk.done || value === void 0) break;
130
+ size += value.byteLength;
131
+ if (size > maxBytes) {
132
+ await reader.cancel().catch(ignore2);
133
+ return { kind: "too_large" };
134
+ }
135
+ chunks.push(value);
136
+ }
137
+ } catch {
138
+ return { kind: "unreadable" };
139
+ }
140
+ return { kind: "bytes", bytes: Buffer.concat(chunks) };
141
+ }
142
+ async function readJson(res) {
143
+ const body = await readCappedBody(res, MAX_RESPONSE_BYTES);
144
+ if (body.kind === "too_large") return void 0;
145
+ if (body.kind === "unreadable") return null;
146
+ try {
147
+ return JSON.parse(body.bytes.toString("utf8"));
148
+ } catch (error) {
149
+ if (error instanceof SyntaxError) return null;
150
+ throw error;
151
+ }
152
+ }
153
+ function upstreamOf(method, path, res) {
154
+ return { method, path, status: res.status, requestId: plain(res.headers.get("x-request-id")) };
155
+ }
156
+ function failOnStatus(res, body, at) {
157
+ if (res.status >= 500 || res.status === 429) throw new OidcError("unavailable", at);
158
+ if (body === void 0) throw new OidcError("provider_error", at);
159
+ }
160
+ async function requestJson(url, init, options) {
161
+ const { res, done, timedOut } = await send(url, init, options);
162
+ const body = await readJson(res).finally(done);
163
+ const at = upstreamOf(options.call.method, options.call.path, res);
164
+ if (timedOut()) throw new OidcError("unavailable", at);
165
+ return { res, body, at };
166
+ }
167
+
168
+ // src/core/token.ts
169
+ var TOKEN_CALL = { method: "POST", path: OIDC_PATHS.token };
170
+ var CONFIG_ERRORS = /* @__PURE__ */ new Set([
171
+ "invalid_client",
172
+ "unauthorized_client",
173
+ "invalid_scope",
174
+ "unsupported_grant_type"
175
+ ]);
176
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
177
+ var own = (record, key) => Object.hasOwn(record, key) ? record[key] : void 0;
178
+ var HEADER_SAFE = /^[\x21-\x7e]+$/;
179
+ var isToken = (value) => typeof value === "string" && HEADER_SAFE.test(value);
180
+ function tokenSetOf(body, refreshTokenRequired) {
181
+ if (!isRecord(body)) return null;
182
+ const accessToken = own(body, "access_token");
183
+ const refreshToken = own(body, "refresh_token");
184
+ const idToken = own(body, "id_token");
185
+ const expiresIn = own(body, "expires_in");
186
+ const tokenType = own(body, "token_type");
187
+ const scope = own(body, "scope");
188
+ if (!isToken(accessToken)) return null;
189
+ if (refreshToken === void 0 && refreshTokenRequired) return null;
190
+ if (refreshToken !== void 0 && !isToken(refreshToken)) return null;
191
+ if (idToken !== void 0 && !isToken(idToken)) return null;
192
+ if (typeof expiresIn !== "number" || !Number.isSafeInteger(expiresIn) || expiresIn <= 0) return null;
193
+ if (typeof tokenType !== "string" || tokenType.toLowerCase() !== "bearer") return null;
194
+ if (scope !== void 0 && typeof scope !== "string") return null;
195
+ return {
196
+ access_token: accessToken,
197
+ ...refreshToken !== void 0 ? { refresh_token: refreshToken } : {},
198
+ ...idToken !== void 0 ? { id_token: idToken } : {},
199
+ expires_in: expiresIn,
200
+ token_type: "Bearer",
201
+ ...scope !== void 0 ? { scope } : {}
202
+ };
203
+ }
204
+ var reasonOf = (code) => {
205
+ if (code === "invalid_grant" || code === "invalid_target") return code;
206
+ return code !== null && CONFIG_ERRORS.has(code) ? "config_invalid" : "provider_error";
207
+ };
208
+ async function tokenEndpointRequest(endpoint, operation, params) {
209
+ let providerError = null;
210
+ try {
211
+ const form = new URLSearchParams({ ...params, ...endpoint.resource !== null ? { resource: endpoint.resource } : {} });
212
+ const { res, body, at } = await requestJson(
213
+ `${endpoint.origin}${TOKEN_CALL.path}`,
214
+ {
215
+ method: TOKEN_CALL.method,
216
+ headers: {
217
+ Authorization: basicAuthHeader(endpoint.clientId, endpoint.clientSecret),
218
+ "Content-Type": "application/x-www-form-urlencoded",
219
+ Accept: "application/json"
220
+ },
221
+ body: form.toString()
222
+ },
223
+ { timeoutMs: endpoint.timeoutMs, fetch: endpoint.fetch, call: TOKEN_CALL }
224
+ );
225
+ if (!res.ok && isRecord(body)) {
226
+ const code = own(body, "error");
227
+ if (typeof code === "string") providerError = code;
228
+ }
229
+ failOnStatus(res, body, at);
230
+ if (!res.ok) throw new OidcError2(reasonOf(providerError), at);
231
+ const tokens = tokenSetOf(body, endpoint.refreshTokenRequired);
232
+ if (tokens === null) throw new OidcError2("provider_error", at);
233
+ return tokens;
234
+ } catch (error) {
235
+ if (error instanceof OidcError2) {
236
+ report(endpoint.onFailure, {
237
+ environment: endpoint.environment,
238
+ operation,
239
+ reason: error.reason,
240
+ method: TOKEN_CALL.method,
241
+ path: TOKEN_CALL.path,
242
+ status: error.upstream?.status ?? null,
243
+ requestId: error.upstream?.requestId ?? null,
244
+ providerError
245
+ });
246
+ }
247
+ throw error;
248
+ }
249
+ }
250
+
251
+ // src/service/client.ts
252
+ var DEFAULT_TOKEN_MS = 1e4;
253
+ var DEFAULT_REQUEST_MS = 1e4;
254
+ var EXPIRY_MARGIN_SECONDS = 60;
255
+ var SINGLE_SLASH_PATH = /^\/(?![/\\])/;
256
+ var PATH_PROBLEM = "serviceClient.fetch: path must start with a single /";
257
+ var ignore3 = () => void 0;
258
+ var isInvalidToken = (res) => {
259
+ if (res.status !== 401) return false;
260
+ const challenge = res.headers.get("www-authenticate") ?? "";
261
+ return /^\s*Bearer\b/i.test(challenge) && /\berror\s*=\s*"?invalid_token"?/i.test(challenge);
262
+ };
263
+ function resolveServiceConfig(raw) {
264
+ if (!isObject(raw)) throw new ConfigError2(["options must be an object"]);
265
+ const problems = [];
266
+ const text = (field) => {
267
+ const value = raw[field];
268
+ if (value === void 0 || typeof value === "string") return value;
269
+ problems.push(`${field} must be a string`);
270
+ return void 0;
271
+ };
272
+ const given = (field) => raw[field] !== void 0;
273
+ const present = (field) => given(field) && !isBlank(raw[field]);
274
+ const required = (field) => {
275
+ const value = text(field);
276
+ const blank = isBlank(value);
277
+ if (blank || !given(field)) problems.push(`${field} is required`);
278
+ return blank ? void 0 : value;
279
+ };
280
+ const origin = (field, allowInsecureHttp2, optional) => {
281
+ if (optional && !present(field)) return void 0;
282
+ const value = text(field);
283
+ if (value === void 0 && given(field)) return void 0;
284
+ return parsed(problems, () => parseIssuer2(value, { field, allowInsecureHttp: allowInsecureHttp2 }));
285
+ };
286
+ const allowInsecureHttp = raw["allowInsecureHttp"] === true;
287
+ const issuer = origin("issuer", allowInsecureHttp, false);
288
+ const backchannelUrl = origin("backchannelUrl", true, true);
289
+ const apiUrl = origin("apiUrl", true, false);
290
+ const clientId = required("clientId");
291
+ const clientSecret = required("clientSecret");
292
+ const scopesRaw = raw["scopes"];
293
+ problems.push(...serviceScopeProblems(scopesRaw));
294
+ const resourceRaw = present("resource") ? text("resource") : void 0;
295
+ const resource = present("resource") ? resourceRaw === void 0 ? void 0 : parsed(problems, () => parseAudience2(resourceRaw, { field: "resource", allowInsecureHttp })) : DEFAULT_AUDIENCES.platform;
296
+ if (raw["allowInsecureHttp"] !== void 0 && typeof raw["allowInsecureHttp"] !== "boolean") {
297
+ problems.push("allowInsecureHttp must be a boolean");
298
+ }
299
+ const timeouts = timeoutsOf(problems, raw["timeouts"], { tokenMs: DEFAULT_TOKEN_MS, requestMs: DEFAULT_REQUEST_MS });
300
+ const { fetch, onFailure } = raw;
301
+ if (fetch !== void 0 && typeof fetch !== "function") problems.push("fetch must be a function");
302
+ if (onFailure !== void 0 && typeof onFailure !== "function") problems.push("onFailure must be a function");
303
+ const environment = raw["environment"];
304
+ const guard = environmentProblems2({
305
+ environment,
306
+ issuer: issuer ?? (environment === "production" ? PRODUCTION_ISSUER2 : ""),
307
+ allowInsecureHttp: raw["allowInsecureHttp"],
308
+ ...resource !== void 0 ? { audiences: [resource] } : {},
309
+ ...backchannelUrl !== void 0 ? { backchannelUrl } : {},
310
+ ...apiUrl !== void 0 ? { apiUrl } : {}
311
+ });
312
+ if (guard.length > 0 || problems.length > 0) throw new ConfigError2([...guard, ...problems]);
313
+ return Object.freeze({
314
+ environment,
315
+ issuer,
316
+ backchannelUrl: backchannelUrl ?? null,
317
+ apiUrl,
318
+ clientId,
319
+ clientSecret,
320
+ scopes: distinctScopes(scopesRaw),
321
+ resource,
322
+ timeouts: Object.freeze(timeouts),
323
+ fetch: fetch ?? globalFetch,
324
+ onFailure
325
+ });
326
+ }
327
+ function createServiceClient(options) {
328
+ const config = resolveServiceConfig(options);
329
+ const endpoint = {
330
+ environment: config.environment,
331
+ origin: config.backchannelUrl ?? config.issuer,
332
+ clientId: config.clientId,
333
+ clientSecret: config.clientSecret,
334
+ resource: config.resource,
335
+ timeoutMs: config.timeouts.tokenMs,
336
+ fetch: config.fetch,
337
+ onFailure: config.onFailure,
338
+ refreshTokenRequired: false
339
+ };
340
+ const scope = config.scopes.join(" ");
341
+ let cached = null;
342
+ let pending = null;
343
+ const mint = async () => {
344
+ const obtainedAt = Date.now();
345
+ const tokens = await tokenEndpointRequest(endpoint, "service_token", { grant_type: "client_credentials", scope });
346
+ const margin = Math.min(EXPIRY_MARGIN_SECONDS, Math.floor(tokens.expires_in / 2));
347
+ cached = { token: tokens.access_token, freshUntil: obtainedAt + (tokens.expires_in - margin) * 1e3 };
348
+ return tokens.access_token;
349
+ };
350
+ const getToken = () => {
351
+ if (cached !== null && Date.now() < cached.freshUntil) return Promise.resolve(cached.token);
352
+ pending ??= mint().finally(() => {
353
+ pending = null;
354
+ });
355
+ return pending;
356
+ };
357
+ const attempt = async (url, init, token, call) => {
358
+ const controller = new AbortController();
359
+ const timer = setTimeout(() => {
360
+ controller.abort();
361
+ }, config.timeouts.requestMs);
362
+ timer.unref();
363
+ const callerSignal = init.signal ?? null;
364
+ try {
365
+ const headers = new Headers(init.headers);
366
+ headers.set("Authorization", `Bearer ${token}`);
367
+ return await config.fetch(url, {
368
+ ...init,
369
+ headers,
370
+ // The bearer token would follow a redirect to another host.
371
+ redirect: init.redirect ?? "manual",
372
+ signal: callerSignal === null ? controller.signal : AbortSignal.any([callerSignal, controller.signal])
373
+ });
374
+ } catch {
375
+ clearTimeout(timer);
376
+ callerSignal?.throwIfAborted();
377
+ report(config.onFailure, {
378
+ environment: config.environment,
379
+ operation: "service_request",
380
+ reason: "unavailable",
381
+ method: call.method,
382
+ path: call.path,
383
+ status: null,
384
+ requestId: null,
385
+ providerError: null
386
+ });
387
+ throw new OidcError3("unavailable", { method: call.method, path: call.path, status: null, requestId: null });
388
+ }
389
+ };
390
+ const fetch = async (path, init = {}) => {
391
+ if (typeof path !== "string" || !SINGLE_SLASH_PATH.test(path)) throw new TypeError(PATH_PROBLEM);
392
+ const given = init;
393
+ if (!isObject(given)) throw new TypeError("serviceClient.fetch: init must be an object");
394
+ const url = `${config.apiUrl}${path}`;
395
+ if (!URL.canParse(url) || new URL(url).origin !== config.apiUrl) throw new TypeError(PATH_PROBLEM);
396
+ init.signal?.throwIfAborted();
397
+ const call = {
398
+ method: typeof init.method === "string" ? init.method.toUpperCase() : "GET",
399
+ path: path.split(/[?#]/, 1)[0] ?? ""
400
+ };
401
+ const token = await getToken();
402
+ const res = await attempt(url, init, token, call);
403
+ if (!isInvalidToken(res)) return res;
404
+ if (cached?.token === token) cached = null;
405
+ if (init.body instanceof ReadableStream) return res;
406
+ await res.body?.cancel().catch(ignore3);
407
+ return attempt(url, init, await getToken(), call);
408
+ };
409
+ return Object.freeze({ environment: config.environment, clientId: config.clientId, getToken, fetch });
410
+ }
411
+
412
+ // src/service/index.ts
413
+ import { ConfigError as ConfigError3, OidcError as OidcError4 } from "@plasgos/auth-shared";
414
+ export {
415
+ ConfigError3 as ConfigError,
416
+ OidcError4 as OidcError,
417
+ createServiceClient
418
+ };
419
+ //# sourceMappingURL=service.js.map