@parallelworks/client 7.120.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/README.md CHANGED
@@ -31,6 +31,21 @@ See the [examples](./examples) directory for complete runnable examples.
31
31
 
32
32
  ## Authentication
33
33
 
34
+ ### Signed In With `pw auth` (Node.js)
35
+
36
+ For scripts you run yourself, sign in once with `pw auth`, then create the client from the pw credentials file:
37
+
38
+ ```typescript
39
+ import { Client } from '@parallelworks/client'
40
+
41
+ const client = Client.fromCredentialConfig()
42
+ const { data } = await client.GET('/api/buckets')
43
+ ```
44
+
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.
46
+
47
+ For unattended jobs such as CI, use an API key in `PW_API_KEY` instead.
48
+
34
49
  ### Automatic Host Detection
35
50
 
36
51
  API keys (`pwt_...`) and JWT tokens contain the platform host encoded within them. Use `fromCredential` to automatically extract it:
@@ -43,6 +58,10 @@ const client = Client.fromCredential('pwt_Y2xvdWQucGFyYWxsZWwud29ya3M.xxxxx')
43
58
  // JWT token - host read from platform_host claim
44
59
  const client = Client.fromCredential('eyJhbGci...')
45
60
  // Connects to the host in the token's platform_host claim
61
+
62
+ // Access token (pwoa_...), which names no host: PW_PLATFORM_HOST, else the
63
+ // server of the credentials file's selected context (Node.js)
64
+ const client = Client.fromCredential(token)
46
65
  ```
47
66
 
48
67
  ### Explicit Host
@@ -50,13 +69,13 @@ const client = Client.fromCredential('eyJhbGci...')
50
69
  If you prefer to specify the host explicitly:
51
70
 
52
71
  ```typescript
53
- // API Key (Basic Auth) - best for long-running integrations
72
+ // API Key (Basic Auth) - best for unattended jobs such as CI
54
73
  const client = new Client('https://cloud.parallel.works')
55
74
  .withApiKey('pwt_...')
56
75
 
57
- // JWT Token (Bearer) - best for scripts, expires in 24h
76
+ // Bearer token, sent as is and never renewed
58
77
  const client = new Client('https://cloud.parallel.works')
59
- .withToken('eyJhbGci...')
78
+ .withToken(token)
60
79
 
61
80
  // Auto-detect credential type
62
81
  const client = new Client('https://cloud.parallel.works')
@@ -0,0 +1,89 @@
1
+ /** A saved context in the pw credentials file, as the CLI writes it. */
2
+ export interface Identity {
3
+ apikey?: string;
4
+ token?: string;
5
+ server: string;
6
+ name: string;
7
+ canonicalName?: string;
8
+ organization: string;
9
+ /** The state of a `pw auth` sign-in, which only the CLI reads. */
10
+ oauth?: Record<string, unknown>;
11
+ }
12
+ /** The pw credentials file. */
13
+ export interface CredentialConfig {
14
+ identities: Record<string, Identity>;
15
+ currentIdentity: string;
16
+ }
17
+ export interface ResolveOptions {
18
+ /** The context to use, over PW_CONTEXT and the current context. */
19
+ context?: string | undefined;
20
+ /** The platform host to use, over the context's server. */
21
+ platformHost?: string | undefined;
22
+ }
23
+ /** The pw executable CLIAuth runs, looked up on PATH. */
24
+ export declare const DEFAULT_CLI_COMMAND = "pw";
25
+ /** One minute, as the AWS SDK's credential_process provider bounds a run by default. */
26
+ export declare const DEFAULT_CLI_TIMEOUT_MS = 60000;
27
+ /**
28
+ * The credentials file path, ~/.config/pw/credentials (XDG_CONFIG_HOME moves
29
+ * it, PW_CREDENTIALS_DIR replaces its directory), as the CLI and Go SDK resolve it.
30
+ */
31
+ export declare function defaultCredentialConfigPath(): string;
32
+ /**
33
+ * Reads the credentials file, falling back to the legacy ~/pw/.credentials.
34
+ * A missing, empty or unparseable file reads as no contexts.
35
+ */
36
+ export declare function loadCredentialConfig(path?: string): CredentialConfig & {
37
+ path: string;
38
+ };
39
+ /**
40
+ * The identity a client authenticates as, and the context it came from (empty
41
+ * for PW_API_KEY): PW_API_KEY, then the context option, PW_CONTEXT, and the
42
+ * file's current context, as the CLI and Go SDK pick it.
43
+ */
44
+ export declare function resolveIdentity(config: CredentialConfig, options?: ResolveOptions): {
45
+ context: string;
46
+ identity: Identity;
47
+ };
48
+ /** The platform host for a credential that names none, or undefined outside Node.js. */
49
+ export declare function hostForUnnamedCredential(): string | undefined;
50
+ /** Supplies the Bearer token for each request. */
51
+ export interface TokenProvider {
52
+ token(): Promise<string>;
53
+ }
54
+ export interface CLIAuthOptions {
55
+ /** The pw executable, looked up on PATH unless it is a path. */
56
+ command?: string | undefined;
57
+ /** The context to print a token for; empty means the one the CLI picks. */
58
+ context?: string | undefined;
59
+ /** Bounds one run of the CLI. */
60
+ timeoutMs?: number | undefined;
61
+ }
62
+ /**
63
+ * Authenticates as a `pw auth` sign-in. It runs `pw auth token --print -o json`
64
+ * for a current access token instead of rotating the refresh token itself: the
65
+ * platform signs a device out when two clients rotate the same refresh token,
66
+ * and the CLI serializes its rotations across processes. Like a client-go exec
67
+ * credential plugin or an AWS credential_process, it reads the token and its
68
+ * lifetime from the command's stdout, an RFC 6749 section 5.1 token response,
69
+ * and caches the token in memory until it nears expiry.
70
+ */
71
+ export declare class CLIAuth implements TokenProvider {
72
+ private readonly options;
73
+ private cached;
74
+ private expiresAt;
75
+ private settled;
76
+ private pending;
77
+ constructor(options?: CLIAuthOptions);
78
+ token(): Promise<string>;
79
+ private usable;
80
+ private renew;
81
+ private run;
82
+ }
83
+ /**
84
+ * Finds command on PATH as Go's exec.LookPath does: a command that names a
85
+ * path is used as is, and a match through a relative PATH entry, such as the
86
+ * current directory, is refused. Windows' own lookup would search the current
87
+ * directory first.
88
+ */
89
+ export declare function resolveCommand(command: string): string;
@@ -0,0 +1,321 @@
1
+ import { CredentialError, extractPlatformHost, isToken, NoPlatformHostError, SignInExpiredError, } from './index';
2
+ function nodeProcess() {
3
+ return globalThis.process;
4
+ }
5
+ function env() {
6
+ return nodeProcess()?.env ?? {};
7
+ }
8
+ // getBuiltinModule rather than an import keeps this module loadable in a browser bundle.
9
+ function builtin(id) {
10
+ const get = nodeProcess()?.getBuiltinModule;
11
+ if (!get) {
12
+ throw new CredentialError(`reading pw credentials needs Node.js 20.16 or later (${id})`);
13
+ }
14
+ return get(id);
15
+ }
16
+ /** The pw executable CLIAuth runs, looked up on PATH. */
17
+ export const DEFAULT_CLI_COMMAND = 'pw';
18
+ /** One minute, as the AWS SDK's credential_process provider bounds a run by default. */
19
+ export const DEFAULT_CLI_TIMEOUT_MS = 60000;
20
+ // Inside the CLI's two-minute renewal window, so the CLI always renews a token the SDK asks it for.
21
+ const CLI_RENEW_MARGIN_MS = 60000;
22
+ /**
23
+ * The credentials file path, ~/.config/pw/credentials (XDG_CONFIG_HOME moves
24
+ * it, PW_CREDENTIALS_DIR replaces its directory), as the CLI and Go SDK resolve it.
25
+ */
26
+ export function defaultCredentialConfigPath() {
27
+ const path = builtin('node:path');
28
+ const override = env()['PW_CREDENTIALS_DIR'];
29
+ if (override) {
30
+ return path.join(override, '.credentials');
31
+ }
32
+ const xdg = env()['XDG_CONFIG_HOME'];
33
+ const base = xdg && path.isAbsolute(xdg)
34
+ ? xdg
35
+ : path.join(builtin('node:os').homedir(), '.config');
36
+ return path.join(base, 'pw', 'credentials');
37
+ }
38
+ function legacyCredentialConfigPath() {
39
+ return builtin('node:path').join(builtin('node:os').homedir(), 'pw', '.credentials');
40
+ }
41
+ /**
42
+ * Reads the credentials file, falling back to the legacy ~/pw/.credentials.
43
+ * A missing, empty or unparseable file reads as no contexts.
44
+ */
45
+ export function loadCredentialConfig(path) {
46
+ const fs = builtin('node:fs');
47
+ if (!path) {
48
+ path = defaultCredentialConfigPath();
49
+ if (!fs.existsSync(path) && !env()['PW_CREDENTIALS_DIR']) {
50
+ const legacy = legacyCredentialConfigPath();
51
+ if (fs.existsSync(legacy)) {
52
+ path = legacy;
53
+ }
54
+ }
55
+ }
56
+ const empty = { identities: {}, currentIdentity: '', path };
57
+ let data;
58
+ try {
59
+ data = fs.readFileSync(path, 'utf8');
60
+ }
61
+ catch (e) {
62
+ if (e.code === 'ENOENT') {
63
+ return empty;
64
+ }
65
+ throw e;
66
+ }
67
+ if (!data.trim()) {
68
+ return empty;
69
+ }
70
+ try {
71
+ const parsed = JSON.parse(data);
72
+ return {
73
+ identities: parsed.identities ?? {},
74
+ currentIdentity: parsed.currentIdentity ?? '',
75
+ path,
76
+ };
77
+ }
78
+ catch {
79
+ console.warn(`warning: credentials file (${path}) is unparseable, treating as missing; re-authenticate with 'pw auth' to recover`);
80
+ return empty;
81
+ }
82
+ }
83
+ /** The context the CLI uses too: the option, then PW_CONTEXT, then the current context. */
84
+ function selectedContext(config, override) {
85
+ return override || env()['PW_CONTEXT'] || config.currentIdentity;
86
+ }
87
+ /**
88
+ * The identity a client authenticates as, and the context it came from (empty
89
+ * for PW_API_KEY): PW_API_KEY, then the context option, PW_CONTEXT, and the
90
+ * file's current context, as the CLI and Go SDK pick it.
91
+ */
92
+ export function resolveIdentity(config, options = {}) {
93
+ const credential = env()['PW_API_KEY'];
94
+ if (credential) {
95
+ return {
96
+ context: '',
97
+ identity: identityFromCredential(config, credential, options),
98
+ };
99
+ }
100
+ const context = selectedContext(config, options.context);
101
+ if (!context) {
102
+ throw new CredentialError("no context configured; use 'pw auth' to authenticate");
103
+ }
104
+ const identity = config.identities[context];
105
+ if (!identity) {
106
+ throw new CredentialError(`context "${context}" not found`);
107
+ }
108
+ return {
109
+ context,
110
+ identity: options.platformHost
111
+ ? { ...identity, server: options.platformHost }
112
+ : { ...identity },
113
+ };
114
+ }
115
+ // A token that names no platform goes to PW_PLATFORM_HOST, else the selected context's server.
116
+ function identityFromCredential(config, credential, options) {
117
+ let host = options.platformHost;
118
+ if (!host) {
119
+ try {
120
+ host = extractPlatformHost(credential);
121
+ }
122
+ catch (e) {
123
+ if (!(e instanceof NoPlatformHostError)) {
124
+ throw e;
125
+ }
126
+ host =
127
+ env()['PW_PLATFORM_HOST'] ||
128
+ config.identities[selectedContext(config, options.context)]?.server;
129
+ if (!host) {
130
+ throw e;
131
+ }
132
+ }
133
+ }
134
+ const identity = { server: host, name: '', organization: '' };
135
+ if (isToken(credential)) {
136
+ identity.token = credential;
137
+ }
138
+ else {
139
+ identity.apikey = credential;
140
+ }
141
+ return identity;
142
+ }
143
+ /** The platform host for a credential that names none, or undefined outside Node.js. */
144
+ export function hostForUnnamedCredential() {
145
+ const fromEnv = env()['PW_PLATFORM_HOST'];
146
+ if (fromEnv) {
147
+ return fromEnv;
148
+ }
149
+ if (!nodeProcess()?.getBuiltinModule) {
150
+ return undefined;
151
+ }
152
+ const config = loadCredentialConfig();
153
+ return config.identities[selectedContext(config)]?.server || undefined;
154
+ }
155
+ /**
156
+ * Authenticates as a `pw auth` sign-in. It runs `pw auth token --print -o json`
157
+ * for a current access token instead of rotating the refresh token itself: the
158
+ * platform signs a device out when two clients rotate the same refresh token,
159
+ * and the CLI serializes its rotations across processes. Like a client-go exec
160
+ * credential plugin or an AWS credential_process, it reads the token and its
161
+ * lifetime from the command's stdout, an RFC 6749 section 5.1 token response,
162
+ * and caches the token in memory until it nears expiry.
163
+ */
164
+ export class CLIAuth {
165
+ constructor(options = {}) {
166
+ this.cached = '';
167
+ // A token the CLI could not renew is used until it expires rather than asking on every request.
168
+ this.settled = false;
169
+ this.options = options;
170
+ }
171
+ token() {
172
+ if (this.usable()) {
173
+ return Promise.resolve(this.cached);
174
+ }
175
+ this.pending ?? (this.pending = this.renew().finally(() => {
176
+ this.pending = undefined;
177
+ }));
178
+ return this.pending;
179
+ }
180
+ usable() {
181
+ if (!this.cached) {
182
+ return false;
183
+ }
184
+ if (this.expiresAt === undefined) {
185
+ return true;
186
+ }
187
+ if (this.settled) {
188
+ return Date.now() < this.expiresAt;
189
+ }
190
+ return this.expiresAt - Date.now() > CLI_RENEW_MARGIN_MS;
191
+ }
192
+ async renew() {
193
+ let printed;
194
+ try {
195
+ printed = await this.run();
196
+ }
197
+ catch (e) {
198
+ if (this.cached &&
199
+ this.expiresAt !== undefined &&
200
+ Date.now() < this.expiresAt) {
201
+ this.settled = true;
202
+ return this.cached;
203
+ }
204
+ throw new SignInExpiredError(e);
205
+ }
206
+ this.cached = printed.token;
207
+ this.expiresAt = printed.expiresAt;
208
+ this.settled =
209
+ this.expiresAt !== undefined &&
210
+ this.expiresAt - Date.now() <= CLI_RENEW_MARGIN_MS;
211
+ return this.cached;
212
+ }
213
+ run() {
214
+ const command = this.options.command || DEFAULT_CLI_COMMAND;
215
+ const timeout = this.options.timeoutMs || DEFAULT_CLI_TIMEOUT_MS;
216
+ const args = ['auth', 'token', '--print', '-o', 'json'];
217
+ if (this.options.context) {
218
+ args.push('--context', this.options.context);
219
+ }
220
+ const describe = [command, ...args].join(' ');
221
+ const file = resolveCommand(command);
222
+ // Without PW_API_KEY, which would make the CLI print it rather than the sign-in's token.
223
+ const { PW_API_KEY: _, ...childEnv } = env();
224
+ const { execFile } = builtin('node:child_process');
225
+ return new Promise((resolve, reject) => {
226
+ execFile(file, args, { env: childEnv, timeout, encoding: 'utf8' }, (error, stdout, stderr) => {
227
+ if (error) {
228
+ reject(cliFailure(describe, timeout, error, stderr));
229
+ return;
230
+ }
231
+ try {
232
+ resolve(parseTokenResponse(describe, stdout, Date.now()));
233
+ }
234
+ catch (e) {
235
+ reject(e);
236
+ }
237
+ });
238
+ });
239
+ }
240
+ }
241
+ function parseTokenResponse(describe, stdout, received) {
242
+ let response;
243
+ try {
244
+ response = JSON.parse(stdout);
245
+ }
246
+ catch (e) {
247
+ throw new Error(`${describe} printed no token response: ${e}`);
248
+ }
249
+ const token = response.access_token;
250
+ if (typeof token !== 'string' || !token || /\s/.test(token)) {
251
+ throw new Error(`${describe} printed no single access_token`);
252
+ }
253
+ if (typeof response.token_type !== 'string' ||
254
+ response.token_type.toLowerCase() !== 'bearer') {
255
+ throw new Error(`${describe} printed token_type ${JSON.stringify(response.token_type)}, want Bearer`);
256
+ }
257
+ const expiresIn = response.expires_in;
258
+ return {
259
+ token,
260
+ expiresAt: typeof expiresIn === 'number' ? received + expiresIn * 1000 : undefined,
261
+ };
262
+ }
263
+ /**
264
+ * Finds command on PATH as Go's exec.LookPath does: a command that names a
265
+ * path is used as is, and a match through a relative PATH entry, such as the
266
+ * current directory, is refused. Windows' own lookup would search the current
267
+ * directory first.
268
+ */
269
+ export function resolveCommand(command) {
270
+ const windows = nodeProcess()?.platform === 'win32';
271
+ if (command.includes('/') || (windows && /[\\:]/.test(command))) {
272
+ return command;
273
+ }
274
+ const fs = builtin('node:fs');
275
+ const path = builtin('node:path');
276
+ const extensions = windows ? windowsExtensions(command) : [''];
277
+ for (const dir of (env()['PATH'] ?? '').split(path.delimiter)) {
278
+ for (const ext of extensions) {
279
+ const candidate = path.join(dir || '.', command + ext);
280
+ if (!isExecutable(fs, candidate, windows)) {
281
+ continue;
282
+ }
283
+ if (!path.isAbsolute(candidate)) {
284
+ throw new CredentialError(`${command} resolves to ${candidate}, relative to the current directory; give the pw command as an absolute path to run it`);
285
+ }
286
+ return candidate;
287
+ }
288
+ }
289
+ throw new CredentialError(`${command}: not found on PATH`);
290
+ }
291
+ // The PATHEXT extensions to try, after the command as is when it already has one.
292
+ function windowsExtensions(command) {
293
+ const extensions = (env()['PATHEXT'] || '.COM;.EXE;.BAT;.CMD')
294
+ .split(';')
295
+ .filter(Boolean);
296
+ const named = extensions.some(ext => command.toLowerCase().endsWith(ext.toLowerCase()));
297
+ return named ? ['', ...extensions] : extensions;
298
+ }
299
+ function isExecutable(fs, file, windows) {
300
+ if (!fs.statSync(file, { throwIfNoEntry: false })?.isFile()) {
301
+ return false;
302
+ }
303
+ if (windows) {
304
+ return true;
305
+ }
306
+ try {
307
+ fs.accessSync(file, fs.constants.X_OK);
308
+ return true;
309
+ }
310
+ catch {
311
+ return false;
312
+ }
313
+ }
314
+ function cliFailure(describe, timeout, error, stderr) {
315
+ if (error.killed) {
316
+ return new Error(`${describe} did not finish within ${timeout}ms`);
317
+ }
318
+ const reason = error.code === 'ENOENT' ? 'not found' : `exit status ${error.code}`;
319
+ const detail = stderr.trim();
320
+ return new Error(`${describe}: ${reason}${detail ? `: ${detail}` : ''}`);
321
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -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
  *
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
@@ -32,10 +39,10 @@ export function problemTypeUrl(error, baseUrl) {
32
39
  /** Prefix for Parallel Works API keys */
33
40
  export const API_KEY_PREFIX = 'pwt_';
34
41
  /**
35
- * Prefix for opaque user tokens. Like an API key, a user token names its
36
- * platform host; like a JWT, it is sent as a Bearer token.
42
+ * Prefix for opaque access tokens, such as the one `pw auth` saves. Sent as a
43
+ * Bearer token; it names no platform host.
37
44
  */
38
- export const USER_TOKEN_PREFIX = 'pwut_';
45
+ export const OPAQUE_ACCESS_TOKEN_PREFIX = 'pwoa_';
39
46
  /** Error thrown when credential parsing fails */
40
47
  export class CredentialError extends Error {
41
48
  constructor(message) {
@@ -43,6 +50,20 @@ export class CredentialError extends Error {
43
50
  this.name = 'CredentialError';
44
51
  }
45
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
+ }
46
67
  /**
47
68
  * Check if a credential is an API key.
48
69
  *
@@ -55,52 +76,51 @@ export function isApiKey(credential) {
55
76
  return credential.trim().startsWith(API_KEY_PREFIX);
56
77
  }
57
78
  /**
58
- * Check if a credential is a token, sent as a Bearer token.
59
- *
60
- * Tokens are opaque user tokens (starting with "pwut_") or JWTs, which have
61
- * 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.
62
81
  *
63
82
  * @param credential - The credential string to check
64
83
  * @returns True if the credential appears to be a token
65
84
  */
66
85
  export function isToken(credential) {
67
86
  const trimmed = credential.trim();
68
- if (trimmed.startsWith(USER_TOKEN_PREFIX)) {
87
+ if (trimmed.startsWith(OPAQUE_ACCESS_TOKEN_PREFIX)) {
69
88
  return true;
70
89
  }
71
90
  const parts = trimmed.split('.');
72
91
  return parts.length === 3 && !trimmed.startsWith(API_KEY_PREFIX);
73
92
  }
74
93
  /**
75
- * Extract the platform host from an API key or token.
94
+ * Extract the platform host from an API key or JWT token.
76
95
  *
77
- * For API keys (pwt_xxxx.yyyy) and opaque user tokens (pwut_xxxx.yyyy): decodes
78
- * the first part after the prefix to get the host
96
+ * For API keys (pwt_xxxx.yyyy): decodes the first part after pwt_ to get the host
79
97
  * For JWT tokens: decodes the payload (second segment) and reads platform_host field
80
98
  *
81
- * @param credential - The API key or token
99
+ * @param credential - The API key or JWT token
82
100
  * @returns The platform host (e.g., "activate.parallel.works")
101
+ * @throws NoPlatformHostError for an opaque access token, which names no host
83
102
  * @throws CredentialError if the credential format is invalid
84
103
  */
85
104
  export function extractPlatformHost(credential) {
86
105
  credential = credential.trim();
87
106
  if (isApiKey(credential)) {
88
- return extractEncodedHost(credential, API_KEY_PREFIX);
107
+ return extractHostFromApiKey(credential);
89
108
  }
90
- if (credential.startsWith(USER_TOKEN_PREFIX)) {
91
- return extractEncodedHost(credential, USER_TOKEN_PREFIX);
109
+ if (credential.startsWith(OPAQUE_ACCESS_TOKEN_PREFIX)) {
110
+ throw new NoPlatformHostError();
92
111
  }
93
112
  if (isToken(credential)) {
94
113
  return extractHostFromToken(credential);
95
114
  }
96
115
  throw new CredentialError('Invalid credential format');
97
116
  }
98
- function extractEncodedHost(credential, prefix) {
99
- const withoutPrefix = credential.slice(prefix.length);
117
+ function extractHostFromApiKey(apiKey) {
118
+ // Remove pwt_ prefix
119
+ const withoutPrefix = apiKey.slice(API_KEY_PREFIX.length);
100
120
  // Split by dot
101
121
  const dotIndex = withoutPrefix.indexOf('.');
102
122
  if (dotIndex === -1) {
103
- throw new CredentialError('Invalid credential format');
123
+ throw new CredentialError('Invalid API key format');
104
124
  }
105
125
  const encodedHost = withoutPrefix.slice(0, dotIndex);
106
126
  // Decode base64 (handle both browser and Node.js)
@@ -127,11 +147,11 @@ function extractEncodedHost(credential, prefix) {
127
147
  }
128
148
  }
129
149
  catch (e) {
130
- throw new CredentialError(`Could not decode credential host: ${e}`);
150
+ throw new CredentialError(`Could not decode API key host: ${e}`);
131
151
  }
132
152
  }
133
153
  if (!host) {
134
- throw new CredentialError('No platform host in credential');
154
+ throw new CredentialError('No platform host in API key');
135
155
  }
136
156
  return host;
137
157
  }
@@ -178,13 +198,12 @@ function extractHostFromToken(token) {
178
198
  * ```ts
179
199
  * import { Client } from '@parallelworks/client'
180
200
  *
181
- * // Using API Key (Basic Auth) - recommended for integrations
182
- * const client = new Client('https://activate.parallel.works')
183
- * .withApiKey('pwt_...')
201
+ * // Signed in with `pw auth`: the client asks the pw CLI to renew the token
202
+ * const client = Client.fromCredentialConfig()
184
203
  *
185
- * // Using Bearer Token (JWT) - for scripts
204
+ * // Using API Key (Basic Auth) - for unattended jobs such as CI
186
205
  * const client = new Client('https://activate.parallel.works')
187
- * .withToken('eyJ...')
206
+ * .withApiKey('pwt_...')
188
207
  *
189
208
  * // Or let the client extract the host from your credential
190
209
  * const client = Client.fromCredential(process.env.PW_API_KEY!)
@@ -202,10 +221,12 @@ export class Client {
202
221
  * Create a client using only a credential.
203
222
  *
204
223
  * The platform host is automatically extracted from the credential:
205
- * - For API keys and opaque user tokens: host is decoded from the first part after the prefix
224
+ * - For API keys: host is decoded from the first part after pwt_
206
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)
207
228
  *
208
- * @param credential - Your API key or JWT token
229
+ * @param credential - Your API key or token
209
230
  * @param options - Additional client options
210
231
  * @returns Configured API client ready to make requests
211
232
  * @throws CredentialError if the credential format is invalid
@@ -217,12 +238,61 @@ export class Client {
217
238
  * ```
218
239
  */
219
240
  static fromCredential(credential, options = {}) {
220
- let host = extractPlatformHost(credential);
221
- // Ensure https:// prefix
222
- if (!host.startsWith('http://') && !host.startsWith('https://')) {
223
- host = `https://${host}`;
241
+ let host;
242
+ try {
243
+ host = extractPlatformHost(credential);
244
+ }
245
+ catch (e) {
246
+ const fallback = e instanceof NoPlatformHostError
247
+ ? hostForUnnamedCredential()
248
+ : undefined;
249
+ if (!fallback) {
250
+ throw e;
251
+ }
252
+ host = fallback;
224
253
  }
225
- return new Client(host, options).withCredential(credential);
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);
226
296
  }
227
297
  /**
228
298
  * Authenticate with an API Key using Basic Auth
@@ -241,20 +311,22 @@ export class Client {
241
311
  ? btoa(`${apiKey}:`)
242
312
  : Buffer.from(`${apiKey}:`).toString('base64');
243
313
  this.authHeader = `Basic ${encoded}`;
314
+ this.tokenProvider = undefined;
244
315
  return this.build();
245
316
  }
246
317
  /**
247
- * Authenticate with a Bearer Token (JWT)
318
+ * Authenticate with a Bearer token, sent as is and never renewed.
248
319
  *
249
- * Best for scripts and CLI tools. Tokens expire after 24 hours.
250
- * 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.
251
322
  *
252
- * @param token - Your JWT token from account settings
323
+ * @param token - A token, such as one `pw auth token --print` printed
253
324
  * @returns Configured API client ready to make requests
254
325
  */
255
326
  withToken(token) {
256
327
  // Trim whitespace to handle env vars with trailing newlines
257
328
  this.authHeader = `Bearer ${token.trim()}`;
329
+ this.tokenProvider = undefined;
258
330
  return this.build();
259
331
  }
260
332
  /**
@@ -263,7 +335,7 @@ export class Client {
263
335
  * Automatically detects whether the credential is an API key (starts with "pwt_")
264
336
  * or a token and configures the appropriate authentication method.
265
337
  *
266
- * @param credential - Your API key or JWT token
338
+ * @param credential - Your API key or token
267
339
  * @returns Configured API client ready to make requests
268
340
  */
269
341
  withCredential(credential) {
@@ -272,6 +344,18 @@ export class Client {
272
344
  }
273
345
  return this.withToken(credential);
274
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
+ }
275
359
  /**
276
360
  * Build the openapi-fetch client with configured options.
277
361
  *
@@ -290,6 +374,15 @@ export class Client {
290
374
  ...(this.authHeader && { Authorization: this.authHeader }),
291
375
  },
292
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
+ }
293
386
  client.use(problemMiddleware);
294
387
  // Attach HTTP status code to error response bodies so consumers
295
388
  // (e.g. SWR hooks) can distinguish 404s from other errors.
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, it } from 'vitest';
2
- import { acceptLanguageFromEnv, Client, extractPlatformHost, isApiKey, isToken, problemMediaType, problemTypeUrl, toApiError, USER_TOKEN_PREFIX, } from './index';
2
+ import { acceptLanguageFromEnv, Client, problemMediaType, problemTypeUrl, toApiError, } from './index';
3
3
  function respond(status, body, contentType) {
4
4
  const requests = [];
5
5
  const fetch = async (input) => {
@@ -106,22 +106,3 @@ describe('acceptLanguageFromEnv', () => {
106
106
  expect(acceptLanguageFromEnv(env)).toBe(want);
107
107
  });
108
108
  });
109
- describe('opaque user tokens', () => {
110
- const token = `${USER_TOKEN_PREFIX}${btoa('activate.parallel.works')}.${btoa('raw')}`;
111
- it('is a token, not an API key', () => {
112
- expect(isToken(token)).toBe(true);
113
- expect(isApiKey(token)).toBe(false);
114
- });
115
- it('names its platform host', () => {
116
- expect(extractPlatformHost(token)).toBe('activate.parallel.works');
117
- expect(() => extractPlatformHost(`${USER_TOKEN_PREFIX}no-dot`)).toThrow();
118
- });
119
- it('is sent as a Bearer token to the host it names', async () => {
120
- const { fetch, requests } = respond(200, '[]', 'application/json');
121
- const client = Client.fromCredential(token, { fetch });
122
- await client.GET('/api/workflows');
123
- const request = requests[0];
124
- expect(new URL(request.url).host).toBe('activate.parallel.works');
125
- expect(request.headers.get('Authorization')).toBe(`Bearer ${token}`);
126
- });
127
- });
@@ -2654,9 +2654,12 @@ export interface paths {
2654
2654
  };
2655
2655
  /**
2656
2656
  * Generate a user token
2657
+ * @deprecated
2657
2658
  * @description > This is a user-centric route, so the response will always be in the context of the currently authenticated user.
2658
2659
  *
2659
2660
  * Generates a token for the authenticated user. The token can be used for API authentication.
2661
+ *
2662
+ * This route is deprecated: sign in with `pw auth login` instead, and use an API key for automation.
2660
2663
  */
2661
2664
  get: operations["get-auth-token"];
2662
2665
  put?: never;
@@ -22365,10 +22368,15 @@ export interface components {
22365
22368
  CreateAPIKeyInputBody: {
22366
22369
  /** @description Budget allocation name (required for AI keys) */
22367
22370
  allocation?: string;
22368
- /** @description Days before the key expires, at most the organization's maximum API key lifetime, which is 730 days when no policy sets it. Empty or 0 creates a key that does not expire, which only an Unlimited policy allows. */
22371
+ /** @description Days before the key expires, at most the organization's maximum API key lifetime, which is 730 days when no policy sets it. Empty or 0 creates a key that does not expire, which only an Unlimited policy allows. Not allowed with expiresIn. */
22369
22372
  duration?: string;
22370
- /** @description Display name for the API key */
22371
- title: string;
22373
+ /**
22374
+ * Format: int64
22375
+ * @description Seconds before the key expires, as in OAuth 2.0 expires_in, for lifetimes that are not whole days. At least 900 (15 minutes) and at most the organization's maximum API key lifetime. Not allowed with duration.
22376
+ */
22377
+ expiresIn?: number;
22378
+ /** @description Display name for the API key, unique among your keys. When omitted, the key is named token-YYYYMMDD-HHMMSS-xxxx, the time in UTC with a random suffix. */
22379
+ title?: string;
22372
22380
  /**
22373
22381
  * @description Key type
22374
22382
  * @default platform
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parallelworks/client",
3
- "version": "7.120.0",
3
+ "version": "7.121.0",
4
4
  "description": "Official TypeScript client for Parallel Works ACTIVATE API",
5
5
  "type": "module",
6
6
  "exports": {