@onkernel/sdk 0.149.0 → 0.151.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.
Files changed (191) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/client.d.mts +29 -4
  3. package/client.d.mts.map +1 -1
  4. package/client.d.ts +29 -4
  5. package/client.d.ts.map +1 -1
  6. package/client.js +32 -3
  7. package/client.js.map +1 -1
  8. package/client.mjs +32 -3
  9. package/client.mjs.map +1 -1
  10. package/lib/credentials/client-auth.d.mts +88 -0
  11. package/lib/credentials/client-auth.d.mts.map +1 -0
  12. package/lib/credentials/client-auth.d.ts +88 -0
  13. package/lib/credentials/client-auth.d.ts.map +1 -0
  14. package/lib/credentials/client-auth.js +166 -0
  15. package/lib/credentials/client-auth.js.map +1 -0
  16. package/lib/credentials/client-auth.mjs +162 -0
  17. package/lib/credentials/client-auth.mjs.map +1 -0
  18. package/lib/credentials/credential-chain.d.mts +20 -0
  19. package/lib/credentials/credential-chain.d.mts.map +1 -0
  20. package/lib/credentials/credential-chain.d.ts +20 -0
  21. package/lib/credentials/credential-chain.d.ts.map +1 -0
  22. package/lib/credentials/credential-chain.js +81 -0
  23. package/lib/credentials/credential-chain.js.map +1 -0
  24. package/lib/credentials/credential-chain.mjs +77 -0
  25. package/lib/credentials/credential-chain.mjs.map +1 -0
  26. package/lib/credentials/identity-token.d.mts +59 -0
  27. package/lib/credentials/identity-token.d.mts.map +1 -0
  28. package/lib/credentials/identity-token.d.ts +59 -0
  29. package/lib/credentials/identity-token.d.ts.map +1 -0
  30. package/lib/credentials/identity-token.js +243 -0
  31. package/lib/credentials/identity-token.js.map +1 -0
  32. package/lib/credentials/identity-token.mjs +202 -0
  33. package/lib/credentials/identity-token.mjs.map +1 -0
  34. package/lib/credentials/oidc-federation.d.mts +65 -0
  35. package/lib/credentials/oidc-federation.d.mts.map +1 -0
  36. package/lib/credentials/oidc-federation.d.ts +65 -0
  37. package/lib/credentials/oidc-federation.d.ts.map +1 -0
  38. package/lib/credentials/oidc-federation.js +200 -0
  39. package/lib/credentials/oidc-federation.js.map +1 -0
  40. package/lib/credentials/oidc-federation.mjs +196 -0
  41. package/lib/credentials/oidc-federation.mjs.map +1 -0
  42. package/lib/credentials/token-cache.d.mts +64 -0
  43. package/lib/credentials/token-cache.d.mts.map +1 -0
  44. package/lib/credentials/token-cache.d.ts +64 -0
  45. package/lib/credentials/token-cache.d.ts.map +1 -0
  46. package/lib/credentials/token-cache.js +147 -0
  47. package/lib/credentials/token-cache.js.map +1 -0
  48. package/lib/credentials/token-cache.mjs +143 -0
  49. package/lib/credentials/token-cache.mjs.map +1 -0
  50. package/lib/credentials/types.d.mts +126 -0
  51. package/lib/credentials/types.d.mts.map +1 -0
  52. package/lib/credentials/types.d.ts +126 -0
  53. package/lib/credentials/types.d.ts.map +1 -0
  54. package/lib/credentials/types.js +182 -0
  55. package/lib/credentials/types.js.map +1 -0
  56. package/lib/credentials/types.mjs +169 -0
  57. package/lib/credentials/types.mjs.map +1 -0
  58. package/lib/credentials.d.mts +6 -0
  59. package/lib/credentials.d.mts.map +1 -0
  60. package/lib/credentials.d.ts +6 -0
  61. package/lib/credentials.d.ts.map +1 -0
  62. package/lib/credentials.js +19 -0
  63. package/lib/credentials.js.map +1 -0
  64. package/lib/credentials.mjs +6 -0
  65. package/lib/credentials.mjs.map +1 -0
  66. package/package.json +9 -1
  67. package/resources/api-keys.d.mts +192 -16
  68. package/resources/api-keys.d.mts.map +1 -1
  69. package/resources/api-keys.d.ts +192 -16
  70. package/resources/api-keys.d.ts.map +1 -1
  71. package/resources/api-keys.js +19 -7
  72. package/resources/api-keys.js.map +1 -1
  73. package/resources/api-keys.mjs +19 -7
  74. package/resources/api-keys.mjs.map +1 -1
  75. package/resources/auth/auth.d.mts +2 -2
  76. package/resources/auth/auth.d.mts.map +1 -1
  77. package/resources/auth/auth.d.ts +2 -2
  78. package/resources/auth/auth.d.ts.map +1 -1
  79. package/resources/auth/auth.js.map +1 -1
  80. package/resources/auth/auth.mjs.map +1 -1
  81. package/resources/auth/connections.d.mts +16 -2
  82. package/resources/auth/connections.d.mts.map +1 -1
  83. package/resources/auth/connections.d.ts +16 -2
  84. package/resources/auth/connections.d.ts.map +1 -1
  85. package/resources/auth/context.d.mts +69 -3
  86. package/resources/auth/context.d.mts.map +1 -1
  87. package/resources/auth/context.d.ts +69 -3
  88. package/resources/auth/context.d.ts.map +1 -1
  89. package/resources/auth/index.d.mts +1 -1
  90. package/resources/auth/index.d.mts.map +1 -1
  91. package/resources/auth/index.d.ts +1 -1
  92. package/resources/auth/index.d.ts.map +1 -1
  93. package/resources/auth/index.js.map +1 -1
  94. package/resources/auth/index.mjs.map +1 -1
  95. package/resources/browser-pools.d.mts +41 -6
  96. package/resources/browser-pools.d.mts.map +1 -1
  97. package/resources/browser-pools.d.ts +41 -6
  98. package/resources/browser-pools.d.ts.map +1 -1
  99. package/resources/browsers/browsers.d.mts +105 -45
  100. package/resources/browsers/browsers.d.mts.map +1 -1
  101. package/resources/browsers/browsers.d.ts +105 -45
  102. package/resources/browsers/browsers.d.ts.map +1 -1
  103. package/resources/browsers/browsers.js.map +1 -1
  104. package/resources/browsers/browsers.mjs.map +1 -1
  105. package/resources/browsers/index.d.mts +1 -1
  106. package/resources/browsers/index.d.mts.map +1 -1
  107. package/resources/browsers/index.d.ts +1 -1
  108. package/resources/browsers/index.d.ts.map +1 -1
  109. package/resources/browsers/index.js.map +1 -1
  110. package/resources/browsers/index.mjs.map +1 -1
  111. package/resources/browsers/telemetry.d.mts +4 -4
  112. package/resources/browsers/telemetry.d.mts.map +1 -1
  113. package/resources/browsers/telemetry.d.ts +4 -4
  114. package/resources/browsers/telemetry.d.ts.map +1 -1
  115. package/resources/index.d.mts +6 -2
  116. package/resources/index.d.mts.map +1 -1
  117. package/resources/index.d.ts +6 -2
  118. package/resources/index.d.ts.map +1 -1
  119. package/resources/index.js +9 -1
  120. package/resources/index.js.map +1 -1
  121. package/resources/index.mjs +4 -0
  122. package/resources/index.mjs.map +1 -1
  123. package/resources/invocations.d.mts +13 -1
  124. package/resources/invocations.d.mts.map +1 -1
  125. package/resources/invocations.d.ts +13 -1
  126. package/resources/invocations.d.ts.map +1 -1
  127. package/resources/service-accounts.d.mts +73 -0
  128. package/resources/service-accounts.d.mts.map +1 -0
  129. package/resources/service-accounts.d.ts +73 -0
  130. package/resources/service-accounts.d.ts.map +1 -0
  131. package/resources/service-accounts.js +50 -0
  132. package/resources/service-accounts.js.map +1 -0
  133. package/resources/service-accounts.mjs +46 -0
  134. package/resources/service-accounts.mjs.map +1 -0
  135. package/resources/vaults/items.d.mts +68 -2
  136. package/resources/vaults/items.d.mts.map +1 -1
  137. package/resources/vaults/items.d.ts +68 -2
  138. package/resources/vaults/items.d.ts.map +1 -1
  139. package/resources/workload-identity-authentication-events.d.mts +36 -0
  140. package/resources/workload-identity-authentication-events.d.mts.map +1 -0
  141. package/resources/workload-identity-authentication-events.d.ts +36 -0
  142. package/resources/workload-identity-authentication-events.d.ts.map +1 -0
  143. package/resources/workload-identity-authentication-events.js +16 -0
  144. package/resources/workload-identity-authentication-events.js.map +1 -0
  145. package/resources/workload-identity-authentication-events.mjs +12 -0
  146. package/resources/workload-identity-authentication-events.mjs.map +1 -0
  147. package/resources/workload-identity-federation-rules.d.mts +194 -0
  148. package/resources/workload-identity-federation-rules.d.mts.map +1 -0
  149. package/resources/workload-identity-federation-rules.d.ts +194 -0
  150. package/resources/workload-identity-federation-rules.d.ts.map +1 -0
  151. package/resources/workload-identity-federation-rules.js +47 -0
  152. package/resources/workload-identity-federation-rules.js.map +1 -0
  153. package/resources/workload-identity-federation-rules.mjs +43 -0
  154. package/resources/workload-identity-federation-rules.mjs.map +1 -0
  155. package/resources/workload-identity-issuers.d.mts +169 -0
  156. package/resources/workload-identity-issuers.d.mts.map +1 -0
  157. package/resources/workload-identity-issuers.d.ts +169 -0
  158. package/resources/workload-identity-issuers.d.ts.map +1 -0
  159. package/resources/workload-identity-issuers.js +54 -0
  160. package/resources/workload-identity-issuers.js.map +1 -0
  161. package/resources/workload-identity-issuers.mjs +50 -0
  162. package/resources/workload-identity-issuers.mjs.map +1 -0
  163. package/src/client.ts +134 -1
  164. package/src/lib/credentials/client-auth.ts +194 -0
  165. package/src/lib/credentials/credential-chain.ts +95 -0
  166. package/src/lib/credentials/identity-token.ts +284 -0
  167. package/src/lib/credentials/oidc-federation.ts +304 -0
  168. package/src/lib/credentials/token-cache.ts +172 -0
  169. package/src/lib/credentials/types.ts +267 -0
  170. package/src/lib/credentials.ts +30 -0
  171. package/src/resources/api-keys.ts +217 -15
  172. package/src/resources/auth/auth.ts +6 -2
  173. package/src/resources/auth/connections.ts +17 -2
  174. package/src/resources/auth/context.ts +81 -3
  175. package/src/resources/auth/index.ts +1 -1
  176. package/src/resources/browser-pools.ts +46 -6
  177. package/src/resources/browsers/browsers.ts +115 -44
  178. package/src/resources/browsers/index.ts +1 -0
  179. package/src/resources/browsers/telemetry.ts +4 -3
  180. package/src/resources/index.ts +42 -0
  181. package/src/resources/invocations.ts +15 -1
  182. package/src/resources/service-accounts.ts +128 -0
  183. package/src/resources/vaults/items.ts +80 -2
  184. package/src/resources/workload-identity-authentication-events.ts +72 -0
  185. package/src/resources/workload-identity-federation-rules.ts +314 -0
  186. package/src/resources/workload-identity-issuers.ts +273 -0
  187. package/src/version.ts +1 -1
  188. package/version.d.mts +1 -1
  189. package/version.d.ts +1 -1
  190. package/version.js +1 -1
  191. package/version.mjs +1 -1
@@ -0,0 +1,65 @@
1
+ import type { Fetch } from "../../internal/builtin-types.js";
2
+ import type { AccessTokenProviderOptions, FederationAccessToken, FederationTokenDetails, IdentityTokenProvider } from "./types.js";
3
+ type ExchangeOptions = {
4
+ /**
5
+ * The host that exchanges identity tokens. Defaults to
6
+ * `KERNEL_AUTH_BASE_URL`, else `https://auth.onkernel.com` when the API
7
+ * base URL is the production default. A custom API base URL needs it set.
8
+ */
9
+ authBaseURL?: string | undefined;
10
+ /**
11
+ * The API the access token is for. Defaults to the origin of the API base
12
+ * URL, for example `https://api.onkernel.com`. The token endpoint compares
13
+ * it exactly, so it must not end in a slash.
14
+ */
15
+ resource?: string | undefined;
16
+ /** Defaults to the `fetch` of the client using the credentials, else the global `fetch`. */
17
+ fetch?: Fetch | undefined;
18
+ /**
19
+ * How long one token request may take, in milliseconds.
20
+ *
21
+ * @default 30000
22
+ */
23
+ timeout?: number | undefined;
24
+ };
25
+ export type OIDCFederationConfig = ExchangeOptions & {
26
+ /**
27
+ * Called once per exchange. It must return a fresh token every time: most
28
+ * providers' tokens can be exchanged only once.
29
+ */
30
+ identityTokenProvider: IdentityTokenProvider;
31
+ /** The `wifr_...` ID of the federation rule to authenticate against. */
32
+ federationRuleId: string;
33
+ };
34
+ export type FederationAssertionExchangeParams = ExchangeOptions & {
35
+ /** The identity provider's token. It is sent as given and never reused. */
36
+ assertion: string;
37
+ /** The `wifr_...` ID of the federation rule to authenticate against. */
38
+ federationRuleId: string;
39
+ };
40
+ export type FederationExchangeResult = {
41
+ accessToken: string;
42
+ } & FederationTokenDetails;
43
+ /**
44
+ * Exchanges a token from the workload's identity provider for a short-lived
45
+ * Kernel access token (the RFC 7523 jwt-bearer grant).
46
+ *
47
+ * Every call asks `identityTokenProvider` for a fresh token and exchanges
48
+ * it; nothing is cached and nothing is retried. Pass the result as the
49
+ * client's `credentials` option, which wraps it in a {@link TokenCache}.
50
+ *
51
+ * The token endpoint returns no refresh token: when the access token is
52
+ * about to expire, a new identity token is exchanged.
53
+ */
54
+ export declare function oidcFederationProvider(config: OIDCFederationConfig): (opts?: AccessTokenProviderOptions) => Promise<FederationAccessToken>;
55
+ /**
56
+ * Exchanges one identity provider token for a Kernel access token, for
57
+ * callers that want to manage the access token themselves. It needs no
58
+ * Kernel credential.
59
+ *
60
+ * The assertion is spent by the call: to get another access token, obtain a
61
+ * fresh assertion from the identity provider first.
62
+ */
63
+ export declare function exchangeFederationAssertion(params: FederationAssertionExchangeParams): Promise<FederationExchangeResult>;
64
+ export {};
65
+ //# sourceMappingURL=oidc-federation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oidc-federation.d.ts","sourceRoot":"","sources":["../../src/lib/credentials/oidc-federation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,wCAAqC;AAI1D,OAAO,KAAK,EACV,0BAA0B,EAC1B,qBAAqB,EAErB,sBAAsB,EACtB,qBAAqB,EACtB,mBAAgB;AAiBjB,KAAK,eAAe,GAAG;IACrB;;;;OAIG;IACH,WAAW,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACjC;;;;OAIG;IACH,QAAQ,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9B,4FAA4F;IAC5F,KAAK,CAAC,EAAE,KAAK,GAAG,SAAS,CAAC;IAC1B;;;;OAIG;IACH,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAC9B,CAAC;AAEF,MAAM,MAAM,oBAAoB,GAAG,eAAe,GAAG;IACnD;;;OAGG;IACH,qBAAqB,EAAE,qBAAqB,CAAC;IAC7C,wEAAwE;IACxE,gBAAgB,EAAE,MAAM,CAAC;CAC1B,CAAC;AAEF,MAAM,MAAM,iCAAiC,GAAG,eAAe,GAAG;IAChE,2EAA2E;IAC3E,SAAS,EAAE,MAAM,CAAC;IAClB,wEAAwE;IACxE,gBAAgB,EAAE,MAAM,CAAC;CAC1B,CAAC;AAEF,MAAM,MAAM,wBAAwB,GAAG;IAAE,WAAW,EAAE,MAAM,CAAA;CAAE,GAAG,sBAAsB,CAAC;AAExF;;;;;;;;;;GAUG;AACH,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,oBAAoB,GAC3B,CAAC,IAAI,CAAC,EAAE,0BAA0B,KAAK,OAAO,CAAC,qBAAqB,CAAC,CAyBvE;AAED;;;;;;;GAOG;AACH,wBAAsB,2BAA2B,CAC/C,MAAM,EAAE,iCAAiC,GACxC,OAAO,CAAC,wBAAwB,CAAC,CAgBnC"}
@@ -0,0 +1,200 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.oidcFederationProvider = oidcFederationProvider;
4
+ exports.exchangeFederationAssertion = exchangeFederationAssertion;
5
+ const shims_1 = require("../../internal/shims.js");
6
+ const version_1 = require("../../version.js");
7
+ const identity_token_1 = require("./identity-token.js");
8
+ const types_1 = require("./types.js");
9
+ /**
10
+ * Exchanges a token from the workload's identity provider for a short-lived
11
+ * Kernel access token (the RFC 7523 jwt-bearer grant).
12
+ *
13
+ * Every call asks `identityTokenProvider` for a fresh token and exchanges
14
+ * it; nothing is cached and nothing is retried. Pass the result as the
15
+ * client's `credentials` option, which wraps it in a {@link TokenCache}.
16
+ *
17
+ * The token endpoint returns no refresh token: when the access token is
18
+ * about to expire, a new identity token is exchanged.
19
+ */
20
+ function oidcFederationProvider(config) {
21
+ if (!config.federationRuleId) {
22
+ throw new types_1.WorkloadIdentityError('federationRuleId is required');
23
+ }
24
+ return async (opts) => {
25
+ const apiBaseURL = opts?.client?.baseURL;
26
+ const authBaseURL = (0, types_1.resolveAuthBaseURL)(config.authBaseURL, apiBaseURL);
27
+ (0, types_1.requireSecureTokenEndpoint)(authBaseURL);
28
+ const resource = (0, types_1.resolveResource)(config.resource, apiBaseURL);
29
+ const fetch = config.fetch ?? opts?.client?.fetch ?? (0, shims_1.getDefaultFetch)();
30
+ const assertion = await config.identityTokenProvider({ audience: authBaseURL, fetch });
31
+ const { accessToken, ...details } = await exchange({
32
+ assertion,
33
+ replayHint: (0, identity_token_1.replayHintFor)(config.identityTokenProvider),
34
+ federationRuleId: config.federationRuleId,
35
+ authBaseURL,
36
+ resource,
37
+ fetch,
38
+ userAgent: `Kernel/JS ${version_1.VERSION} oidcFederationProvider`,
39
+ timeout: config.timeout ?? types_1.DEFAULT_CREDENTIALS_TIMEOUT_IN_MS,
40
+ });
41
+ return { token: accessToken, ...details };
42
+ };
43
+ }
44
+ /**
45
+ * Exchanges one identity provider token for a Kernel access token, for
46
+ * callers that want to manage the access token themselves. It needs no
47
+ * Kernel credential.
48
+ *
49
+ * The assertion is spent by the call: to get another access token, obtain a
50
+ * fresh assertion from the identity provider first.
51
+ */
52
+ async function exchangeFederationAssertion(params) {
53
+ if (!params.federationRuleId) {
54
+ throw new types_1.WorkloadIdentityError('federationRuleId is required');
55
+ }
56
+ const authBaseURL = (0, types_1.resolveAuthBaseURL)(params.authBaseURL);
57
+ (0, types_1.requireSecureTokenEndpoint)(authBaseURL);
58
+ return exchange({
59
+ assertion: params.assertion,
60
+ replayHint: 'Every exchange needs a fresh provider token; this assertion was already exchanged.',
61
+ federationRuleId: params.federationRuleId,
62
+ authBaseURL,
63
+ resource: (0, types_1.resolveResource)(params.resource),
64
+ fetch: params.fetch ?? (0, shims_1.getDefaultFetch)(),
65
+ userAgent: `Kernel/JS ${version_1.VERSION} exchangeFederationAssertion`,
66
+ timeout: params.timeout ?? types_1.DEFAULT_CREDENTIALS_TIMEOUT_IN_MS,
67
+ });
68
+ }
69
+ async function exchange(request) {
70
+ const { assertion } = request;
71
+ if (typeof assertion !== 'string' || !assertion) {
72
+ throw new types_1.WorkloadIdentityError('Identity token is empty');
73
+ }
74
+ // The token endpoint rejects larger assertions. Failing here names the
75
+ // problem, which is usually a path or certificate passed as the token.
76
+ const assertionBytes = new TextEncoder().encode(assertion).length;
77
+ if (assertionBytes > types_1.MAX_ASSERTION_BYTES) {
78
+ throw new types_1.WorkloadIdentityError(`Identity token is ${Math.ceil(assertionBytes / 1024)} KiB, which exceeds the 16 KiB limit`);
79
+ }
80
+ // The token endpoint rejects any parameter other than these four, and any
81
+ // Authorization header.
82
+ const body = new URLSearchParams({
83
+ grant_type: types_1.GRANT_TYPE_JWT_BEARER,
84
+ assertion,
85
+ federation_rule_id: request.federationRuleId,
86
+ resource: request.resource,
87
+ }).toString();
88
+ const url = `${request.authBaseURL}${types_1.TOKEN_ENDPOINT}`;
89
+ const startedAt = (0, types_1.nowAsSeconds)();
90
+ return (0, types_1.withTimeout)(request.timeout, async (signal) => {
91
+ let response;
92
+ try {
93
+ response = await request.fetch(url, {
94
+ method: 'POST',
95
+ redirect: 'manual',
96
+ headers: {
97
+ Accept: 'application/json',
98
+ 'Content-Type': 'application/x-www-form-urlencoded',
99
+ 'User-Agent': request.userAgent,
100
+ },
101
+ body,
102
+ signal,
103
+ });
104
+ }
105
+ catch (err) {
106
+ const reason = signal.aborted ? `timed out after ${request.timeout}ms` : (0, types_1.describeFailure)(err, [assertion]);
107
+ throw new types_1.WorkloadIdentityError(`Failed to reach token endpoint ${url}: ${reason}`);
108
+ }
109
+ const requestId = response.headers.get('x-request-id') ?? response.headers.get('request-id');
110
+ let text;
111
+ try {
112
+ text = await (0, types_1.readLimitedText)(response);
113
+ }
114
+ catch (err) {
115
+ throw new types_1.WorkloadIdentityError(`Failed to read the response from token endpoint ${url}: ${(0, types_1.describeFailure)(err, [assertion])}`, { statusCode: response.status, requestId });
116
+ }
117
+ if (!response.ok) {
118
+ throw exchangeError(response.status, text, requestId, request);
119
+ }
120
+ return parseTokenResponse(response.status, text, requestId, startedAt);
121
+ });
122
+ }
123
+ function exchangeError(status, text, requestId, { assertion, replayHint, resource }) {
124
+ let parsed;
125
+ try {
126
+ parsed = JSON.parse(text);
127
+ }
128
+ catch {
129
+ parsed = undefined;
130
+ }
131
+ const body = (0, types_1.redactSensitive)(parsed, [assertion]);
132
+ const errorCode = body?.['error'] ?? null;
133
+ const errorDescription = body?.['error_description'] ?? null;
134
+ let hint = '';
135
+ if (errorDescription && /already used/i.test(errorDescription)) {
136
+ hint = replayHint;
137
+ }
138
+ else if (errorCode === 'invalid_target') {
139
+ hint = `The token endpoint does not accept the resource "${resource}". Set the resource option to the Kernel API origin, with no trailing slash.`;
140
+ }
141
+ let detail = errorCode ?
142
+ `${errorCode}${errorDescription ? `: ${errorDescription}` : ''}`
143
+ : 'the response is not an OAuth error';
144
+ if (hint)
145
+ detail = `${detail.replace(/\.$/, '')}. ${hint}`;
146
+ return new types_1.WorkloadIdentityError(`Token exchange failed with status ${status}${requestId ? ` (request ID ${requestId})` : ''}: ${detail}`, { statusCode: status, errorCode, errorDescription, requestId, body });
147
+ }
148
+ function parseTokenResponse(status, text, requestId, startedAt) {
149
+ let data;
150
+ try {
151
+ data = JSON.parse(text);
152
+ }
153
+ catch {
154
+ data = undefined;
155
+ }
156
+ // A success body holds the access token, so none of it goes into an error.
157
+ const invalid = (problem) => new types_1.WorkloadIdentityError(`Token endpoint returned an unusable response (status ${status}): ${problem}`, {
158
+ statusCode: status,
159
+ requestId,
160
+ });
161
+ if (typeof data !== 'object' || data === null || Array.isArray(data)) {
162
+ throw invalid('the body is not a JSON object');
163
+ }
164
+ const fields = data;
165
+ const accessToken = fields['access_token'];
166
+ if (typeof accessToken !== 'string' || !accessToken) {
167
+ throw invalid('access_token is missing');
168
+ }
169
+ const tokenType = fields['token_type'];
170
+ if (tokenType !== undefined && (typeof tokenType !== 'string' || tokenType.toLowerCase() !== 'bearer')) {
171
+ throw invalid('token_type is not Bearer');
172
+ }
173
+ const expiresIn = fields['expires_in'];
174
+ if (typeof expiresIn !== 'number' || !Number.isFinite(expiresIn) || expiresIn <= 0) {
175
+ throw invalid('expires_in is missing or not a positive number');
176
+ }
177
+ const stringOrNull = (value) => (typeof value === 'string' ? value : null);
178
+ const rawPrincipal = fields['principal'];
179
+ let principal = null;
180
+ if (typeof rawPrincipal === 'object' &&
181
+ rawPrincipal !== null &&
182
+ typeof rawPrincipal['type'] === 'string' &&
183
+ typeof rawPrincipal['id'] === 'string') {
184
+ principal = { type: rawPrincipal['type'], id: rawPrincipal['id'] };
185
+ }
186
+ return {
187
+ accessToken,
188
+ // Counted from before the request was sent, so the token is never
189
+ // treated as valid for longer than the server allows.
190
+ expiresAt: startedAt + expiresIn,
191
+ expiresIn,
192
+ scope: stringOrNull(fields['scope']),
193
+ orgId: stringOrNull(fields['org_id']),
194
+ accessScope: stringOrNull(fields['access_scope']),
195
+ projectId: stringOrNull(fields['project_id']),
196
+ principal,
197
+ federationRuleId: stringOrNull(fields['federation_rule_id']),
198
+ };
199
+ }
200
+ //# sourceMappingURL=oidc-federation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oidc-federation.js","sourceRoot":"","sources":["../../src/lib/credentials/oidc-federation.ts"],"names":[],"mappings":";;AAgFA,wDA2BC;AAUD,kEAkBC;AAtID,mDAAuD;AACvD,8CAAwC;AACxC,wDAAiD;AAQjD,sCAciB;AA4CjB;;;;;;;;;;GAUG;AACH,SAAgB,sBAAsB,CACpC,MAA4B;IAE5B,IAAI,CAAC,MAAM,CAAC,gBAAgB,EAAE,CAAC;QAC7B,MAAM,IAAI,6BAAqB,CAAC,8BAA8B,CAAC,CAAC;IAClE,CAAC;IAED,OAAO,KAAK,EAAE,IAAI,EAAE,EAAE;QACpB,MAAM,UAAU,GAAG,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC;QACzC,MAAM,WAAW,GAAG,IAAA,0BAAkB,EAAC,MAAM,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC;QACvE,IAAA,kCAA0B,EAAC,WAAW,CAAC,CAAC;QACxC,MAAM,QAAQ,GAAG,IAAA,uBAAe,EAAC,MAAM,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC;QAC9D,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,IAAI,IAAI,EAAE,MAAM,EAAE,KAAK,IAAI,IAAA,uBAAe,GAAE,CAAC;QAEvE,MAAM,SAAS,GAAG,MAAM,MAAM,CAAC,qBAAqB,CAAC,EAAE,QAAQ,EAAE,WAAW,EAAE,KAAK,EAAE,CAAC,CAAC;QACvF,MAAM,EAAE,WAAW,EAAE,GAAG,OAAO,EAAE,GAAG,MAAM,QAAQ,CAAC;YACjD,SAAS;YACT,UAAU,EAAE,IAAA,8BAAa,EAAC,MAAM,CAAC,qBAAqB,CAAC;YACvD,gBAAgB,EAAE,MAAM,CAAC,gBAAgB;YACzC,WAAW;YACX,QAAQ;YACR,KAAK;YACL,SAAS,EA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AC,IAAI,CAAC,KAAK,QAAQ,EACtC,CAAC;QACD,SAAS,GAAG,EAAE,IAAI,EAAE,YAAY,CAAC,MAAM,CAAC,EAAE,EAAE,EAAE,YAAY,CAAC,IAAI,CAAC,EAAE,CAAC;IACrE,CAAC;IAED,OAAO;QACL,WAAW;QACX,kEAAkE;QAClE,sDAAsD;QACtD,SAAS,EAAE,SAAS,GAAG,SAAS;QAChC,SAAS;QACT,KAAK,EAAE,YAAY,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QACpC,KAAK,EAAE,YAAY,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QACrC,WAAW,EAAE,YAAY,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;QACjD,SAAS,EAAE,YAAY,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC;QAC7C,SAAS;QACT,gBAAgB,EAAE,YAAY,CAAC,MAAM,CAAC,oBAAoB,CAAC,CAAC;KAC7D,CAAC;AACJ,CAAC"}
@@ -0,0 +1,196 @@
1
+ import { getDefaultFetch } from "../../internal/shims.mjs";
2
+ import { VERSION } from "../../version.mjs";
3
+ import { replayHintFor } from "./identity-token.mjs";
4
+ import { DEFAULT_CREDENTIALS_TIMEOUT_IN_MS, describeFailure, GRANT_TYPE_JWT_BEARER, MAX_ASSERTION_BYTES, TOKEN_ENDPOINT, WorkloadIdentityError, nowAsSeconds, readLimitedText, redactSensitive, requireSecureTokenEndpoint, resolveAuthBaseURL, resolveResource, withTimeout, } from "./types.mjs";
5
+ /**
6
+ * Exchanges a token from the workload's identity provider for a short-lived
7
+ * Kernel access token (the RFC 7523 jwt-bearer grant).
8
+ *
9
+ * Every call asks `identityTokenProvider` for a fresh token and exchanges
10
+ * it; nothing is cached and nothing is retried. Pass the result as the
11
+ * client's `credentials` option, which wraps it in a {@link TokenCache}.
12
+ *
13
+ * The token endpoint returns no refresh token: when the access token is
14
+ * about to expire, a new identity token is exchanged.
15
+ */
16
+ export function oidcFederationProvider(config) {
17
+ if (!config.federationRuleId) {
18
+ throw new WorkloadIdentityError('federationRuleId is required');
19
+ }
20
+ return async (opts) => {
21
+ const apiBaseURL = opts?.client?.baseURL;
22
+ const authBaseURL = resolveAuthBaseURL(config.authBaseURL, apiBaseURL);
23
+ requireSecureTokenEndpoint(authBaseURL);
24
+ const resource = resolveResource(config.resource, apiBaseURL);
25
+ const fetch = config.fetch ?? opts?.client?.fetch ?? getDefaultFetch();
26
+ const assertion = await config.identityTokenProvider({ audience: authBaseURL, fetch });
27
+ const { accessToken, ...details } = await exchange({
28
+ assertion,
29
+ replayHint: replayHintFor(config.identityTokenProvider),
30
+ federationRuleId: config.federationRuleId,
31
+ authBaseURL,
32
+ resource,
33
+ fetch,
34
+ userAgent: `Kernel/JS ${VERSION} oidcFederationProvider`,
35
+ timeout: config.timeout ?? DEFAULT_CREDENTIALS_TIMEOUT_IN_MS,
36
+ });
37
+ return { token: accessToken, ...details };
38
+ };
39
+ }
40
+ /**
41
+ * Exchanges one identity provider token for a Kernel access token, for
42
+ * callers that want to manage the access token themselves. It needs no
43
+ * Kernel credential.
44
+ *
45
+ * The assertion is spent by the call: to get another access token, obtain a
46
+ * fresh assertion from the identity provider first.
47
+ */
48
+ export async function exchangeFederationAssertion(params) {
49
+ if (!params.federationRuleId) {
50
+ throw new WorkloadIdentityError('federationRuleId is required');
51
+ }
52
+ const authBaseURL = resolveAuthBaseURL(params.authBaseURL);
53
+ requireSecureTokenEndpoint(authBaseURL);
54
+ return exchange({
55
+ assertion: params.assertion,
56
+ replayHint: 'Every exchange needs a fresh provider token; this assertion was already exchanged.',
57
+ federationRuleId: params.federationRuleId,
58
+ authBaseURL,
59
+ resource: resolveResource(params.resource),
60
+ fetch: params.fetch ?? getDefaultFetch(),
61
+ userAgent: `Kernel/JS ${VERSION} exchangeFederationAssertion`,
62
+ timeout: params.timeout ?? DEFAULT_CREDENTIALS_TIMEOUT_IN_MS,
63
+ });
64
+ }
65
+ async function exchange(request) {
66
+ const { assertion } = request;
67
+ if (typeof assertion !== 'string' || !assertion) {
68
+ throw new WorkloadIdentityError('Identity token is empty');
69
+ }
70
+ // The token endpoint rejects larger assertions. Failing here names the
71
+ // problem, which is usually a path or certificate passed as the token.
72
+ const assertionBytes = new TextEncoder().encode(assertion).length;
73
+ if (assertionBytes > MAX_ASSERTION_BYTES) {
74
+ throw new WorkloadIdentityError(`Identity token is ${Math.ceil(assertionBytes / 1024)} KiB, which exceeds the 16 KiB limit`);
75
+ }
76
+ // The token endpoint rejects any parameter other than these four, and any
77
+ // Authorization header.
78
+ const body = new URLSearchParams({
79
+ grant_type: GRANT_TYPE_JWT_BEARER,
80
+ assertion,
81
+ federation_rule_id: request.federationRuleId,
82
+ resource: request.resource,
83
+ }).toString();
84
+ const url = `${request.authBaseURL}${TOKEN_ENDPOINT}`;
85
+ const startedAt = nowAsSeconds();
86
+ return withTimeout(request.timeout, async (signal) => {
87
+ let response;
88
+ try {
89
+ response = await request.fetch(url, {
90
+ method: 'POST',
91
+ redirect: 'manual',
92
+ headers: {
93
+ Accept: 'application/json',
94
+ 'Content-Type': 'application/x-www-form-urlencoded',
95
+ 'User-Agent': request.userAgent,
96
+ },
97
+ body,
98
+ signal,
99
+ });
100
+ }
101
+ catch (err) {
102
+ const reason = signal.aborted ? `timed out after ${request.timeout}ms` : describeFailure(err, [assertion]);
103
+ throw new WorkloadIdentityError(`Failed to reach token endpoint ${url}: ${reason}`);
104
+ }
105
+ const requestId = response.headers.get('x-request-id') ?? response.headers.get('request-id');
106
+ let text;
107
+ try {
108
+ text = await readLimitedText(response);
109
+ }
110
+ catch (err) {
111
+ throw new WorkloadIdentityError(`Failed to read the response from token endpoint ${url}: ${describeFailure(err, [assertion])}`, { statusCode: response.status, requestId });
112
+ }
113
+ if (!response.ok) {
114
+ throw exchangeError(response.status, text, requestId, request);
115
+ }
116
+ return parseTokenResponse(response.status, text, requestId, startedAt);
117
+ });
118
+ }
119
+ function exchangeError(status, text, requestId, { assertion, replayHint, resource }) {
120
+ let parsed;
121
+ try {
122
+ parsed = JSON.parse(text);
123
+ }
124
+ catch {
125
+ parsed = undefined;
126
+ }
127
+ const body = redactSensitive(parsed, [assertion]);
128
+ const errorCode = body?.['error'] ?? null;
129
+ const errorDescription = body?.['error_description'] ?? null;
130
+ let hint = '';
131
+ if (errorDescription && /already used/i.test(errorDescription)) {
132
+ hint = replayHint;
133
+ }
134
+ else if (errorCode === 'invalid_target') {
135
+ hint = `The token endpoint does not accept the resource "${resource}". Set the resource option to the Kernel API origin, with no trailing slash.`;
136
+ }
137
+ let detail = errorCode ?
138
+ `${errorCode}${errorDescription ? `: ${errorDescription}` : ''}`
139
+ : 'the response is not an OAuth error';
140
+ if (hint)
141
+ detail = `${detail.replace(/\.$/, '')}. ${hint}`;
142
+ return new WorkloadIdentityError(`Token exchange failed with status ${status}${requestId ? ` (request ID ${requestId})` : ''}: ${detail}`, { statusCode: status, errorCode, errorDescription, requestId, body });
143
+ }
144
+ function parseTokenResponse(status, text, requestId, startedAt) {
145
+ let data;
146
+ try {
147
+ data = JSON.parse(text);
148
+ }
149
+ catch {
150
+ data = undefined;
151
+ }
152
+ // A success body holds the access token, so none of it goes into an error.
153
+ const invalid = (problem) => new WorkloadIdentityError(`Token endpoint returned an unusable response (status ${status}): ${problem}`, {
154
+ statusCode: status,
155
+ requestId,
156
+ });
157
+ if (typeof data !== 'object' || data === null || Array.isArray(data)) {
158
+ throw invalid('the body is not a JSON object');
159
+ }
160
+ const fields = data;
161
+ const accessToken = fields['access_token'];
162
+ if (typeof accessToken !== 'string' || !accessToken) {
163
+ throw invalid('access_token is missing');
164
+ }
165
+ const tokenType = fields['token_type'];
166
+ if (tokenType !== undefined && (typeof tokenType !== 'string' || tokenType.toLowerCase() !== 'bearer')) {
167
+ throw invalid('token_type is not Bearer');
168
+ }
169
+ const expiresIn = fields['expires_in'];
170
+ if (typeof expiresIn !== 'number' || !Number.isFinite(expiresIn) || expiresIn <= 0) {
171
+ throw invalid('expires_in is missing or not a positive number');
172
+ }
173
+ const stringOrNull = (value) => (typeof value === 'string' ? value : null);
174
+ const rawPrincipal = fields['principal'];
175
+ let principal = null;
176
+ if (typeof rawPrincipal === 'object' &&
177
+ rawPrincipal !== null &&
178
+ typeof rawPrincipal['type'] === 'string' &&
179
+ typeof rawPrincipal['id'] === 'string') {
180
+ principal = { type: rawPrincipal['type'], id: rawPrincipal['id'] };
181
+ }
182
+ return {
183
+ accessToken,
184
+ // Counted from before the request was sent, so the token is never
185
+ // treated as valid for longer than the server allows.
186
+ expiresAt: startedAt + expiresIn,
187
+ expiresIn,
188
+ scope: stringOrNull(fields['scope']),
189
+ orgId: stringOrNull(fields['org_id']),
190
+ accessScope: stringOrNull(fields['access_scope']),
191
+ projectId: stringOrNull(fields['project_id']),
192
+ principal,
193
+ federationRuleId: stringOrNull(fields['federation_rule_id']),
194
+ };
195
+ }
196
+ //# sourceMappingURL=oidc-federation.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oidc-federation.mjs","sourceRoot":"","sources":["../../src/lib/credentials/oidc-federation.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,iCAA6B;AACvD,OAAO,EAAE,OAAO,EAAE,0BAAsB;AACxC,OAAO,EAAE,aAAa,EAAE,6BAAyB;AAQjD,OAAO,EACL,iCAAiC,EACjC,eAAe,EACf,qBAAqB,EACrB,mBAAmB,EACnB,cAAc,EACd,qBAAqB,EACrB,YAAY,EACZ,eAAe,EACf,eAAe,EACf,0BAA0B,EAC1B,kBAAkB,EAClB,eAAe,EACf,WAAW,GACZ,oBAAgB;AA4CjB;;;;;;;;;;GAUG;AACH,MAAM,UAAU,sBAAsB,CACpC,MAA4B;IAE5B,IAAI,CAAC,MAAM,CAAC,gBAAgB,EAAE,CAAC;QAC7B,MAAM,IAAI,qBAAqB,CAAC,8BAA8B,CAAC,CAAC;IAClE,CAAC;IAED,OAAO,KAAK,EAAE,IAAI,EAAE,EAAE;QACpB,MAAM,UAAU,GAAG,IAAI,EAAE,MAAM,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
+ import type { AccessTokenProvider } from "./types.mjs";
2
+ /**
3
+ * Wraps an {@link AccessTokenProvider} with two-tier proactive refresh and
4
+ * concurrent deduplication.
5
+ *
6
+ * The refresh thresholds scale with the token's lifetime (the time it had
7
+ * left when it was cached), so a token that lives for a few seconds is not
8
+ * refreshed on every call:
9
+ *
10
+ * - advisory: min(120s, 40% of the lifetime) remaining;
11
+ * - mandatory: min(30s, 10% of the lifetime) remaining.
12
+ *
13
+ * On each {@link getToken} call:
14
+ *
15
+ * - No cached token: call the provider, cache the result and return it.
16
+ * - Cached with `expiresAt == null`: return it forever.
17
+ * - More than the advisory threshold remaining: return the cached token.
18
+ * - Between the two thresholds: return the cached token and refresh in the
19
+ * background. A failure is reported to `onAdvisoryRefreshError` and the
20
+ * cached token keeps being served.
21
+ * - Less than the mandatory threshold remaining, or expired: wait for a
22
+ * refresh, and throw if it fails.
23
+ *
24
+ * Concurrent callers share one provider call.
25
+ */
26
+ export declare class TokenCache {
27
+ private provider;
28
+ private cached;
29
+ private cachedLifetime;
30
+ private pendingRefresh;
31
+ private pendingIsForced;
32
+ private queuedForcedRefresh;
33
+ private nextForce;
34
+ private invalidations;
35
+ private lastAdvisoryError;
36
+ private onAdvisoryRefreshError;
37
+ constructor(provider: AccessTokenProvider, onAdvisoryRefreshError?: (err: unknown) => void);
38
+ getToken(): Promise<string>;
39
+ /**
40
+ * Drops the cached token so the next {@link getToken} mints a new one.
41
+ * Call it after a 401: the server has rejected the token even though it
42
+ * has not expired.
43
+ *
44
+ * Pass the rejected token to leave the cache alone when it already holds a
45
+ * newer one, as happens when several requests fail with the same token.
46
+ */
47
+ invalidate(token?: string): void;
48
+ /**
49
+ * Joins the refresh in flight, so the provider is never called twice at
50
+ * once. A forced refresh cannot join an unforced one, which may be served
51
+ * from the provider's own cache: it is queued to run when that call
52
+ * settles, and every caller that needs a token meanwhile waits for it.
53
+ */
54
+ private refresh;
55
+ /**
56
+ * Waits {@link ADVISORY_REFRESH_BACKOFF_IN_SECONDS} after a failure before
57
+ * trying again, so an outage during the advisory window does not send one
58
+ * token request per API request.
59
+ */
60
+ private backgroundRefresh;
61
+ /** Only called when no refresh is in flight. */
62
+ private doRefresh;
63
+ }
64
+ //# sourceMappingURL=token-cache.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"token-cache.d.mts","sourceRoot":"","sources":["../../src/lib/credentials/token-cache.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAe,mBAAmB,EAAE,oBAAgB;AAUhE;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,qBAAa,UAAU;IACrB,OAAO,CAAC,QAAQ,CAAsB;IACtC,OAAO,CAAC,MAAM,CAA4B;IAC1C,OAAO,CAAC,cAAc,CAAK;IAC3B,OAAO,CAAC,cAAc,CAAqC;IAC3D,OAAO,CAAC,eAAe,CAAS;IAChC,OAAO,CAAC,mBAAmB,CAAqC;IAChE,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,aAAa,CAAK;IAC1B,OAAO,CAAC,iBAAiB,CAAa;IACtC,OAAO,CAAC,sBAAsB,CAAuC;gBAEzD,QAAQ,EAAE,mBAAmB,EAAE,sBAAsB,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,IAAI;IAKpF,QAAQ,IAAI,OAAO,CAAC,MAAM,CAAC;IAmCjC;;;;;;;OAOG;IACH,UAAU,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI;IAOhC;;;;;OAKG;IACH,OAAO,CAAC,OAAO;IAmBf;;;;OAIG;IACH,OAAO,CAAC,iBAAiB;IAazB,gDAAgD;IAChD,OAAO,CAAC,SAAS;CA0BlB"}
@@ -0,0 +1,64 @@
1
+ import type { AccessTokenProvider } from "./types.js";
2
+ /**
3
+ * Wraps an {@link AccessTokenProvider} with two-tier proactive refresh and
4
+ * concurrent deduplication.
5
+ *
6
+ * The refresh thresholds scale with the token's lifetime (the time it had
7
+ * left when it was cached), so a token that lives for a few seconds is not
8
+ * refreshed on every call:
9
+ *
10
+ * - advisory: min(120s, 40% of the lifetime) remaining;
11
+ * - mandatory: min(30s, 10% of the lifetime) remaining.
12
+ *
13
+ * On each {@link getToken} call:
14
+ *
15
+ * - No cached token: call the provider, cache the result and return it.
16
+ * - Cached with `expiresAt == null`: return it forever.
17
+ * - More than the advisory threshold remaining: return the cached token.
18
+ * - Between the two thresholds: return the cached token and refresh in the
19
+ * background. A failure is reported to `onAdvisoryRefreshError` and the
20
+ * cached token keeps being served.
21
+ * - Less than the mandatory threshold remaining, or expired: wait for a
22
+ * refresh, and throw if it fails.
23
+ *
24
+ * Concurrent callers share one provider call.
25
+ */
26
+ export declare class TokenCache {
27
+ private provider;
28
+ private cached;
29
+ private cachedLifetime;
30
+ private pendingRefresh;
31
+ private pendingIsForced;
32
+ private queuedForcedRefresh;
33
+ private nextForce;
34
+ private invalidations;
35
+ private lastAdvisoryError;
36
+ private onAdvisoryRefreshError;
37
+ constructor(provider: AccessTokenProvider, onAdvisoryRefreshError?: (err: unknown) => void);
38
+ getToken(): Promise<string>;
39
+ /**
40
+ * Drops the cached token so the next {@link getToken} mints a new one.
41
+ * Call it after a 401: the server has rejected the token even though it
42
+ * has not expired.
43
+ *
44
+ * Pass the rejected token to leave the cache alone when it already holds a
45
+ * newer one, as happens when several requests fail with the same token.
46
+ */
47
+ invalidate(token?: string): void;
48
+ /**
49
+ * Joins the refresh in flight, so the provider is never called twice at
50
+ * once. A forced refresh cannot join an unforced one, which may be served
51
+ * from the provider's own cache: it is queued to run when that call
52
+ * settles, and every caller that needs a token meanwhile waits for it.
53
+ */
54
+ private refresh;
55
+ /**
56
+ * Waits {@link ADVISORY_REFRESH_BACKOFF_IN_SECONDS} after a failure before
57
+ * trying again, so an outage during the advisory window does not send one
58
+ * token request per API request.
59
+ */
60
+ private backgroundRefresh;
61
+ /** Only called when no refresh is in flight. */
62
+ private doRefresh;
63
+ }
64
+ //# sourceMappingURL=token-cache.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"token-cache.d.ts","sourceRoot":"","sources":["../../src/lib/credentials/token-cache.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAe,mBAAmB,EAAE,mBAAgB;AAUhE;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,qBAAa,UAAU;IACrB,OAAO,CAAC,QAAQ,CAAsB;IACtC,OAAO,CAAC,MAAM,CAA4B;IAC1C,OAAO,CAAC,cAAc,CAAK;IAC3B,OAAO,CAAC,cAAc,CAAqC;IAC3D,OAAO,CAAC,eAAe,CAAS;IAChC,OAAO,CAAC,mBAAmB,CAAqC;IAChE,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,aAAa,CAAK;IAC1B,OAAO,CAAC,iBAAiB,CAAa;IACtC,OAAO,CAAC,sBAAsB,CAAuC;gBAEzD,QAAQ,EAAE,mBAAmB,EAAE,sBAAsB,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,IAAI;IAKpF,QAAQ,IAAI,OAAO,CAAC,MAAM,CAAC;IAmCjC;;;;;;;OAOG;IACH,UAAU,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI;IAOhC;;;;;OAKG;IACH,OAAO,CAAC,OAAO;IAmBf;;;;OAIG;IACH,OAAO,CAAC,iBAAiB;IAazB,gDAAgD;IAChD,OAAO,CAAC,SAAS;CA0BlB"}