@parallelworks/client 7.119.0 → 7.121.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.
package/dist/index.js CHANGED
@@ -1,6 +1,13 @@
1
1
  import { problemMiddleware } from '@parallelworks/problem';
2
2
  import createClient from 'openapi-fetch';
3
+ import { CLIAuth, hostForUnnamedCredential, loadCredentialConfig, resolveIdentity, } from './credentials';
4
+ export * from './credentials';
3
5
  export { ApiError, codeForStatus, FieldError, fromResponseBody, problemMediaType, toApiError, } from '@parallelworks/problem';
6
+ function withScheme(host) {
7
+ return host.startsWith('http://') || host.startsWith('https://')
8
+ ? host
9
+ : `https://${host}`;
10
+ }
4
11
  /**
5
12
  * The language of the POSIX locale environment (LC_ALL, then LC_MESSAGES,
6
13
  * then LANG) as a language tag: `ja_JP.UTF-8` is `ja-JP`. Undefined when none
@@ -31,6 +38,11 @@ export function problemTypeUrl(error, baseUrl) {
31
38
  }
32
39
  /** Prefix for Parallel Works API keys */
33
40
  export const API_KEY_PREFIX = 'pwt_';
41
+ /**
42
+ * Prefix for opaque access tokens, such as the one `pw auth` saves. Sent as a
43
+ * Bearer token; it names no platform host.
44
+ */
45
+ export const OPAQUE_ACCESS_TOKEN_PREFIX = 'pwoa_';
34
46
  /** Error thrown when credential parsing fails */
35
47
  export class CredentialError extends Error {
36
48
  constructor(message) {
@@ -38,6 +50,20 @@ export class CredentialError extends Error {
38
50
  this.name = 'CredentialError';
39
51
  }
40
52
  }
53
+ /** Raised when a credential names no platform host and nothing else supplies one. */
54
+ export class NoPlatformHostError extends CredentialError {
55
+ constructor(message = 'could not extract platform host from credential') {
56
+ super(message);
57
+ this.name = 'NoPlatformHostError';
58
+ }
59
+ }
60
+ /** Raised when the pw CLI cannot provide a token for a `pw auth` sign-in and no earlier one is still valid. */
61
+ export class SignInExpiredError extends CredentialError {
62
+ constructor(cause) {
63
+ super(`the pw CLI could not provide a token for the pw auth sign-in; run pw auth again, or install pw: ${cause instanceof Error ? cause.message : String(cause)}`);
64
+ this.name = 'SignInExpiredError';
65
+ }
66
+ }
41
67
  /**
42
68
  * Check if a credential is an API key.
43
69
  *
@@ -50,15 +76,17 @@ export function isApiKey(credential) {
50
76
  return credential.trim().startsWith(API_KEY_PREFIX);
51
77
  }
52
78
  /**
53
- * Check if a credential is a JWT token.
54
- *
55
- * JWTs have three base64-encoded parts separated by dots.
79
+ * Check if a credential is sent as a Bearer token: a JWT, whose three
80
+ * base64-encoded parts are separated by dots, or an opaque access token.
56
81
  *
57
82
  * @param credential - The credential string to check
58
- * @returns True if the credential appears to be a JWT token
83
+ * @returns True if the credential appears to be a token
59
84
  */
60
85
  export function isToken(credential) {
61
86
  const trimmed = credential.trim();
87
+ if (trimmed.startsWith(OPAQUE_ACCESS_TOKEN_PREFIX)) {
88
+ return true;
89
+ }
62
90
  const parts = trimmed.split('.');
63
91
  return parts.length === 3 && !trimmed.startsWith(API_KEY_PREFIX);
64
92
  }
@@ -70,6 +98,7 @@ export function isToken(credential) {
70
98
  *
71
99
  * @param credential - The API key or JWT token
72
100
  * @returns The platform host (e.g., "activate.parallel.works")
101
+ * @throws NoPlatformHostError for an opaque access token, which names no host
73
102
  * @throws CredentialError if the credential format is invalid
74
103
  */
75
104
  export function extractPlatformHost(credential) {
@@ -77,6 +106,9 @@ export function extractPlatformHost(credential) {
77
106
  if (isApiKey(credential)) {
78
107
  return extractHostFromApiKey(credential);
79
108
  }
109
+ if (credential.startsWith(OPAQUE_ACCESS_TOKEN_PREFIX)) {
110
+ throw new NoPlatformHostError();
111
+ }
80
112
  if (isToken(credential)) {
81
113
  return extractHostFromToken(credential);
82
114
  }
@@ -166,13 +198,12 @@ function extractHostFromToken(token) {
166
198
  * ```ts
167
199
  * import { Client } from '@parallelworks/client'
168
200
  *
169
- * // Using API Key (Basic Auth) - recommended for integrations
170
- * const client = new Client('https://activate.parallel.works')
171
- * .withApiKey('pwt_...')
201
+ * // Signed in with `pw auth`: the client asks the pw CLI to renew the token
202
+ * const client = Client.fromCredentialConfig()
172
203
  *
173
- * // Using Bearer Token (JWT) - for scripts
204
+ * // Using API Key (Basic Auth) - for unattended jobs such as CI
174
205
  * const client = new Client('https://activate.parallel.works')
175
- * .withToken('eyJ...')
206
+ * .withApiKey('pwt_...')
176
207
  *
177
208
  * // Or let the client extract the host from your credential
178
209
  * const client = Client.fromCredential(process.env.PW_API_KEY!)
@@ -192,8 +223,10 @@ export class Client {
192
223
  * The platform host is automatically extracted from the credential:
193
224
  * - For API keys: host is decoded from the first part after pwt_
194
225
  * - For JWT tokens: host is read from the platform_host claim
226
+ * - For access tokens (pwoa_), which name no host: PW_PLATFORM_HOST, else
227
+ * the server of the credentials file's selected context (Node.js only)
195
228
  *
196
- * @param credential - Your API key or JWT token
229
+ * @param credential - Your API key or token
197
230
  * @param options - Additional client options
198
231
  * @returns Configured API client ready to make requests
199
232
  * @throws CredentialError if the credential format is invalid
@@ -205,12 +238,61 @@ export class Client {
205
238
  * ```
206
239
  */
207
240
  static fromCredential(credential, options = {}) {
208
- let host = extractPlatformHost(credential);
209
- // Ensure https:// prefix
210
- if (!host.startsWith('http://') && !host.startsWith('https://')) {
211
- host = `https://${host}`;
241
+ let host;
242
+ try {
243
+ host = extractPlatformHost(credential);
212
244
  }
213
- return new Client(host, options).withCredential(credential);
245
+ catch (e) {
246
+ const fallback = e instanceof NoPlatformHostError
247
+ ? hostForUnnamedCredential()
248
+ : undefined;
249
+ if (!fallback) {
250
+ throw e;
251
+ }
252
+ host = fallback;
253
+ }
254
+ return new Client(withScheme(host), options).withCredential(credential);
255
+ }
256
+ /**
257
+ * Create a client from the pw credentials file (Node.js only), picking the
258
+ * credential as the CLI and the Go SDK do: PW_API_KEY, then the `context`
259
+ * option, PW_CONTEXT, and the file's current context.
260
+ *
261
+ * A context signed in with `pw auth` stays signed in: when its access token
262
+ * nears expiry the client runs `pw auth token --print` for a renewed one
263
+ * (see `CLIAuth`), so sign in once and let scripts run. Unattended jobs such
264
+ * as CI should use an API key in PW_API_KEY instead.
265
+ *
266
+ * @example
267
+ * ```ts
268
+ * const client = Client.fromCredentialConfig()
269
+ * const { data } = await client.GET('/api/buckets')
270
+ * ```
271
+ */
272
+ static fromCredentialConfig(options = {}) {
273
+ const { context, platformHost, cliCommand, cliTimeoutMs, ...clientOptions } = options;
274
+ const config = loadCredentialConfig();
275
+ const { context: name, identity } = resolveIdentity(config, {
276
+ context,
277
+ platformHost,
278
+ });
279
+ const client = new Client(withScheme(identity.server), clientOptions);
280
+ if (identity.apikey) {
281
+ return isToken(identity.apikey)
282
+ ? client.withToken(identity.apikey)
283
+ : client.withApiKey(identity.apikey);
284
+ }
285
+ if (!identity.token) {
286
+ throw new CredentialError('you must first authenticate using "pw auth"');
287
+ }
288
+ if (identity.oauth) {
289
+ return client.withTokenProvider(new CLIAuth({
290
+ command: cliCommand,
291
+ context: name,
292
+ timeoutMs: cliTimeoutMs,
293
+ }));
294
+ }
295
+ return client.withToken(identity.token);
214
296
  }
215
297
  /**
216
298
  * Authenticate with an API Key using Basic Auth
@@ -229,29 +311,31 @@ export class Client {
229
311
  ? btoa(`${apiKey}:`)
230
312
  : Buffer.from(`${apiKey}:`).toString('base64');
231
313
  this.authHeader = `Basic ${encoded}`;
314
+ this.tokenProvider = undefined;
232
315
  return this.build();
233
316
  }
234
317
  /**
235
- * Authenticate with a Bearer Token (JWT)
318
+ * Authenticate with a Bearer token, sent as is and never renewed.
236
319
  *
237
- * Best for scripts and CLI tools. Tokens expire after 24 hours.
238
- * Tokens can be generated from your ACTIVATE account settings.
320
+ * For a script, sign in once with `pw auth` and use `fromCredentialConfig`,
321
+ * which renews the token; for an unattended job such as CI, use an API key.
239
322
  *
240
- * @param token - Your JWT token from account settings
323
+ * @param token - A token, such as one `pw auth token --print` printed
241
324
  * @returns Configured API client ready to make requests
242
325
  */
243
326
  withToken(token) {
244
327
  // Trim whitespace to handle env vars with trailing newlines
245
328
  this.authHeader = `Bearer ${token.trim()}`;
329
+ this.tokenProvider = undefined;
246
330
  return this.build();
247
331
  }
248
332
  /**
249
333
  * Authenticate with automatic credential type detection
250
334
  *
251
335
  * Automatically detects whether the credential is an API key (starts with "pwt_")
252
- * or a JWT token and configures the appropriate authentication method.
336
+ * or a token and configures the appropriate authentication method.
253
337
  *
254
- * @param credential - Your API key or JWT token
338
+ * @param credential - Your API key or token
255
339
  * @returns Configured API client ready to make requests
256
340
  */
257
341
  withCredential(credential) {
@@ -260,6 +344,18 @@ export class Client {
260
344
  }
261
345
  return this.withToken(credential);
262
346
  }
347
+ /**
348
+ * Authenticate each request with a Bearer token the provider supplies, such
349
+ * as a `CLIAuth` that renews a `pw auth` sign-in.
350
+ *
351
+ * @param provider - Supplies the current token
352
+ * @returns Configured API client ready to make requests
353
+ */
354
+ withTokenProvider(provider) {
355
+ this.authHeader = undefined;
356
+ this.tokenProvider = provider;
357
+ return this.build();
358
+ }
263
359
  /**
264
360
  * Build the openapi-fetch client with configured options.
265
361
  *
@@ -278,6 +374,15 @@ export class Client {
278
374
  ...(this.authHeader && { Authorization: this.authHeader }),
279
375
  },
280
376
  });
377
+ const provider = this.tokenProvider;
378
+ if (provider) {
379
+ client.use({
380
+ async onRequest({ request }) {
381
+ request.headers.set('Authorization', `Bearer ${await provider.token()}`);
382
+ return request;
383
+ },
384
+ });
385
+ }
281
386
  client.use(problemMiddleware);
282
387
  // Attach HTTP status code to error response bodies so consumers
283
388
  // (e.g. SWR hooks) can distinguish 404s from other errors.