@parallelworks/client 7.120.0 → 7.122.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.
@@ -0,0 +1,277 @@
1
+ import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync, } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import { delimiter, join, relative } from 'node:path';
4
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
5
+ import { Client, CLIAuth, CredentialError, isToken, loadCredentialConfig, NoPlatformHostError, resolveCommand, resolveIdentity, SignInExpiredError, } from './index';
6
+ let binDir;
7
+ let credDir;
8
+ let callLog;
9
+ function credentialsPath() {
10
+ return join(credDir, '.credentials');
11
+ }
12
+ function fakeCLI(body) {
13
+ const script = `#!/bin/sh\necho "$* key=\${PW_API_KEY:-unset}" >> ${callLog}\n${body}\n`;
14
+ writeFileSync(join(binDir, 'pw'), script);
15
+ chmodSync(join(binDir, 'pw'), 0o755);
16
+ }
17
+ function calls() {
18
+ return existsSync(callLog)
19
+ ? readFileSync(callLog, 'utf8').trim().split('\n')
20
+ : [];
21
+ }
22
+ function signIn(token, expiresInMs) {
23
+ return JSON.stringify({
24
+ currentIdentity: 'work',
25
+ identities: {
26
+ work: {
27
+ token,
28
+ server: 'work.example.com',
29
+ name: 'work',
30
+ organization: 'org',
31
+ oauth: {
32
+ clientId: 'pw-cli',
33
+ expiresAt: new Date(Date.now() + expiresInMs).toISOString(),
34
+ keychainAccount: 'work',
35
+ },
36
+ },
37
+ other: {
38
+ token: 'pwoa_other',
39
+ server: 'other.example.com',
40
+ name: 'other',
41
+ organization: 'org',
42
+ oauth: { expiresAt: new Date(Date.now() - 1000).toISOString() },
43
+ },
44
+ api: {
45
+ apikey: 'pwt_aG9zdA==.key',
46
+ server: 'api.example.com',
47
+ name: 'api',
48
+ organization: 'org',
49
+ },
50
+ },
51
+ });
52
+ }
53
+ function writeSignIn(token, expiresInMs) {
54
+ writeFileSync(credentialsPath(), signIn(token, expiresInMs));
55
+ }
56
+ // Prints a token response for token; no expiresIn leaves expires_in out.
57
+ function printScript(token, expiresIn) {
58
+ const response = { access_token: token, token_type: 'Bearer' };
59
+ return `echo '${JSON.stringify(expiresIn === undefined ? response : { ...response, expires_in: expiresIn })}'`;
60
+ }
61
+ function respond() {
62
+ const requests = [];
63
+ const fetch = async (input) => {
64
+ requests.push(input);
65
+ return new Response('[]', {
66
+ status: 200,
67
+ headers: { 'Content-Type': 'application/json' },
68
+ });
69
+ };
70
+ return { fetch, requests };
71
+ }
72
+ async function authorizations(client, requests, times = 1) {
73
+ for (let i = 0; i < times; i++) {
74
+ await client.GET('/api/workflows');
75
+ }
76
+ return requests.map(r => r.headers.get('Authorization'));
77
+ }
78
+ beforeEach(() => {
79
+ binDir = mkdtempSync(join(tmpdir(), 'pw-bin-'));
80
+ credDir = mkdtempSync(join(tmpdir(), 'pw-cred-'));
81
+ callLog = join(binDir, 'calls');
82
+ vi.stubEnv('PATH', `${binDir}${delimiter}${process.env['PATH']}`);
83
+ vi.stubEnv('PW_CREDENTIALS_DIR', credDir);
84
+ vi.stubEnv('PW_API_KEY', '');
85
+ vi.stubEnv('PW_CONTEXT', '');
86
+ vi.stubEnv('PW_PLATFORM_HOST', '');
87
+ });
88
+ afterEach(() => {
89
+ vi.unstubAllEnvs();
90
+ vi.useRealTimers();
91
+ vi.restoreAllMocks();
92
+ rmSync(binDir, { recursive: true, force: true });
93
+ rmSync(credDir, { recursive: true, force: true });
94
+ });
95
+ describe.skipIf(process.platform === 'win32')('Client.fromCredentialConfig', () => {
96
+ it('caches the token until it nears expiry', async () => {
97
+ writeSignIn('pwoa_stored', 3600000);
98
+ fakeCLI(printScript('pwoa_new', 3600));
99
+ const { fetch, requests } = respond();
100
+ const client = Client.fromCredentialConfig({ fetch });
101
+ vi.stubEnv('PW_API_KEY', 'pwt_leaked');
102
+ expect(await authorizations(client, requests, 3)).toEqual(Array(3).fill('Bearer pwoa_new'));
103
+ expect(new URL(requests[0].url).host).toBe('work.example.com');
104
+ expect(calls()).toEqual([
105
+ 'auth token --print -o json --context work key=unset',
106
+ ]);
107
+ });
108
+ it('renews the token before it expires', async () => {
109
+ writeSignIn('pwoa_stored', 3600000);
110
+ fakeCLI(printScript('pwoa_new', 3600));
111
+ const { fetch, requests } = respond();
112
+ const client = Client.fromCredentialConfig({ fetch });
113
+ await client.GET('/api/workflows');
114
+ vi.useFakeTimers({ toFake: ['Date'] });
115
+ vi.setSystemTime(Date.now() + 3570000);
116
+ fakeCLI(printScript('pwoa_newer', 3600));
117
+ expect(await authorizations(client, requests, 2)).toEqual([
118
+ 'Bearer pwoa_new',
119
+ 'Bearer pwoa_newer',
120
+ 'Bearer pwoa_newer',
121
+ ]);
122
+ expect(calls()).toHaveLength(2);
123
+ });
124
+ it('uses a token with no expiry for the life of the client', async () => {
125
+ writeSignIn('pwoa_stored', 3600000);
126
+ fakeCLI(printScript('pwoa_new'));
127
+ const { fetch, requests } = respond();
128
+ const client = Client.fromCredentialConfig({ fetch });
129
+ expect(await authorizations(client, requests, 3)).toEqual(Array(3).fill('Bearer pwoa_new'));
130
+ expect(calls()).toHaveLength(1);
131
+ });
132
+ it('asks the CLI for the context the SDK selected', async () => {
133
+ writeSignIn('pwoa_old', 3600000);
134
+ fakeCLI(printScript('pwoa_printed', 3600));
135
+ vi.stubEnv('PW_CONTEXT', 'work');
136
+ const { fetch, requests } = respond();
137
+ const client = Client.fromCredentialConfig({ fetch, context: 'other' });
138
+ expect(await authorizations(client, requests)).toEqual([
139
+ 'Bearer pwoa_printed',
140
+ ]);
141
+ expect(calls()).toEqual([
142
+ 'auth token --print -o json --context other key=unset',
143
+ ]);
144
+ });
145
+ it('keeps a token the CLI could not renew until it expires', async () => {
146
+ writeSignIn('pwoa_stored', 30000);
147
+ fakeCLI(printScript('pwoa_stored', 30));
148
+ const { fetch, requests } = respond();
149
+ const client = Client.fromCredentialConfig({ fetch });
150
+ expect(await authorizations(client, requests, 3)).toEqual(Array(3).fill('Bearer pwoa_stored'));
151
+ expect(calls()).toHaveLength(1);
152
+ });
153
+ it('uses the last token until it expires when the CLI fails', async () => {
154
+ fakeCLI(printScript('pwoa_new', 3600));
155
+ const auth = new CLIAuth({ context: 'work' });
156
+ expect(await auth.token()).toBe('pwoa_new');
157
+ fakeCLI('exit 1');
158
+ vi.useFakeTimers({ toFake: ['Date'] });
159
+ vi.setSystemTime(Date.now() + 3570000);
160
+ expect(await auth.token()).toBe('pwoa_new');
161
+ vi.setSystemTime(Date.now() + 60000);
162
+ await expect(auth.token()).rejects.toThrow(SignInExpiredError);
163
+ });
164
+ it('fails without the CLI', async () => {
165
+ writeSignIn('pwoa_stored', 3600000);
166
+ const { fetch } = respond();
167
+ const client = Client.fromCredentialConfig({
168
+ fetch,
169
+ cliCommand: join(binDir, 'missing-pw'),
170
+ });
171
+ await expect(client.GET('/api/workflows')).rejects.toThrow(SignInExpiredError);
172
+ });
173
+ it("surfaces the CLI's error", async () => {
174
+ fakeCLI("echo 'sign-in revoked' >&2\nexit 1");
175
+ const error = await new CLIAuth({ context: 'work' })
176
+ .token()
177
+ .catch((e) => e);
178
+ expect(error).toBeInstanceOf(SignInExpiredError);
179
+ expect(error.message).toContain('sign-in revoked');
180
+ });
181
+ it.each([
182
+ ['a bare token', 'echo pwoa_bare'],
183
+ ['no token', `echo '{"token_type":"Bearer"}'`],
184
+ [
185
+ 'another token type',
186
+ `echo '{"access_token":"pwoa_x","token_type":"mac"}'`,
187
+ ],
188
+ [
189
+ 'a spaced token',
190
+ `echo '{"access_token":"pwoa x","token_type":"Bearer"}'`,
191
+ ],
192
+ ])('rejects output with %s', async (_, body) => {
193
+ fakeCLI(body);
194
+ await expect(new CLIAuth().token()).rejects.toThrow(SignInExpiredError);
195
+ });
196
+ it('bounds a run of the CLI', async () => {
197
+ fakeCLI('exec sleep 5');
198
+ const auth = new CLIAuth({ context: 'work', timeoutMs: 100 });
199
+ await expect(auth.token()).rejects.toThrow('did not finish within 100ms');
200
+ });
201
+ it('refuses a pw found through a relative PATH entry', async () => {
202
+ fakeCLI(printScript('pwoa_new', 3600));
203
+ vi.stubEnv('PATH', relative(process.cwd(), binDir));
204
+ expect(() => resolveCommand('pw')).toThrow(/relative to the current directory/);
205
+ await expect(new CLIAuth().token()).rejects.toThrow(SignInExpiredError);
206
+ expect(calls()).toEqual([]);
207
+ vi.stubEnv('PATH', binDir);
208
+ expect(resolveCommand('pw')).toBe(join(binDir, 'pw'));
209
+ expect(resolveCommand('./pw')).toBe('./pw');
210
+ expect(() => resolveCommand('missing-pw')).toThrow(/not found on PATH/);
211
+ });
212
+ it('uses an API key context or PW_API_KEY as is', async () => {
213
+ fakeCLI('echo pwoa_unexpected');
214
+ writeSignIn('pwoa_stored', 3600000);
215
+ const { fetch, requests } = respond();
216
+ await Client.fromCredentialConfig({ fetch, context: 'api' }).GET('/api/workflows');
217
+ vi.stubEnv('PW_API_KEY', 'pwoa_explicit');
218
+ await Client.fromCredentialConfig({ fetch }).GET('/api/workflows');
219
+ expect(requests.map(r => r.headers.get('Authorization'))).toEqual([
220
+ `Basic ${btoa('pwt_aG9zdA==.key:')}`,
221
+ 'Bearer pwoa_explicit',
222
+ ]);
223
+ expect(new URL(requests[1].url).host).toBe('work.example.com');
224
+ expect(calls()).toEqual([]);
225
+ });
226
+ });
227
+ describe('credentials file', () => {
228
+ it('resolves PW_API_KEY, then the context option, PW_CONTEXT and the current context', () => {
229
+ writeSignIn('pwoa_stored', 3600000);
230
+ const config = loadCredentialConfig();
231
+ expect(resolveIdentity(config).context).toBe('work');
232
+ vi.stubEnv('PW_CONTEXT', 'other');
233
+ expect(resolveIdentity(config).context).toBe('other');
234
+ expect(resolveIdentity(config, { context: 'api' }).context).toBe('api');
235
+ expect(() => resolveIdentity(config, { context: 'nope' })).toThrow(CredentialError);
236
+ vi.stubEnv('PW_API_KEY', 'pwt_aG9zdA==.key');
237
+ expect(resolveIdentity(config)).toEqual({
238
+ context: '',
239
+ identity: {
240
+ apikey: 'pwt_aG9zdA==.key',
241
+ server: 'host',
242
+ name: '',
243
+ organization: '',
244
+ },
245
+ });
246
+ });
247
+ it('reads a missing or unparseable file as no contexts', () => {
248
+ expect(loadCredentialConfig().identities).toEqual({});
249
+ writeFileSync(credentialsPath(), '{not json');
250
+ vi.spyOn(console, 'warn').mockImplementation(() => { });
251
+ expect(loadCredentialConfig().identities).toEqual({});
252
+ });
253
+ it('reads the XDG path when PW_CREDENTIALS_DIR is unset', () => {
254
+ const xdg = join(credDir, 'xdg');
255
+ vi.stubEnv('PW_CREDENTIALS_DIR', '');
256
+ vi.stubEnv('XDG_CONFIG_HOME', xdg);
257
+ expect(loadCredentialConfig().path).toBe(join(xdg, 'pw', 'credentials'));
258
+ });
259
+ });
260
+ describe('access tokens', () => {
261
+ it('is a token that names no host', () => {
262
+ expect(isToken('pwoa_abc')).toBe(true);
263
+ expect(() => Client.fromCredential('pwoa_abc')).toThrow(NoPlatformHostError);
264
+ });
265
+ it('goes to PW_PLATFORM_HOST, else the selected context', async () => {
266
+ writeSignIn('pwoa_stored', 3600000);
267
+ const { fetch, requests } = respond();
268
+ await Client.fromCredential('pwoa_abc', { fetch }).GET('/api/workflows');
269
+ vi.stubEnv('PW_PLATFORM_HOST', 'env.example.com');
270
+ await Client.fromCredential('pwoa_abc', { fetch }).GET('/api/workflows');
271
+ expect(requests.map(r => new URL(r.url).host)).toEqual([
272
+ 'work.example.com',
273
+ 'env.example.com',
274
+ ]);
275
+ expect(requests[0].headers.get('Authorization')).toBe('Bearer pwoa_abc');
276
+ });
277
+ });
package/dist/index.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import { type ApiError } from '@parallelworks/problem';
2
2
  import createClient, { type ClientOptions as OpenAPIClientOptions } from 'openapi-fetch';
3
+ import { type ResolveOptions, type TokenProvider } from './credentials';
3
4
  import type { paths } from './types/api';
5
+ export * from './credentials';
4
6
  export type { paths };
5
7
  export type { components, operations } from './types/api';
6
8
  export { ApiError, codeForStatus, FieldError, fromResponseBody, problemMediaType, toApiError, } from '@parallelworks/problem';
@@ -12,6 +14,12 @@ export interface ClientOptions extends Omit<OpenAPIClientOptions, 'baseUrl'> {
12
14
  */
13
15
  acceptLanguage?: string;
14
16
  }
17
+ export interface CredentialConfigOptions extends ClientOptions, ResolveOptions {
18
+ /** The pw executable that renews a `pw auth` sign-in, looked up on PATH. */
19
+ cliCommand?: string | undefined;
20
+ /** Bounds each run of the pw CLI that renews a `pw auth` sign-in. */
21
+ cliTimeoutMs?: number | undefined;
22
+ }
15
23
  /**
16
24
  * The language of the POSIX locale environment (LC_ALL, then LC_MESSAGES,
17
25
  * then LANG) as a language tag: `ja_JP.UTF-8` is `ja-JP`. Undefined when none
@@ -26,14 +34,22 @@ export declare function problemTypeUrl(error: ApiError, baseUrl: string): string
26
34
  /** Prefix for Parallel Works API keys */
27
35
  export declare const API_KEY_PREFIX = "pwt_";
28
36
  /**
29
- * Prefix for opaque user tokens. Like an API key, a user token names its
30
- * platform host; like a JWT, it is sent as a Bearer token.
37
+ * Prefix for opaque access tokens, such as the one `pw auth` saves. Sent as a
38
+ * Bearer token; it names no platform host.
31
39
  */
32
- export declare const USER_TOKEN_PREFIX = "pwut_";
40
+ export declare const OPAQUE_ACCESS_TOKEN_PREFIX = "pwoa_";
33
41
  /** Error thrown when credential parsing fails */
34
42
  export declare class CredentialError extends Error {
35
43
  constructor(message: string);
36
44
  }
45
+ /** Raised when a credential names no platform host and nothing else supplies one. */
46
+ export declare class NoPlatformHostError extends CredentialError {
47
+ constructor(message?: string);
48
+ }
49
+ /** Raised when the pw CLI cannot provide a token for a `pw auth` sign-in and no earlier one is still valid. */
50
+ export declare class SignInExpiredError extends CredentialError {
51
+ constructor(cause: unknown);
52
+ }
37
53
  /**
38
54
  * Check if a credential is an API key.
39
55
  *
@@ -44,24 +60,22 @@ export declare class CredentialError extends Error {
44
60
  */
45
61
  export declare function isApiKey(credential: string): boolean;
46
62
  /**
47
- * Check if a credential is a token, sent as a Bearer token.
48
- *
49
- * Tokens are opaque user tokens (starting with "pwut_") or JWTs, which have
50
- * three base64-encoded parts separated by dots.
63
+ * 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.
51
65
  *
52
66
  * @param credential - The credential string to check
53
67
  * @returns True if the credential appears to be a token
54
68
  */
55
69
  export declare function isToken(credential: string): boolean;
56
70
  /**
57
- * Extract the platform host from an API key or token.
71
+ * Extract the platform host from an API key or JWT token.
58
72
  *
59
- * For API keys (pwt_xxxx.yyyy) and opaque user tokens (pwut_xxxx.yyyy): decodes
60
- * the first part after the prefix to get the host
73
+ * For API keys (pwt_xxxx.yyyy): decodes the first part after pwt_ to get the host
61
74
  * For JWT tokens: decodes the payload (second segment) and reads platform_host field
62
75
  *
63
- * @param credential - The API key or token
76
+ * @param credential - The API key or JWT token
64
77
  * @returns The platform host (e.g., "activate.parallel.works")
78
+ * @throws NoPlatformHostError for an opaque access token, which names no host
65
79
  * @throws CredentialError if the credential format is invalid
66
80
  */
67
81
  export declare function extractPlatformHost(credential: string): string;
@@ -72,13 +86,12 @@ export declare function extractPlatformHost(credential: string): string;
72
86
  * ```ts
73
87
  * import { Client } from '@parallelworks/client'
74
88
  *
75
- * // Using API Key (Basic Auth) - recommended for integrations
76
- * const client = new Client('https://activate.parallel.works')
77
- * .withApiKey('pwt_...')
89
+ * // Signed in with `pw auth`: the client asks the pw CLI to renew the token
90
+ * const client = Client.fromCredentialConfig()
78
91
  *
79
- * // Using Bearer Token (JWT) - for scripts
92
+ * // Using API Key (Basic Auth) - for unattended jobs such as CI
80
93
  * const client = new Client('https://activate.parallel.works')
81
- * .withToken('eyJ...')
94
+ * .withApiKey('pwt_...')
82
95
  *
83
96
  * // Or let the client extract the host from your credential
84
97
  * const client = Client.fromCredential(process.env.PW_API_KEY!)
@@ -90,16 +103,19 @@ export declare function extractPlatformHost(credential: string): string;
90
103
  export declare class Client {
91
104
  private baseUrl;
92
105
  private options;
93
- private authHeader?;
106
+ private authHeader;
107
+ private tokenProvider;
94
108
  constructor(baseUrl: string, options?: ClientOptions);
95
109
  /**
96
110
  * Create a client using only a credential.
97
111
  *
98
112
  * The platform host is automatically extracted from the credential:
99
- * - For API keys and opaque user tokens: host is decoded from the first part after the prefix
113
+ * - For API keys: host is decoded from the first part after pwt_
100
114
  * - For JWT tokens: host is read from the platform_host claim
115
+ * - For access tokens (pwoa_), which name no host: PW_PLATFORM_HOST, else
116
+ * the server of the credentials file's selected context (Node.js only)
101
117
  *
102
- * @param credential - Your API key or JWT token
118
+ * @param credential - Your API key or token
103
119
  * @param options - Additional client options
104
120
  * @returns Configured API client ready to make requests
105
121
  * @throws CredentialError if the credential format is invalid
@@ -111,6 +127,23 @@ export declare class Client {
111
127
  * ```
112
128
  */
113
129
  static fromCredential(credential: string, options?: ClientOptions): OpenAPIFetchClient;
130
+ /**
131
+ * Create a client from the pw credentials file (Node.js only), picking the
132
+ * credential as the CLI and the Go SDK do: PW_API_KEY, then the `context`
133
+ * option, PW_CONTEXT, and the file's current context.
134
+ *
135
+ * A context signed in with `pw auth` stays signed in: when its access token
136
+ * nears expiry the client runs `pw auth token --print` for a renewed one
137
+ * (see `CLIAuth`), so sign in once and let scripts run. Unattended jobs such
138
+ * as CI should use an API key in PW_API_KEY instead.
139
+ *
140
+ * @example
141
+ * ```ts
142
+ * const client = Client.fromCredentialConfig()
143
+ * const { data } = await client.GET('/api/buckets')
144
+ * ```
145
+ */
146
+ static fromCredentialConfig(options?: CredentialConfigOptions): OpenAPIFetchClient;
114
147
  /**
115
148
  * Authenticate with an API Key using Basic Auth
116
149
  *
@@ -122,12 +155,12 @@ export declare class Client {
122
155
  */
123
156
  withApiKey(apiKey: string): OpenAPIFetchClient;
124
157
  /**
125
- * Authenticate with a Bearer Token (JWT)
158
+ * Authenticate with a Bearer token, sent as is and never renewed.
126
159
  *
127
- * Best for scripts and CLI tools. Tokens expire after 24 hours.
128
- * Tokens can be generated from your ACTIVATE account settings.
160
+ * For a script, sign in once with `pw auth` and use `fromCredentialConfig`,
161
+ * which renews the token; for an unattended job such as CI, use an API key.
129
162
  *
130
- * @param token - Your JWT token from account settings
163
+ * @param token - A token, such as one `pw auth token --print` printed
131
164
  * @returns Configured API client ready to make requests
132
165
  */
133
166
  withToken(token: string): OpenAPIFetchClient;
@@ -137,10 +170,18 @@ export declare class Client {
137
170
  * Automatically detects whether the credential is an API key (starts with "pwt_")
138
171
  * or a token and configures the appropriate authentication method.
139
172
  *
140
- * @param credential - Your API key or JWT token
173
+ * @param credential - Your API key or token
141
174
  * @returns Configured API client ready to make requests
142
175
  */
143
176
  withCredential(credential: string): OpenAPIFetchClient;
177
+ /**
178
+ * Authenticate each request with a Bearer token the provider supplies, such
179
+ * as a `CLIAuth` that renews a `pw auth` sign-in.
180
+ *
181
+ * @param provider - Supplies the current token
182
+ * @returns Configured API client ready to make requests
183
+ */
184
+ withTokenProvider(provider: TokenProvider): OpenAPIFetchClient;
144
185
  /**
145
186
  * Build the openapi-fetch client with configured options.
146
187
  *