@parallelworks/client 7.122.0 → 7.139.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/README.md CHANGED
@@ -24,7 +24,7 @@ import { Client } from '@parallelworks/client'
24
24
  // The platform host is automatically extracted from your credential
25
25
  const client = Client.fromCredential(process.env.PW_API_KEY!)
26
26
 
27
- const { data, error } = await client.GET('/api/buckets')
27
+ const { data, error } = await client.GET('/api/storage')
28
28
  ```
29
29
 
30
30
  See the [examples](./examples) directory for complete runnable examples.
@@ -39,7 +39,7 @@ For scripts you run yourself, sign in once with `pw auth`, then create the clien
39
39
  import { Client } from '@parallelworks/client'
40
40
 
41
41
  const client = Client.fromCredentialConfig()
42
- const { data } = await client.GET('/api/buckets')
42
+ const { data } = await client.GET('/api/storage')
43
43
  ```
44
44
 
45
45
  The credential is picked as the `pw` CLI picks it: `PW_API_KEY`, then the `context` option, `PW_CONTEXT`, and the current context. A signed-in context stays signed in: the client runs `pw auth token --print -o json` for an access token, reads its lifetime from the response (an RFC 6749 token response), and runs it again a minute before the token expires, the way a Kubernetes exec credential plugin or an AWS `credential_process` works, so only the `pw` CLI ever rotates the sign-in's refresh token. `cliCommand` and `cliTimeoutMs` set the `pw` executable (default `pw` on `PATH`) and how long one run may take (default one minute). A `pw` found through a relative `PATH` entry, such as the current directory, is refused, as Go refuses it. Without `pw`, requests reject with `SignInExpiredError`. This needs Node.js 20.16 or later.
@@ -110,7 +110,9 @@ export const { useQuery, useImmutable, useInfinite } = createSwrHooks(client)
110
110
  import { useQuery } from '@/lib/api'
111
111
 
112
112
  export function BucketList() {
113
- const { data, error, isLoading } = useQuery('/api/buckets')
113
+ const { data, error, isLoading } = useQuery('/api/storage', {
114
+ params: { query: { category: 'buckets' } },
115
+ })
114
116
 
115
117
  if (isLoading) return <div>Loading...</div>
116
118
  if (error) return <div>Error: {error.message}</div>
@@ -132,7 +134,7 @@ The client asks for errors as [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457)
132
134
  ```ts
133
135
  import { Client, problemTypeUrl, toApiError } from '@parallelworks/client'
134
136
 
135
- const { error } = await client.GET('/api/buckets')
137
+ const { error } = await client.GET('/api/storage')
136
138
  if (error) {
137
139
  const problem = toApiError(error)
138
140
  console.error(problem.code, problem.message)
@@ -8,6 +8,8 @@ export interface Identity {
8
8
  organization: string;
9
9
  /** The state of a `pw auth` sign-in, which only the CLI reads. */
10
10
  oauth?: Record<string, unknown>;
11
+ /** A workload `pw agent enroll` registered, which signs in with its own key. */
12
+ workload?: Record<string, unknown>;
11
13
  }
12
14
  /** The pw credentials file. */
13
15
  export interface CredentialConfig {
@@ -121,6 +121,28 @@ describe.skipIf(process.platform === 'win32')('Client.fromCredentialConfig', ()
121
121
  ]);
122
122
  expect(calls()).toHaveLength(2);
123
123
  });
124
+ it('renews an enrolled workload through the CLI, even before its first token', async () => {
125
+ writeFileSync(credentialsPath(), JSON.stringify({
126
+ currentIdentity: 'agent',
127
+ identities: {
128
+ agent: {
129
+ server: 'work.example.com',
130
+ name: 'agent',
131
+ organization: 'org',
132
+ workload: { clientId: 'pwc_x', subject: 'user:alice' },
133
+ },
134
+ },
135
+ }));
136
+ fakeCLI(printScript('pwoa_workload', 3600));
137
+ const { fetch, requests } = respond();
138
+ const client = Client.fromCredentialConfig({ fetch });
139
+ expect(await authorizations(client, requests)).toEqual([
140
+ 'Bearer pwoa_workload',
141
+ ]);
142
+ expect(calls()).toEqual([
143
+ 'auth token --print -o json --context agent key=unset',
144
+ ]);
145
+ });
124
146
  it('uses a token with no expiry for the life of the client', async () => {
125
147
  writeSignIn('pwoa_stored', 3600000);
126
148
  fakeCLI(printScript('pwoa_new'));
package/dist/index.d.ts CHANGED
@@ -38,6 +38,17 @@ export declare const API_KEY_PREFIX = "pwt_";
38
38
  * Bearer token; it names no platform host.
39
39
  */
40
40
  export declare const OPAQUE_ACCESS_TOKEN_PREFIX = "pwoa_";
41
+ /**
42
+ * Prefix for a workflow run's opaque token. It names its platform host like an
43
+ * API key and is sent as a Bearer token.
44
+ */
45
+ export declare const WORKFLOW_RUN_TOKEN_PREFIX = "pwwr_";
46
+ /** Prefix for an instance agent's opaque token, named and sent like a workflow run's. */
47
+ export declare const INSTANCE_TOKEN_PREFIX = "pwin_";
48
+ /** Prefix for a cluster session's opaque token, named and sent like a workflow run's. */
49
+ export declare const CLUSTER_SESSION_TOKEN_PREFIX = "pwcs_";
50
+ /** The User-Agent the client sends outside a browser, which sends its own. */
51
+ export declare const USER_AGENT: string;
41
52
  /** Error thrown when credential parsing fails */
42
53
  export declare class CredentialError extends Error {
43
54
  constructor(message: string);
@@ -61,7 +72,8 @@ export declare class SignInExpiredError extends CredentialError {
61
72
  export declare function isApiKey(credential: string): boolean;
62
73
  /**
63
74
  * Check if a credential is sent as a Bearer token: a JWT, whose three
64
- * base64-encoded parts are separated by dots, or an opaque access token.
75
+ * base64-encoded parts are separated by dots, an opaque access token, or a
76
+ * workflow run's, instance's or cluster session's token.
65
77
  *
66
78
  * @param credential - The credential string to check
67
79
  * @returns True if the credential appears to be a token
@@ -70,7 +82,9 @@ export declare function isToken(credential: string): boolean;
70
82
  /**
71
83
  * Extract the platform host from an API key or JWT token.
72
84
  *
73
- * For API keys (pwt_xxxx.yyyy): decodes the first part after pwt_ to get the host
85
+ * For API keys (pwt_xxxx.yyyy) and workflow run, instance and cluster session
86
+ * tokens (pwwr_, pwin_, pwcs_ followed by xxxx.yyyy): decodes the first part
87
+ * after the prefix to get the host
74
88
  * For JWT tokens: decodes the payload (second segment) and reads platform_host field
75
89
  *
76
90
  * @param credential - The API key or JWT token
@@ -97,7 +111,7 @@ export declare function extractPlatformHost(credential: string): string;
97
111
  * const client = Client.fromCredential(process.env.PW_API_KEY!)
98
112
  *
99
113
  * // Make requests
100
- * const { data, error } = await client.GET('/api/buckets')
114
+ * const { data, error } = await client.GET('/api/storage')
101
115
  * ```
102
116
  */
103
117
  export declare class Client {
@@ -110,7 +124,8 @@ export declare class Client {
110
124
  * Create a client using only a credential.
111
125
  *
112
126
  * The platform host is automatically extracted from the credential:
113
- * - For API keys: host is decoded from the first part after pwt_
127
+ * - For API keys and workflow run, instance and cluster session tokens: host
128
+ * is decoded from the first part after the prefix
114
129
  * - For JWT tokens: host is read from the platform_host claim
115
130
  * - For access tokens (pwoa_), which name no host: PW_PLATFORM_HOST, else
116
131
  * the server of the credentials file's selected context (Node.js only)
@@ -140,7 +155,7 @@ export declare class Client {
140
155
  * @example
141
156
  * ```ts
142
157
  * const client = Client.fromCredentialConfig()
143
- * const { data } = await client.GET('/api/buckets')
158
+ * const { data } = await client.GET('/api/storage')
144
159
  * ```
145
160
  */
146
161
  static fromCredentialConfig(options?: CredentialConfigOptions): OpenAPIFetchClient;
package/dist/index.js CHANGED
@@ -43,6 +43,41 @@ export const API_KEY_PREFIX = 'pwt_';
43
43
  * Bearer token; it names no platform host.
44
44
  */
45
45
  export const OPAQUE_ACCESS_TOKEN_PREFIX = 'pwoa_';
46
+ /**
47
+ * Prefix for a workflow run's opaque token. It names its platform host like an
48
+ * API key and is sent as a Bearer token.
49
+ */
50
+ export const WORKFLOW_RUN_TOKEN_PREFIX = 'pwwr_';
51
+ /** Prefix for an instance agent's opaque token, named and sent like a workflow run's. */
52
+ export const INSTANCE_TOKEN_PREFIX = 'pwin_';
53
+ /** Prefix for a cluster session's opaque token, named and sent like a workflow run's. */
54
+ export const CLUSTER_SESSION_TOKEN_PREFIX = 'pwcs_';
55
+ const HOST_NAMING_TOKEN_PREFIXES = [
56
+ WORKFLOW_RUN_TOKEN_PREFIX,
57
+ INSTANCE_TOKEN_PREFIX,
58
+ CLUSTER_SESSION_TOKEN_PREFIX,
59
+ ];
60
+ function hostNamingTokenPrefix(credential) {
61
+ return HOST_NAMING_TOKEN_PREFIXES.find(prefix => credential.startsWith(prefix));
62
+ }
63
+ // The release stamps the version in package.json, which only Node.js can read here. A bundle that moved
64
+ // this module finds some other package.json, so only this package's own counts.
65
+ function sdkVersion() {
66
+ const get = globalThis.process?.getBuiltinModule;
67
+ try {
68
+ const nodeModule = get?.('node:module');
69
+ const pkg = nodeModule?.createRequire(import.meta.url)('../package.json');
70
+ return pkg?.name === '@parallelworks/client' &&
71
+ typeof pkg.version === 'string'
72
+ ? pkg.version
73
+ : '0';
74
+ }
75
+ catch {
76
+ return '0';
77
+ }
78
+ }
79
+ /** The User-Agent the client sends outside a browser, which sends its own. */
80
+ export const USER_AGENT = `parallelworks-typescript-sdk/${sdkVersion()}`;
46
81
  /** Error thrown when credential parsing fails */
47
82
  export class CredentialError extends Error {
48
83
  constructor(message) {
@@ -77,14 +112,16 @@ export function isApiKey(credential) {
77
112
  }
78
113
  /**
79
114
  * 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.
115
+ * base64-encoded parts are separated by dots, an opaque access token, or a
116
+ * workflow run's, instance's or cluster session's token.
81
117
  *
82
118
  * @param credential - The credential string to check
83
119
  * @returns True if the credential appears to be a token
84
120
  */
85
121
  export function isToken(credential) {
86
122
  const trimmed = credential.trim();
87
- if (trimmed.startsWith(OPAQUE_ACCESS_TOKEN_PREFIX)) {
123
+ if (trimmed.startsWith(OPAQUE_ACCESS_TOKEN_PREFIX) ||
124
+ hostNamingTokenPrefix(trimmed) !== undefined) {
88
125
  return true;
89
126
  }
90
127
  const parts = trimmed.split('.');
@@ -93,7 +130,9 @@ export function isToken(credential) {
93
130
  /**
94
131
  * Extract the platform host from an API key or JWT token.
95
132
  *
96
- * For API keys (pwt_xxxx.yyyy): decodes the first part after pwt_ to get the host
133
+ * For API keys (pwt_xxxx.yyyy) and workflow run, instance and cluster session
134
+ * tokens (pwwr_, pwin_, pwcs_ followed by xxxx.yyyy): decodes the first part
135
+ * after the prefix to get the host
97
136
  * For JWT tokens: decodes the payload (second segment) and reads platform_host field
98
137
  *
99
138
  * @param credential - The API key or JWT token
@@ -104,7 +143,11 @@ export function isToken(credential) {
104
143
  export function extractPlatformHost(credential) {
105
144
  credential = credential.trim();
106
145
  if (isApiKey(credential)) {
107
- return extractHostFromApiKey(credential);
146
+ return extractHostFromApiKey(credential, API_KEY_PREFIX);
147
+ }
148
+ const prefix = hostNamingTokenPrefix(credential);
149
+ if (prefix !== undefined) {
150
+ return extractHostFromApiKey(credential, prefix);
108
151
  }
109
152
  if (credential.startsWith(OPAQUE_ACCESS_TOKEN_PREFIX)) {
110
153
  throw new NoPlatformHostError();
@@ -114,9 +157,8 @@ export function extractPlatformHost(credential) {
114
157
  }
115
158
  throw new CredentialError('Invalid credential format');
116
159
  }
117
- function extractHostFromApiKey(apiKey) {
118
- // Remove pwt_ prefix
119
- const withoutPrefix = apiKey.slice(API_KEY_PREFIX.length);
160
+ function extractHostFromApiKey(apiKey, prefix) {
161
+ const withoutPrefix = apiKey.slice(prefix.length);
120
162
  // Split by dot
121
163
  const dotIndex = withoutPrefix.indexOf('.');
122
164
  if (dotIndex === -1) {
@@ -209,7 +251,7 @@ function extractHostFromToken(token) {
209
251
  * const client = Client.fromCredential(process.env.PW_API_KEY!)
210
252
  *
211
253
  * // Make requests
212
- * const { data, error } = await client.GET('/api/buckets')
254
+ * const { data, error } = await client.GET('/api/storage')
213
255
  * ```
214
256
  */
215
257
  export class Client {
@@ -221,7 +263,8 @@ export class Client {
221
263
  * Create a client using only a credential.
222
264
  *
223
265
  * The platform host is automatically extracted from the credential:
224
- * - For API keys: host is decoded from the first part after pwt_
266
+ * - For API keys and workflow run, instance and cluster session tokens: host
267
+ * is decoded from the first part after the prefix
225
268
  * - For JWT tokens: host is read from the platform_host claim
226
269
  * - For access tokens (pwoa_), which name no host: PW_PLATFORM_HOST, else
227
270
  * the server of the credentials file's selected context (Node.js only)
@@ -266,7 +309,7 @@ export class Client {
266
309
  * @example
267
310
  * ```ts
268
311
  * const client = Client.fromCredentialConfig()
269
- * const { data } = await client.GET('/api/buckets')
312
+ * const { data } = await client.GET('/api/storage')
270
313
  * ```
271
314
  */
272
315
  static fromCredentialConfig(options = {}) {
@@ -282,16 +325,16 @@ export class Client {
282
325
  ? client.withToken(identity.apikey)
283
326
  : client.withApiKey(identity.apikey);
284
327
  }
285
- if (!identity.token) {
286
- throw new CredentialError('you must first authenticate using "pw auth"');
287
- }
288
- if (identity.oauth) {
328
+ if (identity.oauth || identity.workload) {
289
329
  return client.withTokenProvider(new CLIAuth({
290
330
  command: cliCommand,
291
331
  context: name,
292
332
  timeoutMs: cliTimeoutMs,
293
333
  }));
294
334
  }
335
+ if (!identity.token) {
336
+ throw new CredentialError('you must first authenticate using "pw auth"');
337
+ }
295
338
  return client.withToken(identity.token);
296
339
  }
297
340
  /**
@@ -363,12 +406,13 @@ export class Client {
363
406
  */
364
407
  build() {
365
408
  const { acceptLanguage: language, ...options } = this.options;
366
- const acceptLanguage = language ??
367
- (typeof document === 'undefined' ? acceptLanguageFromEnv() : undefined);
409
+ const outsideBrowser = typeof document === 'undefined';
410
+ const acceptLanguage = language ?? (outsideBrowser ? acceptLanguageFromEnv() : undefined);
368
411
  const client = createClient({
369
412
  baseUrl: this.baseUrl,
370
413
  ...options,
371
414
  headers: {
415
+ ...(outsideBrowser && { 'User-Agent': USER_AGENT }),
372
416
  ...(acceptLanguage && { 'Accept-Language': acceptLanguage }),
373
417
  ...options.headers,
374
418
  ...(this.authHeader && { Authorization: this.authHeader }),
@@ -1,5 +1,6 @@
1
+ import { readFileSync } from 'node:fs';
1
2
  import { describe, expect, it } from 'vitest';
2
- import { acceptLanguageFromEnv, Client, problemMediaType, problemTypeUrl, toApiError, } from './index';
3
+ import { acceptLanguageFromEnv, CLUSTER_SESSION_TOKEN_PREFIX, Client, extractPlatformHost, INSTANCE_TOKEN_PREFIX, isToken, problemMediaType, problemTypeUrl, toApiError, USER_AGENT, } from './index';
3
4
  function respond(status, body, contentType) {
4
5
  const requests = [];
5
6
  const fetch = async (input) => {
@@ -22,6 +23,30 @@ async function failedRequest(status, body, contentType = problemMediaType) {
22
23
  return { error: toApiError(error), raw: error, request: requests[0] };
23
24
  }
24
25
  describe('Client', () => {
26
+ it('sends the version of the SDK as its User-Agent', async () => {
27
+ const { request } = await failedRequest(404, '{}');
28
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
29
+ expect(USER_AGENT).toBe(`parallelworks-typescript-sdk/${pkg.version}`);
30
+ expect(request.headers.get('User-Agent')).toBe(USER_AGENT);
31
+ });
32
+ it('sends a workflow run token to the host it names as a Bearer token', async () => {
33
+ const token = `pwwr_${btoa('run.example.com')}.${btoa('secret')}`;
34
+ expect(isToken(token)).toBe(true);
35
+ expect(extractPlatformHost(token)).toBe('run.example.com');
36
+ const { fetch, requests } = respond(200, '[]', 'application/json');
37
+ await Client.fromCredential(token, { fetch }).GET('/api/workflows');
38
+ expect(requests[0].url).toBe('https://run.example.com/api/workflows');
39
+ expect(requests[0].headers.get('Authorization')).toBe(`Bearer ${token}`);
40
+ });
41
+ it.each([INSTANCE_TOKEN_PREFIX, CLUSTER_SESSION_TOKEN_PREFIX])('sends a %s token to the host it names as a Bearer token', async (prefix) => {
42
+ const token = `${prefix}${btoa('agent.example.com')}.${btoa('secret')}`;
43
+ expect(isToken(token)).toBe(true);
44
+ expect(extractPlatformHost(token)).toBe('agent.example.com');
45
+ const { fetch, requests } = respond(200, '[]', 'application/json');
46
+ await Client.fromCredential(token, { fetch }).GET('/api/workflows');
47
+ expect(requests[0].url).toBe('https://agent.example.com/api/workflows');
48
+ expect(requests[0].headers.get('Authorization')).toBe(`Bearer ${token}`);
49
+ });
25
50
  it('asks for problem details in the chosen language', async () => {
26
51
  const { request } = await failedRequest(404, '{}');
27
52
  expect(request.headers.get('Accept')).toContain(problemMediaType);
@@ -33,7 +33,7 @@ type AuthenticatedClient = ReturnType<Client['withApiKey']>;
33
33
  *
34
34
  * // In your component
35
35
  * function BucketList() {
36
- * const { data, error, isLoading } = useQuery('/api/buckets')
36
+ * const { data, error, isLoading } = useQuery('/api/storage', { params: { query: { category: 'buckets' } } })
37
37
  *
38
38
  * if (isLoading) return <div>Loading...</div>
39
39
  * if (error) return <div>Error: {error.message}</div>
package/dist/swr/index.js CHANGED
@@ -31,7 +31,7 @@ export function hasStatus(error, status) {
31
31
  *
32
32
  * // In your component
33
33
  * function BucketList() {
34
- * const { data, error, isLoading } = useQuery('/api/buckets')
34
+ * const { data, error, isLoading } = useQuery('/api/storage', { params: { query: { category: 'buckets' } } })
35
35
  *
36
36
  * if (isLoading) return <div>Loading...</div>
37
37
  * if (error) return <div>Error: {error.message}</div>