@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,172 @@
1
+ import type { AccessToken, AccessTokenProvider } from './types';
2
+ import {
3
+ ADVISORY_REFRESH_BACKOFF_IN_SECONDS,
4
+ ADVISORY_REFRESH_LIFETIME_FRACTION,
5
+ ADVISORY_REFRESH_THRESHOLD_IN_SECONDS,
6
+ MANDATORY_REFRESH_LIFETIME_FRACTION,
7
+ MANDATORY_REFRESH_THRESHOLD_IN_SECONDS,
8
+ nowAsSeconds,
9
+ } from './types';
10
+
11
+ /**
12
+ * Wraps an {@link AccessTokenProvider} with two-tier proactive refresh and
13
+ * concurrent deduplication.
14
+ *
15
+ * The refresh thresholds scale with the token's lifetime (the time it had
16
+ * left when it was cached), so a token that lives for a few seconds is not
17
+ * refreshed on every call:
18
+ *
19
+ * - advisory: min(120s, 40% of the lifetime) remaining;
20
+ * - mandatory: min(30s, 10% of the lifetime) remaining.
21
+ *
22
+ * On each {@link getToken} call:
23
+ *
24
+ * - No cached token: call the provider, cache the result and return it.
25
+ * - Cached with `expiresAt == null`: return it forever.
26
+ * - More than the advisory threshold remaining: return the cached token.
27
+ * - Between the two thresholds: return the cached token and refresh in the
28
+ * background. A failure is reported to `onAdvisoryRefreshError` and the
29
+ * cached token keeps being served.
30
+ * - Less than the mandatory threshold remaining, or expired: wait for a
31
+ * refresh, and throw if it fails.
32
+ *
33
+ * Concurrent callers share one provider call.
34
+ */
35
+ export class TokenCache {
36
+ private provider: AccessTokenProvider;
37
+ private cached: AccessToken | null = null;
38
+ private cachedLifetime = 0;
39
+ private pendingRefresh: Promise<AccessToken> | null = null;
40
+ private pendingIsForced = false;
41
+ private queuedForcedRefresh: Promise<AccessToken> | null = null;
42
+ private nextForce = false;
43
+ private invalidations = 0;
44
+ private lastAdvisoryError = -Infinity;
45
+ private onAdvisoryRefreshError: ((err: unknown) => void) | undefined;
46
+
47
+ constructor(provider: AccessTokenProvider, onAdvisoryRefreshError?: (err: unknown) => void) {
48
+ this.provider = provider;
49
+ this.onAdvisoryRefreshError = onAdvisoryRefreshError;
50
+ }
51
+
52
+ async getToken(): Promise<string> {
53
+ // Stays set until a forced refresh succeeds.
54
+ const force = this.nextForce;
55
+ const cached = this.cached;
56
+
57
+ if (force || cached == null) {
58
+ return (await this.refresh(force)).token;
59
+ }
60
+
61
+ if (cached.expiresAt == null) {
62
+ return cached.token;
63
+ }
64
+
65
+ const remaining = cached.expiresAt - nowAsSeconds();
66
+ const advisory = Math.min(
67
+ ADVISORY_REFRESH_THRESHOLD_IN_SECONDS,
68
+ ADVISORY_REFRESH_LIFETIME_FRACTION * this.cachedLifetime,
69
+ );
70
+ const mandatory = Math.min(
71
+ MANDATORY_REFRESH_THRESHOLD_IN_SECONDS,
72
+ MANDATORY_REFRESH_LIFETIME_FRACTION * this.cachedLifetime,
73
+ );
74
+
75
+ if (remaining > advisory) {
76
+ return cached.token;
77
+ }
78
+
79
+ if (remaining > mandatory) {
80
+ this.backgroundRefresh();
81
+ return cached.token;
82
+ }
83
+
84
+ return (await this.refresh()).token;
85
+ }
86
+
87
+ /**
88
+ * Drops the cached token so the next {@link getToken} mints a new one.
89
+ * Call it after a 401: the server has rejected the token even though it
90
+ * has not expired.
91
+ *
92
+ * Pass the rejected token to leave the cache alone when it already holds a
93
+ * newer one, as happens when several requests fail with the same token.
94
+ */
95
+ invalidate(token?: string): void {
96
+ if (token !== undefined && this.cached?.token !== token) return;
97
+ this.cached = null;
98
+ this.nextForce = true;
99
+ this.invalidations++;
100
+ }
101
+
102
+ /**
103
+ * Joins the refresh in flight, so the provider is never called twice at
104
+ * once. A forced refresh cannot join an unforced one, which may be served
105
+ * from the provider's own cache: it is queued to run when that call
106
+ * settles, and every caller that needs a token meanwhile waits for it.
107
+ */
108
+ private refresh(force = false): Promise<AccessToken> {
109
+ if (this.queuedForcedRefresh) {
110
+ return this.queuedForcedRefresh;
111
+ }
112
+ const pending = this.pendingRefresh;
113
+ if (!pending) {
114
+ return this.doRefresh(force);
115
+ }
116
+ if (!force || this.pendingIsForced) {
117
+ return pending;
118
+ }
119
+ const run = () => {
120
+ this.queuedForcedRefresh = null;
121
+ return this.doRefresh(true);
122
+ };
123
+ this.queuedForcedRefresh = pending.then(run, run);
124
+ return this.queuedForcedRefresh;
125
+ }
126
+
127
+ /**
128
+ * Waits {@link ADVISORY_REFRESH_BACKOFF_IN_SECONDS} after a failure before
129
+ * trying again, so an outage during the advisory window does not send one
130
+ * token request per API request.
131
+ */
132
+ private backgroundRefresh(): void {
133
+ if (this.pendingRefresh || this.queuedForcedRefresh) {
134
+ return;
135
+ }
136
+ if (nowAsSeconds() - this.lastAdvisoryError < ADVISORY_REFRESH_BACKOFF_IN_SECONDS) {
137
+ return;
138
+ }
139
+ this.doRefresh().catch((err) => {
140
+ this.lastAdvisoryError = nowAsSeconds();
141
+ this.onAdvisoryRefreshError?.(err);
142
+ });
143
+ }
144
+
145
+ /** Only called when no refresh is in flight. */
146
+ private doRefresh(force = false): Promise<AccessToken> {
147
+ const invalidations = this.invalidations;
148
+ this.pendingIsForced = force;
149
+ this.pendingRefresh = (async () => this.provider(force ? { forceRefresh: true } : undefined))().then(
150
+ (token) => {
151
+ this.pendingRefresh = null;
152
+ // An unforced call that was already running when the cache was
153
+ // invalidated may return the rejected token from the provider's own
154
+ // cache. Its caller gets the result, but it is not cached, so the
155
+ // next caller forces a refresh.
156
+ if (force) this.nextForce = false;
157
+ if (force || invalidations === this.invalidations) {
158
+ this.cached = token;
159
+ // Measured from now, not from the token's issue time, so a token
160
+ // that was slow to arrive is not already inside its refresh window.
161
+ this.cachedLifetime = token.expiresAt == null ? 0 : Math.max(0, token.expiresAt - nowAsSeconds());
162
+ }
163
+ return token;
164
+ },
165
+ (err) => {
166
+ this.pendingRefresh = null;
167
+ throw err;
168
+ },
169
+ );
170
+ return this.pendingRefresh;
171
+ }
172
+ }
@@ -0,0 +1,267 @@
1
+ import { KernelError } from '../../core/error';
2
+ import type { Fetch } from '../../internal/builtin-types';
3
+ import { readEnv } from '../../internal/utils/env';
4
+
5
+ export type AccessToken = {
6
+ token: string;
7
+ /** Unix epoch seconds, fractions allowed. `null` means the token never expires. */
8
+ expiresAt: number | null;
9
+ };
10
+
11
+ /** What a client passes to its credentials on every call. */
12
+ export type CredentialsClientContext = {
13
+ /** The client's configured `fetch`, with the client's `fetchOptions` applied. */
14
+ fetch: Fetch;
15
+ /** The client's API base URL. */
16
+ baseURL: string;
17
+ };
18
+
19
+ export type AccessTokenProviderOptions = {
20
+ /**
21
+ * Set by {@link TokenCache.invalidate} after a 401. A provider that keeps
22
+ * its own cache must bypass it and mint a new token.
23
+ */
24
+ forceRefresh?: boolean;
25
+ /** Set when a Kernel client calls the provider. */
26
+ client?: CredentialsClientContext;
27
+ };
28
+
29
+ /** Mints an access token. Wrap it in a {@link TokenCache} to avoid minting one per request. */
30
+ export type AccessTokenProvider = (opts?: AccessTokenProviderOptions) => Promise<AccessToken>;
31
+
32
+ export type IdentityTokenRequest = {
33
+ /** The audience Kernel expects when the source has no explicit audience configured. */
34
+ audience?: string;
35
+ /** The `fetch` to use for sources that make an HTTP request. */
36
+ fetch?: Fetch;
37
+ };
38
+
39
+ /**
40
+ * Returns a token from the workload's own identity provider. It is called
41
+ * once per exchange and must return a fresh token every time: most providers'
42
+ * tokens can be exchanged only once.
43
+ */
44
+ export type IdentityTokenProvider = (request?: IdentityTokenRequest) => string | Promise<string>;
45
+
46
+ export type FederationPrincipal = { type: string; id: string };
47
+
48
+ export type FederationTokenDetails = {
49
+ /** Unix epoch seconds, fractions allowed. */
50
+ expiresAt: number;
51
+ /** The lifetime the token endpoint reported, in seconds. */
52
+ expiresIn: number;
53
+ scope: string | null;
54
+ orgId: string | null;
55
+ accessScope: string | null;
56
+ projectId: string | null;
57
+ principal: FederationPrincipal | null;
58
+ federationRuleId: string | null;
59
+ };
60
+
61
+ export type FederationAccessToken = { token: string } & FederationTokenDetails;
62
+
63
+ export const GRANT_TYPE_JWT_BEARER = 'urn:ietf:params:oauth:grant-type:jwt-bearer';
64
+ export const TOKEN_ENDPOINT = '/token';
65
+ export const DEFAULT_API_BASE_URL = 'https://api.onkernel.com';
66
+ export const DEFAULT_AUTH_BASE_URL = 'https://auth.onkernel.com';
67
+
68
+ export const ADVISORY_REFRESH_THRESHOLD_IN_SECONDS = 120;
69
+ export const ADVISORY_REFRESH_LIFETIME_FRACTION = 0.4;
70
+ export const MANDATORY_REFRESH_THRESHOLD_IN_SECONDS = 30;
71
+ export const MANDATORY_REFRESH_LIFETIME_FRACTION = 0.1;
72
+ export const ADVISORY_REFRESH_BACKOFF_IN_SECONDS = 5;
73
+
74
+ export const MAX_ASSERTION_BYTES = 16 * 1024;
75
+ export const MAX_TOKEN_RESPONSE_BYTES = 1 << 20;
76
+ export const DEFAULT_CREDENTIALS_TIMEOUT_IN_MS = 30_000;
77
+
78
+ export function nowAsSeconds(): number {
79
+ return Date.now() / 1000;
80
+ }
81
+
82
+ export class WorkloadIdentityError extends KernelError {
83
+ /** HTTP status of the token endpoint response, when there was one. */
84
+ readonly statusCode: number | null;
85
+ /** OAuth `error` code, such as `invalid_grant`. */
86
+ readonly errorCode: string | null;
87
+ /** OAuth `error_description`. */
88
+ readonly errorDescription: string | null;
89
+ readonly requestId: string | null;
90
+ /** The response body, reduced to its `error`, `error_description` and `error_uri` strings. */
91
+ readonly body: Record<string, string> | null;
92
+
93
+ constructor(
94
+ message: string,
95
+ {
96
+ statusCode = null,
97
+ errorCode = null,
98
+ errorDescription = null,
99
+ requestId = null,
100
+ body = null,
101
+ cause,
102
+ }: {
103
+ statusCode?: number | null;
104
+ errorCode?: string | null;
105
+ errorDescription?: string | null;
106
+ requestId?: string | null;
107
+ body?: Record<string, string> | null;
108
+ cause?: unknown;
109
+ } = {},
110
+ ) {
111
+ super(message);
112
+ this.name = 'WorkloadIdentityError';
113
+ this.statusCode = statusCode;
114
+ this.errorCode = errorCode;
115
+ this.errorDescription = errorDescription;
116
+ this.requestId = requestId;
117
+ this.body = body;
118
+ // in some environments the 'cause' property is already declared
119
+ // @ts-ignore
120
+ if (cause !== undefined) this.cause = cause;
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Rejects token endpoints that would send an identity token over cleartext
126
+ * HTTP. Loopback hosts are allowed for local development.
127
+ */
128
+ export function requireSecureTokenEndpoint(baseURL: string): void {
129
+ let url: URL;
130
+ try {
131
+ url = new URL(baseURL);
132
+ } catch {
133
+ throw new WorkloadIdentityError(`Invalid auth base URL "${baseURL}"`);
134
+ }
135
+ if (url.protocol === 'https:') return;
136
+ // URL.hostname keeps the brackets around an IPv6 address.
137
+ const host = url.hostname.toLowerCase().replace(/^\[|\]$/g, '');
138
+ if (url.protocol === 'http:' && (host === 'localhost' || host === '127.0.0.1' || host === '::1')) {
139
+ return;
140
+ }
141
+ throw new WorkloadIdentityError(
142
+ `Refusing to send an identity token to non-https auth base URL "${baseURL}"`,
143
+ );
144
+ }
145
+
146
+ /**
147
+ * The host that exchanges identity tokens: the explicit value, else
148
+ * `KERNEL_AUTH_BASE_URL`, else production when the API base URL is the
149
+ * production default. A custom API base URL never falls back to production.
150
+ */
151
+ export function resolveAuthBaseURL(explicit?: string | undefined, apiBaseURL?: string | undefined): string {
152
+ const configured = explicit || readEnv('KERNEL_AUTH_BASE_URL');
153
+ if (configured) return configured.replace(/\/+$/, '');
154
+ const api = resolveAPIBaseURL(apiBaseURL);
155
+ if (api.replace(/\/+$/, '') === DEFAULT_API_BASE_URL) return DEFAULT_AUTH_BASE_URL;
156
+ throw new WorkloadIdentityError(
157
+ `Cannot determine the auth base URL for the custom API base URL "${api}". Set the KERNEL_AUTH_BASE_URL environment variable or the authBaseURL option.`,
158
+ );
159
+ }
160
+
161
+ /** The `resource` an access token is requested for: the origin of the API base URL. */
162
+ export function resolveResource(explicit?: string | undefined, apiBaseURL?: string | undefined): string {
163
+ if (explicit) return explicit;
164
+ const api = resolveAPIBaseURL(apiBaseURL);
165
+ try {
166
+ return new URL(api).origin;
167
+ } catch {
168
+ throw new WorkloadIdentityError(`Invalid API base URL "${api}"`);
169
+ }
170
+ }
171
+
172
+ function resolveAPIBaseURL(apiBaseURL: string | undefined): string {
173
+ return apiBaseURL || readEnv('KERNEL_BASE_URL') || DEFAULT_API_BASE_URL;
174
+ }
175
+
176
+ // RFC 6749 section 5.2 error fields. A token endpoint may echo anything else
177
+ // it was sent, including the assertion, so every other field is dropped.
178
+ const SAFE_ERROR_KEYS = new Set(['error', 'error_description', 'error_uri']);
179
+
180
+ /**
181
+ * Reduces a token endpoint error body to what is safe to put in an error:
182
+ * the RFC 6749 error fields that are strings. Anything that is not a JSON
183
+ * object, such as a proxy's error page, is discarded. Pass every credential
184
+ * that was sent as `secrets`, so a server that echoes one back does not
185
+ * leak it.
186
+ */
187
+ export function redactSensitive(body: unknown, secrets: string[] = []): Record<string, string> | null {
188
+ if (typeof body !== 'object' || body === null || Array.isArray(body)) return null;
189
+ const out: Record<string, string> = {};
190
+ for (const [key, value] of Object.entries(body)) {
191
+ if (SAFE_ERROR_KEYS.has(key) && typeof value === 'string') out[key] = scrubSecrets(value, secrets);
192
+ }
193
+ return out;
194
+ }
195
+
196
+ /**
197
+ * Describes an error thrown while a credential was in flight, with its
198
+ * causes and without the credential. Use the result in place of attaching
199
+ * the error as a `cause`, which loggers print in full.
200
+ */
201
+ export function describeFailure(err: unknown, secrets: string[]): string {
202
+ const parts: string[] = [];
203
+ for (
204
+ let current = err;
205
+ current != null && parts.length < 3;
206
+ current = (current as { cause?: unknown }).cause
207
+ ) {
208
+ parts.push(String(current));
209
+ }
210
+ return scrubSecrets(parts.join(': '), secrets);
211
+ }
212
+
213
+ /** Replaces every occurrence of each secret, plain or URL-encoded, in text that came from outside the SDK. */
214
+ export function scrubSecrets(text: string, secrets: string[]): string {
215
+ for (const secret of secrets) {
216
+ if (!secret) continue;
217
+ for (const form of new Set([secret, encodeURIComponent(secret)])) {
218
+ text = text.split(form).join('[redacted]');
219
+ }
220
+ }
221
+ return text;
222
+ }
223
+
224
+ /** Reads at most `maxBytes` of a response body as UTF-8 text. */
225
+ export async function readLimitedText(
226
+ response: Response,
227
+ maxBytes: number = MAX_TOKEN_RESPONSE_BYTES,
228
+ ): Promise<string> {
229
+ if (!response.body) return '';
230
+ const reader = response.body.getReader();
231
+ const chunks: Uint8Array[] = [];
232
+ let received = 0;
233
+ for (;;) {
234
+ const { done, value } = await reader.read();
235
+ if (done) break;
236
+ if (received + value.length > maxBytes) {
237
+ chunks.push(value.subarray(0, maxBytes - received));
238
+ received = maxBytes;
239
+ await reader.cancel();
240
+ break;
241
+ }
242
+ chunks.push(value);
243
+ received += value.length;
244
+ }
245
+ const merged = new Uint8Array(received);
246
+ let offset = 0;
247
+ for (const chunk of chunks) {
248
+ merged.set(chunk, offset);
249
+ offset += chunk.length;
250
+ }
251
+ return new TextDecoder('utf-8').decode(merged);
252
+ }
253
+
254
+ /**
255
+ * Runs `fn` with an abort signal that fires after `timeoutMs`. The timer
256
+ * covers everything `fn` awaits, so it bounds reading the body as well as
257
+ * waiting for the headers.
258
+ */
259
+ export async function withTimeout<T>(timeoutMs: number, fn: (signal: AbortSignal) => Promise<T>): Promise<T> {
260
+ const controller = new AbortController();
261
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
262
+ try {
263
+ return await fn(controller.signal);
264
+ } finally {
265
+ clearTimeout(timer);
266
+ }
267
+ }
@@ -0,0 +1,30 @@
1
+ export {
2
+ type AccessToken,
3
+ type AccessTokenProvider,
4
+ type AccessTokenProviderOptions,
5
+ type CredentialsClientContext,
6
+ type FederationAccessToken,
7
+ type FederationPrincipal,
8
+ type FederationTokenDetails,
9
+ type IdentityTokenProvider,
10
+ type IdentityTokenRequest,
11
+ WorkloadIdentityError,
12
+ } from './credentials/types';
13
+ export { TokenCache } from './credentials/token-cache';
14
+ export {
15
+ type FederationAssertionExchangeParams,
16
+ type FederationExchangeResult,
17
+ type OIDCFederationConfig,
18
+ exchangeFederationAssertion,
19
+ oidcFederationProvider,
20
+ } from './credentials/oidc-federation';
21
+ export {
22
+ type AWSSTSIdentityTokenOptions,
23
+ type IdentityTokenSourceOptions,
24
+ identityTokenFromAWSSTS,
25
+ identityTokenFromFile,
26
+ identityTokenFromGCPMetadata,
27
+ identityTokenFromGitHubActions,
28
+ identityTokenFromValue,
29
+ } from './credentials/identity-token';
30
+ export { type IdentityTokenSource, federationCredentialsFromEnv } from './credentials/credential-chain';