axiam-sdk 1.1.1 → 1.1.2

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.
Files changed (42) hide show
  1. package/README.md +20 -4
  2. package/dist/browser/index.d.cts +1 -1
  3. package/dist/browser/index.d.ts +1 -1
  4. package/dist/{client-D34sXV8p.d.cts → client-BGFn1VQh.d.cts} +7 -1
  5. package/dist/{client-BMNQi36J.d.ts → client-DrQZZ1js.d.ts} +7 -1
  6. package/dist/{cookieJar-DcrMe93Q.d.ts → cookieJar-BTmpjXZe.d.ts} +8 -2
  7. package/dist/{cookieJar-C_xPuniu.d.cts → cookieJar-BqYOnNN-.d.cts} +8 -2
  8. package/dist/grpc/index.d.cts +4 -4
  9. package/dist/grpc/index.d.ts +4 -4
  10. package/dist/grpc/index.js +32 -2
  11. package/dist/grpc/index.js.map +1 -1
  12. package/dist/grpc/index.mjs +32 -2
  13. package/dist/grpc/index.mjs.map +1 -1
  14. package/dist/index.d.cts +2 -2
  15. package/dist/index.d.ts +2 -2
  16. package/dist/index.js +24 -2
  17. package/dist/index.js.map +1 -1
  18. package/dist/index.mjs +24 -2
  19. package/dist/index.mjs.map +1 -1
  20. package/dist/middleware/index.d.cts +3 -3
  21. package/dist/middleware/index.d.ts +3 -3
  22. package/dist/middleware/index.js +149 -22
  23. package/dist/middleware/index.js.map +1 -1
  24. package/dist/middleware/index.mjs +149 -22
  25. package/dist/middleware/index.mjs.map +1 -1
  26. package/dist/node/index.d.cts +3 -3
  27. package/dist/node/index.d.ts +3 -3
  28. package/dist/node/index.js +178 -23
  29. package/dist/node/index.js.map +1 -1
  30. package/dist/node/index.mjs +178 -23
  31. package/dist/node/index.mjs.map +1 -1
  32. package/dist/{oidcState-BFIHt7_Y.d.cts → oidcState-BaJ-SM_R.d.cts} +37 -6
  33. package/dist/{oidcState-qoy2vsYG.d.ts → oidcState-C3VLn3eD.d.ts} +37 -6
  34. package/dist/rest/index.d.cts +3 -3
  35. package/dist/rest/index.d.ts +3 -3
  36. package/dist/rest/index.js +24 -2
  37. package/dist/rest/index.js.map +1 -1
  38. package/dist/rest/index.mjs +24 -2
  39. package/dist/rest/index.mjs.map +1 -1
  40. package/dist/{session-BbPFTpMZ.d.ts → session-B03NsqVs.d.ts} +16 -0
  41. package/dist/{session-C9WlP6DV.d.cts → session-plDr4lFu.d.cts} +16 -0
  42. package/package.json +1 -1
@@ -1424,7 +1424,7 @@ function delayMs(attempt, retryAfterMs2, fraction) {
1424
1424
  return retryAfterMs2 === void 0 ? jittered : Math.max(jittered, retryAfterMs2);
1425
1425
  }
1426
1426
  async function withRetry(fn, options) {
1427
- const retryable = options.enabled !== false;
1427
+ const retryable = options.idempotent && options.enabled !== false;
1428
1428
  const maxAttempts = retryable ? MAX_ATTEMPTS : 1;
1429
1429
  const sleep2 = options.sleepFn ?? defaultSleep;
1430
1430
  const random = options.randomFn ?? Math.random;
@@ -1438,6 +1438,7 @@ async function withRetry(fn, options) {
1438
1438
  }
1439
1439
  const retryAfterMs2 = isRetryAfterCarrier(err) ? err.retryAfterMs : void 0;
1440
1440
  const delay = delayMs(attempt, retryAfterMs2, random());
1441
+ options.admit?.(delay);
1441
1442
  options.telemetry?.emit({
1442
1443
  type: "retry",
1443
1444
  operation: options.operation ?? "unknown",
@@ -1500,6 +1501,8 @@ var MAX_LOGOUT_TOKEN_AGE_SECS = 300;
1500
1501
  var PollSchedule = class {
1501
1502
  #intervalSecs;
1502
1503
  #remainingSecs;
1504
+ /** A `Retry-After` still to be served by the next wait (§14.2 rule 9, contract 1.64). */
1505
+ #retryAfterSecs = 0;
1503
1506
  constructor(intervalSecs, expiresInSecs) {
1504
1507
  this.#intervalSecs = intervalSecs > 0 ? intervalSecs : DEFAULT_POLL_INTERVAL_SECS;
1505
1508
  this.#remainingSecs = expiresInSecs;
@@ -1508,6 +1511,21 @@ var PollSchedule = class {
1508
1511
  get intervalSecs() {
1509
1512
  return this.#intervalSecs;
1510
1513
  }
1514
+ /**
1515
+ * The delay before the next poll, in seconds: the interval, or the pending
1516
+ * `Retry-After` when that is longer (a minimum, §14.2 rule 9).
1517
+ */
1518
+ get waitSecs() {
1519
+ return Math.max(this.#intervalSecs, this.#retryAfterSecs);
1520
+ }
1521
+ /**
1522
+ * Record a `429 rate_limit_exceeded` (§14.2 rule 9, contract 1.64): the next
1523
+ * wait lasts at least `retryAfterSecs` and stands in for one interval. The
1524
+ * interval itself is **not** raised — only the `400 slow_down` does that.
1525
+ */
1526
+ rateLimited(retryAfterSecs) {
1527
+ this.#retryAfterSecs = retryAfterSecs !== void 0 && retryAfterSecs > 0 ? retryAfterSecs : 0;
1528
+ }
1511
1529
  /** Apply one `slow_down` (§14.2 rule 1): **cumulative, never reset.** */
1512
1530
  slowDown() {
1513
1531
  this.#intervalSecs += SLOW_DOWN_INCREMENT_SECS;
@@ -1520,14 +1538,27 @@ var PollSchedule = class {
1520
1538
  * the server is still answering `authorization_pending`.
1521
1539
  */
1522
1540
  tick() {
1523
- if (this.#intervalSecs >= this.#remainingSecs) {
1541
+ const waitSecs = this.waitSecs;
1542
+ this.#retryAfterSecs = 0;
1543
+ if (waitSecs >= this.#remainingSecs) {
1524
1544
  this.#remainingSecs = 0;
1525
1545
  return false;
1526
1546
  }
1527
- this.#remainingSecs -= this.#intervalSecs;
1547
+ this.#remainingSecs -= waitSecs;
1528
1548
  return true;
1529
1549
  }
1530
1550
  };
1551
+ var POLL_RETRY_AFTER_MS = /* @__PURE__ */ new WeakMap();
1552
+ function pollRateLimit(err) {
1553
+ if (axiosStatus(err) !== 429) return void 0;
1554
+ const body = axiosBody(err);
1555
+ const description = body !== null && typeof body === "object" && typeof body.error_description === "string" ? body.error_description : "";
1556
+ const limited = new OAuthProtocolError("rate_limit_exceeded", description);
1557
+ const response = err.response;
1558
+ const retryAfter = response ? retryAfterMs(response) : void 0;
1559
+ if (retryAfter !== void 0) POLL_RETRY_AFTER_MS.set(limited, retryAfter);
1560
+ return limited;
1561
+ }
1531
1562
  function sleep(ms) {
1532
1563
  return new Promise((resolve) => {
1533
1564
  setTimeout(resolve, ms);
@@ -1661,6 +1692,19 @@ function transient(error) {
1661
1692
  return error;
1662
1693
  }
1663
1694
  var SYSTEM_CIBA_CLOCK = { now: () => Date.now(), sleep };
1695
+ function deadlineBoundedRetry(bound, what) {
1696
+ return {
1697
+ admit: (ms) => {
1698
+ if (bound.clock.now() + ms >= bound.deadline) {
1699
+ throw new OAuthProtocolError(
1700
+ "expired_token",
1701
+ `the ${what} expired before it was decided (client-side deadline from expires_in; CONTRACT.md \xA714.2 rule 4, \xA734.2 P10)`
1702
+ );
1703
+ }
1704
+ },
1705
+ sleepFn: (ms) => bound.clock.sleep(ms)
1706
+ };
1707
+ }
1664
1708
  function isAccessDenied(err) {
1665
1709
  return err instanceof OAuthProtocolError && err.error === "access_denied";
1666
1710
  }
@@ -2445,26 +2489,36 @@ var OidcClient = class {
2445
2489
  * The raw single call, so an application driving its own loop (a UI
2446
2490
  * rendering a countdown, say) can. The five RFC 8628 §3.5 answers surface as
2447
2491
  * {@link OAuthProtocolError} — `authorization_pending` and `slow_down`
2448
- * included — so a hand-rolled loop sees exactly what {@link deviceLogin}
2449
- * sees. Most callers want {@link deviceLogin}.
2492
+ * included — so a hand-rolled loop dispatches on the same answers
2493
+ * {@link deviceLogin} does. Most callers want {@link deviceLogin}.
2450
2494
  *
2451
2495
  * Client authentication is the one {@link deviceAuthorize} describes
2452
2496
  * (contract 1.62, §14.1 rule 2): a configured `clientSecret` is sent as
2453
2497
  * `client_secret` in the form body, never as `Authorization: Basic`; a public
2454
2498
  * client sends none; `client_id` is sent on **every** poll (§14.1 rule 3). A
2455
2499
  * `401 invalid_client` surfaces as {@link OAuthProtocolError}, is not retried
2456
- * and does not enter the §9 refresh guard (§14.2 rule 5). This SDK ships no
2500
+ * and does not enter the §9 refresh guard (§14.2 rule 5). Any `429`
2501
+ * is an {@link OAuthProtocolError} with `error == 'rate_limit_exceeded'` too
2502
+ * (rule 9, whatever its body names) — never `slow_down`; {@link deviceLogin}
2503
+ * waits it out. Its `Retry-After` is not exposed, so a hand-rolled loop
2504
+ * should wait at least one interval on it without raising the interval, or
2505
+ * use {@link deviceLogin}. This SDK ships no
2457
2506
  * DPoP proof generator, so it cannot drive a client registered for DPoP; it
2458
2507
  * surfaces that client's refusal as the same `invalid_client`.
2459
2508
  */
2460
2509
  async devicePoll(params) {
2510
+ return this.#devicePoll(params, void 0);
2511
+ }
2512
+ /** {@link devicePoll}; `bound` is the loop's deadline, which a §16 retry inside the poll must not pass. */
2513
+ async #devicePoll(params, bound) {
2461
2514
  const configuration = params.configuration ?? await this.oidcDiscover();
2462
2515
  const form = new URLSearchParams();
2463
2516
  form.set("grant_type", DEVICE_CODE_GRANT_TYPE);
2464
2517
  form.set("device_code", exposeSecret(params.deviceCode));
2465
2518
  form.set("client_id", this.#options.clientId);
2466
2519
  this.#appendClientSecret(form);
2467
- const wire = await this.#postToken(configuration, form, params.tenantId);
2520
+ const url = this.#endpointUrl(this.#requiredEndpoint(configuration, "token_endpoint"), params.tenantId);
2521
+ const wire = await this.#postDevicePoll(url, form, bound);
2468
2522
  return this.#toTokenSet(wire, configuration, void 0);
2469
2523
  }
2470
2524
  /**
@@ -2485,31 +2539,44 @@ var OidcClient = class {
2485
2539
  * even if the server has not yet said `expired_token`. A 5xx or transport
2486
2540
  * failure mid-poll is **not** terminal (rule 6) — the loop absorbs it and
2487
2541
  * tries again, bounded by the same deadline, because a server restart must
2488
- * not lose a grant the user has already approved.
2542
+ * not lose a grant the user has already approved: that bound holds for the
2543
+ * §16 retry inside a poll too, whose waits are served on the loop's clock and
2544
+ * never reach the deadline (`Retry-After` included; the typed `expired_token`
2545
+ * is raised at once, C164-36). A `429
2546
+ * rate_limit_exceeded` (rule 9, contract 1.64) is not terminal either: the
2547
+ * loop waits `Retry-After` as a minimum (capped at the `expires_in`
2548
+ * deadline), counts the wait as one interval, does **not** raise the
2549
+ * interval, and polls again.
2489
2550
  */
2490
2551
  async deviceLogin(params) {
2491
2552
  const configuration = params.configuration ?? await this.oidcDiscover();
2553
+ const clock = params.clock ?? SYSTEM_CIBA_CLOCK;
2492
2554
  const authorization = await this.deviceAuthorize({
2493
2555
  ...params.scope !== void 0 ? { scope: params.scope } : {},
2494
2556
  ...params.tenantId !== void 0 ? { tenantId: params.tenantId } : {},
2495
2557
  configuration
2496
2558
  });
2559
+ const deadline = clock.now() + authorization.expiresIn * 1e3;
2497
2560
  await params.onUserCode(authorization);
2498
2561
  const schedule = new PollSchedule(authorization.interval, authorization.expiresIn);
2499
2562
  for (; ; ) {
2500
- if (!schedule.tick()) {
2563
+ const waitSecs = schedule.waitSecs;
2564
+ if (!schedule.tick() || clock.now() + waitSecs * 1e3 >= deadline) {
2501
2565
  throw new OAuthProtocolError(
2502
2566
  "expired_token",
2503
2567
  "the device authorization expired before the user completed it (client-side deadline from expires_in; CONTRACT.md \xA714.2 rule 4)"
2504
2568
  );
2505
2569
  }
2506
- await sleep(schedule.intervalSecs * 1e3);
2570
+ await clock.sleep(waitSecs * 1e3);
2507
2571
  try {
2508
- return await this.devicePoll({
2509
- deviceCode: authorization.deviceCode,
2510
- ...params.tenantId !== void 0 ? { tenantId: params.tenantId } : {},
2511
- configuration
2512
- });
2572
+ return await this.#devicePoll(
2573
+ {
2574
+ deviceCode: authorization.deviceCode,
2575
+ ...params.tenantId !== void 0 ? { tenantId: params.tenantId } : {},
2576
+ configuration
2577
+ },
2578
+ { deadline, clock }
2579
+ );
2513
2580
  } catch (err) {
2514
2581
  if (err instanceof OAuthProtocolError) {
2515
2582
  if (err.error === "authorization_pending") {
@@ -2519,6 +2586,11 @@ var OidcClient = class {
2519
2586
  schedule.slowDown();
2520
2587
  continue;
2521
2588
  }
2589
+ if (err.error === "rate_limit_exceeded") {
2590
+ const pollWaitMs = POLL_RETRY_AFTER_MS.get(err);
2591
+ schedule.rateLimited(pollWaitMs === void 0 ? void 0 : pollWaitMs / 1e3);
2592
+ continue;
2593
+ }
2522
2594
  throw err;
2523
2595
  }
2524
2596
  if (err instanceof NetworkError) {
@@ -3039,6 +3111,10 @@ var OidcClient = class {
3039
3111
  * this client's credential.
3040
3112
  */
3041
3113
  async cibaPoll(params) {
3114
+ return this.#cibaPoll(params, void 0);
3115
+ }
3116
+ /** {@link cibaPoll}; `bound` is `cibaAwait`'s deadline, which a §16 retry inside the poll must not pass. */
3117
+ async #cibaPoll(params, bound) {
3042
3118
  const operation = "ciba_poll";
3043
3119
  const auth = this.#cibaClientAuth(operation);
3044
3120
  const configuration = params.configuration ?? await this.oidcDiscover();
@@ -3069,9 +3145,11 @@ var OidcClient = class {
3069
3145
  return { error: mapHttpStatusToError(response.status, `${operation}: HTTP ${response.status}`) };
3070
3146
  },
3071
3147
  {
3148
+ idempotent: true,
3072
3149
  operation,
3073
3150
  enabled: this.#session.retryEnabled,
3074
- telemetry: this.#session.telemetry.dispatcher
3151
+ telemetry: this.#session.telemetry.dispatcher,
3152
+ ...bound !== void 0 ? deadlineBoundedRetry(bound, "CIBA request") : {}
3075
3153
  }
3076
3154
  );
3077
3155
  if (outcome.error) throw outcome.error;
@@ -3091,7 +3169,9 @@ var OidcClient = class {
3091
3169
  * the interval and polls again.
3092
3170
  * - Polling stops at `receivedAt + expiresIn`, even if the server has not
3093
3171
  * said `expired_token`: when the next wait would reach the deadline, the
3094
- * same `expired_token` is raised locally, without a request.
3172
+ * same `expired_token` is raised locally, without a request. A §16 retry
3173
+ * inside {@link cibaPoll} is bounded the same way (§34.2 P10): a wait that
3174
+ * would reach the deadline is not served and nothing is sent after it.
3095
3175
  * - `access_denied`, `expired_token`, `invalid_grant` and any other answer
3096
3176
  * end the loop.
3097
3177
  *
@@ -3119,11 +3199,14 @@ var OidcClient = class {
3119
3199
  }
3120
3200
  await clock.sleep(waitMs);
3121
3201
  try {
3122
- return await this.cibaPoll({
3123
- authReqId: initiated.authReqId,
3124
- configuration,
3125
- ...params.tenantId !== void 0 ? { tenantId: params.tenantId } : {}
3126
- });
3202
+ return await this.#cibaPoll(
3203
+ {
3204
+ authReqId: initiated.authReqId,
3205
+ configuration,
3206
+ ...params.tenantId !== void 0 ? { tenantId: params.tenantId } : {}
3207
+ },
3208
+ { deadline, clock }
3209
+ );
3127
3210
  } catch (err) {
3128
3211
  if (err instanceof OAuthProtocolError) {
3129
3212
  if (err.error === "authorization_pending" || err.error === "rate_limit_exceeded") continue;
@@ -3219,6 +3302,46 @@ var OidcClient = class {
3219
3302
  throw transient(new NetworkError(`${operation}: the request failed before any response arrived${code}`));
3220
3303
  }
3221
3304
  }
3305
+ /**
3306
+ * One device-poll attempt under §16 (CONTRACT.md §14.2 rule 6, §16.2; C164-25): a `5xx` or
3307
+ * a transport failure is retried **inside** the poll (three requests in all, the `Retry-After`
3308
+ * a floor) before it surfaces as a `NetworkError`; the loop then takes its next interval. A
3309
+ * `429` is never retried here — it is rule 9's wait, the loop's — nor is any answer the
3310
+ * server decided (`400`, `401`).
3311
+ */
3312
+ async #postDevicePoll(url, form, bound) {
3313
+ const operation = "device_poll";
3314
+ const outcome = await withRetry(
3315
+ async () => {
3316
+ try {
3317
+ const response = await this.#session.axios.post(url, form.toString(), {
3318
+ headers: { "Content-Type": "application/x-www-form-urlencoded" }
3319
+ });
3320
+ return { wire: response.data };
3321
+ } catch (err) {
3322
+ if (err instanceof AxiamError) return { error: err };
3323
+ const status = axiosStatus(err);
3324
+ const response = err.response;
3325
+ if (status === void 0) {
3326
+ throw new NetworkError(`${operation}: the request failed before any response arrived`, sanitizeAxiosError(err));
3327
+ }
3328
+ if (status >= 500) {
3329
+ throw retryableNetworkError(`${operation}: HTTP ${status}`, response);
3330
+ }
3331
+ return { error: pollRateLimit(err) ?? mapOidcError(err, url, "token request failed") };
3332
+ }
3333
+ },
3334
+ {
3335
+ idempotent: true,
3336
+ operation,
3337
+ enabled: this.#session.retryEnabled,
3338
+ telemetry: this.#session.telemetry.dispatcher,
3339
+ ...bound !== void 0 ? deadlineBoundedRetry(bound, "device authorization") : {}
3340
+ }
3341
+ );
3342
+ if (outcome.error) throw outcome.error;
3343
+ return outcome.wire;
3344
+ }
3222
3345
  /** POST a form body to the token endpoint from the discovery document. */
3223
3346
  async #postToken(configuration, form, tenantId) {
3224
3347
  const url = this.#endpointUrl(this.#requiredEndpoint(configuration, "token_endpoint"), tenantId);
@@ -3405,6 +3528,10 @@ var OidcClient = class {
3405
3528
  try {
3406
3529
  return await this.#session.axios.post(url, form.toString(), config);
3407
3530
  } catch (err) {
3531
+ if (axiosStatus(err) === 429) {
3532
+ const protocol = oauth2ErrorFromBody(axiosBody(err));
3533
+ if (protocol) throw protocol;
3534
+ }
3408
3535
  throw mapOidcError(err, url, fallbackMessage);
3409
3536
  }
3410
3537
  }