@work-shape/catalyst-api-client 0.8.0-rc.3 → 0.8.0-rc.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { z } from 'zod';
2
- import { ApiErrorCode, Operation, OperationPathParamName, OperationRequestHeader, apiOperations, ApiOperationName } from '@work-shape/catalyst-api-contract';
2
+ import { ApiErrorCode, LocaleCode, Operation, OperationPathParamName, OperationRequestHeader, apiOperations, ApiOperationName } from '@work-shape/catalyst-api-contract';
3
3
  export * from '@work-shape/catalyst-api-contract';
4
4
 
5
5
  /**
@@ -22,14 +22,64 @@ declare const authSessionSchema: z.ZodNullable<z.ZodObject<{
22
22
  type AuthSession = NonNullable<z.infer<typeof authSessionSchema>>;
23
23
  interface AuthResult {
24
24
  ok: boolean;
25
+ /** The sign-in library's code for a refusal, such as `INVALID_EMAIL_OR_PASSWORD`. */
26
+ code?: string;
25
27
  message?: string;
28
+ /** The HTTP status of a refusal; 429 is the instance's limit on attempts. */
29
+ status?: number;
30
+ }
31
+ /** The second factor of a sign-in: a code from the authenticator app, or a backup code. */
32
+ type SecondFactorKind = "app" | "backup";
33
+ /** A sign-in: refused, signed in, or waiting for the second factor (TWO-FACTOR-1). */
34
+ interface SignInResult extends AuthResult {
35
+ /** The password was right and the account asks for a code before there is a session. */
36
+ secondFactor?: true;
37
+ }
38
+ /** What an authenticator app reads, and the ten backup codes, shown once. */
39
+ interface TwoFactorSetup {
40
+ totpUri: string;
41
+ backupCodes: string[];
26
42
  }
27
43
  declare function getAuthSession(apiBaseUrl: string): Promise<AuthSession | null>;
28
44
  declare function signInWithEmail(input: {
29
45
  apiBaseUrl: string;
30
46
  email: string;
31
47
  password: string;
48
+ }): Promise<SignInResult>;
49
+ /**
50
+ * The second sign-in step: a code from the authenticator app, or a backup code, which signs in
51
+ * once. `trustBrowser` skips the code in this browser for 30 days from now.
52
+ */
53
+ declare function verifySecondFactor(input: {
54
+ apiBaseUrl: string;
55
+ code: string;
56
+ kind: SecondFactorKind;
57
+ trustBrowser?: boolean;
58
+ }): Promise<AuthResult>;
59
+ /**
60
+ * Starts the setup of two-factor sign-in with the password. The factor is on only after the
61
+ * first code from the app is confirmed with `verifySecondFactor`.
62
+ */
63
+ declare function startTwoFactorSetup(input: {
64
+ apiBaseUrl: string;
65
+ password: string;
66
+ }): Promise<AuthResult & {
67
+ setup?: TwoFactorSetup;
68
+ }>;
69
+ /** Turns two-factor sign-in off with the password; every trusted browser is forgotten. */
70
+ declare function turnOffTwoFactor(input: {
71
+ apiBaseUrl: string;
72
+ password: string;
32
73
  }): Promise<AuthResult>;
74
+ /** Replaces all ten backup codes with the password. The new ones are shown once. */
75
+ declare function regenerateBackupCodes(input: {
76
+ apiBaseUrl: string;
77
+ password: string;
78
+ }): Promise<AuthResult & {
79
+ backupCodes?: string[];
80
+ }>;
81
+ /** Every browser of the person asks for the code again at its next sign-in. */
82
+ declare function forgetTrustedBrowsers(apiBaseUrl: string): Promise<AuthResult>;
33
83
  /**
34
84
  * For a tool outside a browser, which keeps no cookies: signs in and returns a fetch that
35
85
  * carries the session cookie and the origin the instance trusts on every request.
@@ -50,6 +100,12 @@ declare function signOut(apiBaseUrl: string): Promise<void>;
50
100
  */
51
101
  declare class ApiError extends Error {
52
102
  readonly status: number;
103
+ /** Response location and category only; never response contents or URL credentials. */
104
+ responseInfo?: {
105
+ url: string;
106
+ contentType: string;
107
+ body: string;
108
+ };
53
109
  readonly code?: ApiErrorCode;
54
110
  readonly payload: unknown;
55
111
  readonly correlationId?: string;
@@ -73,6 +129,8 @@ declare class ApiResponseShapeError extends ApiError {
73
129
  readonly paths: readonly string[];
74
130
  constructor(status: number, cause: z.ZodError);
75
131
  }
132
+ /** Add diagnostics without retaining the response text, query parameters or credentials. */
133
+ declare function describeResponse(error: unknown, response: Response, url: string, text: string): unknown;
76
134
 
77
135
  interface ApiClientOptions {
78
136
  baseUrl: string;
@@ -82,6 +140,13 @@ interface ApiClientOptions {
82
140
  */
83
141
  getToken?: () => string | undefined | Promise<string | undefined>;
84
142
  fetchImpl?: typeof fetch;
143
+ /** Cancels this client's requests when its owning session ends. */
144
+ signal?: AbortSignal;
145
+ /**
146
+ * The language every request asks the server to answer in, read at each request. A browser's
147
+ * own Accept-Language names its settings, not the language a person chose in the interface.
148
+ */
149
+ locale?: LocaleCode;
85
150
  /** Only available without a token source; browser navigation cannot send a bearer token. */
86
151
  browserManagedDownloads?: boolean;
87
152
  /**
@@ -239,4 +304,4 @@ declare function listAll<Item>(readPage: (paging: {
239
304
  nextCursor?: string;
240
305
  }>): Promise<Item[]>;
241
306
 
242
- export { AUTH_MOUNT_PATH, type ApiClient, type ApiClientFor, type ApiClientOptions, ApiError, type ApiOperationMethods, ApiResponseShapeError, type AuthResult, type AuthSession, type OperationInput, type OperationOutcome, completedOutput, createApiClient, createApiClientFor, getAuthSession, listAll, refusalError, signInForSessionFetch, signInWithEmail, signOut, transportError, unreadableResponseError };
307
+ export { AUTH_MOUNT_PATH, type ApiClient, type ApiClientFor, type ApiClientOptions, ApiError, type ApiOperationMethods, ApiResponseShapeError, type AuthResult, type AuthSession, type OperationInput, type OperationOutcome, type SecondFactorKind, type SignInResult, type TwoFactorSetup, completedOutput, createApiClient, createApiClientFor, describeResponse, forgetTrustedBrowsers, getAuthSession, listAll, refusalError, regenerateBackupCodes, signInForSessionFetch, signInWithEmail, signOut, startTwoFactorSetup, transportError, turnOffTwoFactor, unreadableResponseError, verifySecondFactor };
package/dist/index.js CHANGED
@@ -6,9 +6,15 @@ var authSessionSchema = z.object({
6
6
  user: z.object({ id: z.string(), email: z.string(), name: z.string() })
7
7
  }).nullable();
8
8
  var authFailureSchema = z.object({
9
+ code: z.string().optional(),
9
10
  message: z.string().optional(),
10
11
  error: z.object({ message: z.string().optional() }).optional()
11
12
  });
13
+ var signInAnswerSchema = z.object({ twoFactorRedirect: z.boolean().optional() });
14
+ var twoFactorSetupSchema = z.object({
15
+ totpURI: z.string(),
16
+ backupCodes: z.array(z.string())
17
+ });
12
18
  async function getAuthSession(apiBaseUrl) {
13
19
  const response = await fetch(authUrl(apiBaseUrl, "/get-session"), {
14
20
  credentials: "include"
@@ -32,12 +38,64 @@ async function signInWithEmail(input) {
32
38
  })
33
39
  });
34
40
  if (response.ok) {
35
- return { ok: true };
41
+ const answer = signInAnswerSchema.safeParse(await response.json().catch(() => void 0));
42
+ return answer.data?.twoFactorRedirect === true ? { ok: true, secondFactor: true } : { ok: true };
43
+ }
44
+ return failureOf(response, "Sign in failed");
45
+ }
46
+ async function verifySecondFactor(input) {
47
+ const path = input.kind === "app" ? "/two-factor/verify-totp" : "/two-factor/verify-backup-code";
48
+ const response = await postAuth(input.apiBaseUrl, path, {
49
+ code: input.code.replaceAll(/\s/gu, ""),
50
+ trustDevice: input.trustBrowser === true
51
+ });
52
+ return response.ok ? { ok: true } : failureOf(response, "The code was not accepted");
53
+ }
54
+ async function startTwoFactorSetup(input) {
55
+ const response = await postAuth(input.apiBaseUrl, "/two-factor/enable", {
56
+ password: input.password
57
+ });
58
+ if (!response.ok) {
59
+ return failureOf(response, "Two-factor sign-in could not be set up");
60
+ }
61
+ const setup = twoFactorSetupSchema.parse(await response.json());
62
+ return { ok: true, setup: { totpUri: setup.totpURI, backupCodes: setup.backupCodes } };
63
+ }
64
+ async function turnOffTwoFactor(input) {
65
+ const response = await postAuth(input.apiBaseUrl, "/two-factor/disable", {
66
+ password: input.password
67
+ });
68
+ return response.ok ? { ok: true } : failureOf(response, "Two-factor sign-in stayed on");
69
+ }
70
+ async function regenerateBackupCodes(input) {
71
+ const response = await postAuth(input.apiBaseUrl, "/two-factor/generate-backup-codes", {
72
+ password: input.password
73
+ });
74
+ if (!response.ok) {
75
+ return failureOf(response, "No new backup codes were made");
36
76
  }
77
+ const { backupCodes } = twoFactorSetupSchema.pick({ backupCodes: true }).parse(await response.json());
78
+ return { ok: true, backupCodes };
79
+ }
80
+ async function forgetTrustedBrowsers(apiBaseUrl) {
81
+ const response = await postAuth(apiBaseUrl, "/two-factor/forget-trusted-browsers", {});
82
+ return response.ok ? { ok: true } : failureOf(response, "The browsers are still trusted");
83
+ }
84
+ function postAuth(apiBaseUrl, path, body) {
85
+ return fetch(authUrl(apiBaseUrl, path), {
86
+ method: "POST",
87
+ credentials: "include",
88
+ headers: { "content-type": "application/json" },
89
+ body: JSON.stringify(body)
90
+ });
91
+ }
92
+ async function failureOf(response, fallback) {
37
93
  const failure = authFailureSchema.safeParse(await response.json().catch(() => void 0));
38
94
  return {
39
95
  ok: false,
40
- message: failure.data?.message ?? failure.data?.error?.message ?? "Sign in failed"
96
+ status: response.status,
97
+ ...failure.data?.code === void 0 ? {} : { code: failure.data.code },
98
+ message: failure.data?.message ?? failure.data?.error?.message ?? fallback
41
99
  };
42
100
  }
43
101
  async function signInForSessionFetch(input) {
@@ -50,6 +108,12 @@ async function signInForSessionFetch(input) {
50
108
  if (!response.ok) {
51
109
  throw new Error(`Sign-in as '${input.email}' was refused with status ${response.status}`);
52
110
  }
111
+ const answer = signInAnswerSchema.safeParse(
112
+ await response.clone().json().catch(() => void 0)
113
+ );
114
+ if (answer.data?.twoFactorRedirect === true) {
115
+ throw new Error(`'${input.email}' signs in with a second factor; use an API key for this tool`);
116
+ }
53
117
  const cookie = response.headers.getSetCookie().map((value) => value.split(";", 1)[0]).join("; ");
54
118
  return (resource, init) => {
55
119
  const request = new Request(resource, init);
@@ -76,6 +140,8 @@ import {
76
140
  import { z as z2 } from "zod";
77
141
  var ApiError = class extends Error {
78
142
  status;
143
+ /** Response location and category only; never response contents or URL credentials. */
144
+ responseInfo;
79
145
  code;
80
146
  payload;
81
147
  correlationId;
@@ -143,6 +209,28 @@ function readRetryAfterSeconds(payload) {
143
209
  const parsed = z2.object({ error: z2.object({ details: rateLimitedDetailsSchema }) }).safeParse(payload);
144
210
  return parsed.success ? parsed.data.error.details.retryAfterSeconds : void 0;
145
211
  }
212
+ function describeResponse(error, response, url, text) {
213
+ if (!(error instanceof ApiError)) return error;
214
+ const address = new URL(response.url || url);
215
+ address.username = "";
216
+ address.password = "";
217
+ address.search = "";
218
+ address.hash = "";
219
+ const mediaType = response.headers.get("content-type")?.split(";")[0]?.trim();
220
+ const contentType = mediaType && /^[a-z0-9.+-]+\/[a-z0-9.+-]+$/iu.test(mediaType) ? mediaType : "unknown content type";
221
+ let body = "non-JSON text";
222
+ if (contentType === "text/html" || /^\s*(?:<!doctype html|<html)(?:\s|>)/iu.test(text)) {
223
+ body = "an HTML page instead of API JSON";
224
+ } else {
225
+ try {
226
+ JSON.parse(text);
227
+ body = "other JSON that does not match the API contract";
228
+ } catch {
229
+ }
230
+ }
231
+ error.responseInfo = { url: address.toString(), contentType, body };
232
+ return error;
233
+ }
146
234
 
147
235
  // src/client.ts
148
236
  import {
@@ -180,7 +268,9 @@ function readEventData(block) {
180
268
  }
181
269
 
182
270
  // src/transport.ts
183
- import { isUnknownOperationResponse } from "@work-shape/catalyst-api-contract";
271
+ import {
272
+ isUnknownOperationResponse
273
+ } from "@work-shape/catalyst-api-contract";
184
274
  function createApiTransport(options) {
185
275
  const baseUrl = options.baseUrl.replace(/\/$/u, "");
186
276
  const cookieMode = options.getToken === void 0;
@@ -213,9 +303,16 @@ function createApiTransport(options) {
213
303
  headers.set("catalyst-unattended", "1");
214
304
  }
215
305
  const token = await options.getToken?.();
306
+ const sessionSignal = options.signal;
307
+ const signal = sessionSignal && request.signal ? AbortSignal.any([sessionSignal, request.signal]) : sessionSignal ?? request.signal;
216
308
  if (token) {
217
309
  headers.set("authorization", `Bearer ${token}`);
218
310
  }
311
+ const locale = options.locale;
312
+ if (locale !== void 0) {
313
+ headers.set("accept-language", locale);
314
+ }
315
+ signal?.throwIfAborted();
219
316
  let response;
220
317
  try {
221
318
  response = await (options.fetchImpl ?? fetch)(url, {
@@ -223,10 +320,10 @@ function createApiTransport(options) {
223
320
  headers,
224
321
  body,
225
322
  credentials: cookieMode ? "include" : "omit",
226
- signal: request.signal
323
+ signal
227
324
  });
228
325
  } catch (error) {
229
- throw request.signal?.aborted ? error : transportError(error);
326
+ throw signal?.aborted ? error : transportError(error);
230
327
  }
231
328
  if (response.ok) {
232
329
  return response;
@@ -331,23 +428,27 @@ function callOperation(transport, operation, request) {
331
428
  return void 0;
332
429
  }
333
430
  const text = await readBody(() => answer.text(), request);
334
- if (!accepted) {
335
- return parseJson(transport, text, response.schema, answer.status);
431
+ try {
432
+ if (!accepted) {
433
+ return parseJson(transport, text, response.schema, answer.status);
434
+ }
435
+ const outcome = {
436
+ operationRunId: answer.headers.get("operation-run-id") ?? void 0,
437
+ replayed: answer.headers.get("idempotent-replayed") === "true"
438
+ };
439
+ return answer.status === 202 ? {
440
+ ...outcome,
441
+ status: "pending_approval",
442
+ run: parseJson(transport, text, accepted, answer.status),
443
+ location: answer.headers.get("location") ?? void 0
444
+ } : {
445
+ ...outcome,
446
+ status: "done",
447
+ output: parseJson(transport, text, response.schema, answer.status)
448
+ };
449
+ } catch (error) {
450
+ throw describeResponse(error, answer, transport.urlFor(operation, request), text);
336
451
  }
337
- const outcome = {
338
- operationRunId: answer.headers.get("operation-run-id") ?? void 0,
339
- replayed: answer.headers.get("idempotent-replayed") === "true"
340
- };
341
- return answer.status === 202 ? {
342
- ...outcome,
343
- status: "pending_approval",
344
- run: parseJson(transport, text, accepted, answer.status),
345
- location: answer.headers.get("location") ?? void 0
346
- } : {
347
- ...outcome,
348
- status: "done",
349
- output: parseJson(transport, text, response.schema, answer.status)
350
- };
351
452
  });
352
453
  }
353
454
  async function* streamEvents(transport, operation, response, request) {
@@ -422,12 +523,18 @@ export {
422
523
  completedOutput,
423
524
  createApiClient,
424
525
  createApiClientFor,
526
+ describeResponse,
527
+ forgetTrustedBrowsers,
425
528
  getAuthSession,
426
529
  listAll,
427
530
  refusalError,
531
+ regenerateBackupCodes,
428
532
  signInForSessionFetch,
429
533
  signInWithEmail,
430
534
  signOut,
535
+ startTwoFactorSetup,
431
536
  transportError,
432
- unreadableResponseError
537
+ turnOffTwoFactor,
538
+ unreadableResponseError,
539
+ verifySecondFactor
433
540
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@work-shape/catalyst-api-client",
3
- "version": "0.8.0-rc.3",
3
+ "version": "0.8.0-rc.30",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -29,7 +29,7 @@
29
29
  },
30
30
  "dependencies": {
31
31
  "zod": "4.4.3",
32
- "@work-shape/catalyst-api-contract": "0.8.0-rc.3"
32
+ "@work-shape/catalyst-api-contract": "0.8.0-rc.30"
33
33
  },
34
34
  "devDependencies": {
35
35
  "@types/node": "^24.13.1",