@keycardai/oauth 0.26.5 → 0.27.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.
Files changed (100) hide show
  1. package/README.md +66 -1
  2. package/dist/cjs/basicAuthorization.d.ts +11 -0
  3. package/dist/cjs/basicAuthorization.d.ts.map +1 -0
  4. package/dist/cjs/basicAuthorization.js +16 -0
  5. package/dist/cjs/basicAuthorization.js.map +1 -0
  6. package/dist/cjs/clientCredentials.d.ts.map +1 -1
  7. package/dist/cjs/clientCredentials.js +2 -2
  8. package/dist/cjs/clientCredentials.js.map +1 -1
  9. package/dist/cjs/credentials.d.ts +35 -0
  10. package/dist/cjs/credentials.d.ts.map +1 -1
  11. package/dist/cjs/credentials.js +19 -0
  12. package/dist/cjs/credentials.js.map +1 -1
  13. package/dist/cjs/deviceAuthorization.d.ts +166 -0
  14. package/dist/cjs/deviceAuthorization.d.ts.map +1 -0
  15. package/dist/cjs/deviceAuthorization.js +440 -0
  16. package/dist/cjs/deviceAuthorization.js.map +1 -0
  17. package/dist/cjs/discovery.d.ts +10 -41
  18. package/dist/cjs/discovery.d.ts.map +1 -1
  19. package/dist/cjs/discovery.js +7 -3
  20. package/dist/cjs/discovery.js.map +1 -1
  21. package/dist/cjs/errors.d.ts +61 -3
  22. package/dist/cjs/errors.d.ts.map +1 -1
  23. package/dist/cjs/errors.js +75 -4
  24. package/dist/cjs/errors.js.map +1 -1
  25. package/dist/cjs/index.d.ts +6 -3
  26. package/dist/cjs/index.d.ts.map +1 -1
  27. package/dist/cjs/index.js +13 -1
  28. package/dist/cjs/index.js.map +1 -1
  29. package/dist/cjs/pkce.d.ts.map +1 -1
  30. package/dist/cjs/pkce.js +6 -2
  31. package/dist/cjs/pkce.js.map +1 -1
  32. package/dist/cjs/server/clientSecret.d.ts +7 -1
  33. package/dist/cjs/server/clientSecret.d.ts.map +1 -1
  34. package/dist/cjs/server/clientSecret.js +17 -0
  35. package/dist/cjs/server/clientSecret.js.map +1 -1
  36. package/dist/cjs/server/webIdentity.d.ts +11 -1
  37. package/dist/cjs/server/webIdentity.d.ts.map +1 -1
  38. package/dist/cjs/server/webIdentity.js +35 -2
  39. package/dist/cjs/server/webIdentity.js.map +1 -1
  40. package/dist/cjs/server/workloadIdentity.d.ts +8 -1
  41. package/dist/cjs/server/workloadIdentity.d.ts.map +1 -1
  42. package/dist/cjs/server/workloadIdentity.js +15 -0
  43. package/dist/cjs/server/workloadIdentity.js.map +1 -1
  44. package/dist/cjs/tokenExchange.d.ts.map +1 -1
  45. package/dist/cjs/tokenExchange.js +2 -2
  46. package/dist/cjs/tokenExchange.js.map +1 -1
  47. package/dist/cjs/webApp.d.ts +35 -15
  48. package/dist/cjs/webApp.d.ts.map +1 -1
  49. package/dist/cjs/webApp.js +39 -11
  50. package/dist/cjs/webApp.js.map +1 -1
  51. package/dist/esm/basicAuthorization.d.ts +11 -0
  52. package/dist/esm/basicAuthorization.d.ts.map +1 -0
  53. package/dist/esm/basicAuthorization.js +13 -0
  54. package/dist/esm/basicAuthorization.js.map +1 -0
  55. package/dist/esm/clientCredentials.d.ts.map +1 -1
  56. package/dist/esm/clientCredentials.js +2 -2
  57. package/dist/esm/clientCredentials.js.map +1 -1
  58. package/dist/esm/credentials.d.ts +35 -0
  59. package/dist/esm/credentials.d.ts.map +1 -1
  60. package/dist/esm/credentials.js +17 -1
  61. package/dist/esm/credentials.js.map +1 -1
  62. package/dist/esm/deviceAuthorization.d.ts +166 -0
  63. package/dist/esm/deviceAuthorization.d.ts.map +1 -0
  64. package/dist/esm/deviceAuthorization.js +434 -0
  65. package/dist/esm/deviceAuthorization.js.map +1 -0
  66. package/dist/esm/discovery.d.ts +10 -41
  67. package/dist/esm/discovery.d.ts.map +1 -1
  68. package/dist/esm/discovery.js +7 -3
  69. package/dist/esm/discovery.js.map +1 -1
  70. package/dist/esm/errors.d.ts +61 -3
  71. package/dist/esm/errors.d.ts.map +1 -1
  72. package/dist/esm/errors.js +71 -3
  73. package/dist/esm/errors.js.map +1 -1
  74. package/dist/esm/index.d.ts +6 -3
  75. package/dist/esm/index.d.ts.map +1 -1
  76. package/dist/esm/index.js +3 -1
  77. package/dist/esm/index.js.map +1 -1
  78. package/dist/esm/pkce.d.ts.map +1 -1
  79. package/dist/esm/pkce.js +6 -2
  80. package/dist/esm/pkce.js.map +1 -1
  81. package/dist/esm/server/clientSecret.d.ts +7 -1
  82. package/dist/esm/server/clientSecret.d.ts.map +1 -1
  83. package/dist/esm/server/clientSecret.js +17 -0
  84. package/dist/esm/server/clientSecret.js.map +1 -1
  85. package/dist/esm/server/webIdentity.d.ts +11 -1
  86. package/dist/esm/server/webIdentity.d.ts.map +1 -1
  87. package/dist/esm/server/webIdentity.js +35 -2
  88. package/dist/esm/server/webIdentity.js.map +1 -1
  89. package/dist/esm/server/workloadIdentity.d.ts +8 -1
  90. package/dist/esm/server/workloadIdentity.d.ts.map +1 -1
  91. package/dist/esm/server/workloadIdentity.js +15 -0
  92. package/dist/esm/server/workloadIdentity.js.map +1 -1
  93. package/dist/esm/tokenExchange.d.ts.map +1 -1
  94. package/dist/esm/tokenExchange.js +2 -2
  95. package/dist/esm/tokenExchange.js.map +1 -1
  96. package/dist/esm/webApp.d.ts +35 -15
  97. package/dist/esm/webApp.d.ts.map +1 -1
  98. package/dist/esm/webApp.js +39 -11
  99. package/dist/esm/webApp.js.map +1 -1
  100. package/package.json +7 -2
@@ -0,0 +1,166 @@
1
+ import { type ApplicationCredential } from "./credentials.js";
2
+ import { type OAuthAuthorizationServerMetadata } from "./discovery.js";
3
+ import { type TokenResponse } from "./tokenExchange.js";
4
+ /**
5
+ * The time source and timer for the device grant. Inject a fake in tests so
6
+ * that `expiresAt` and the waits between polls do not depend on real time.
7
+ */
8
+ export interface Clock {
9
+ /** The current time in milliseconds since the Unix epoch. */
10
+ now(): number;
11
+ /** Resolves after `ms` milliseconds. Rejects with `signal.reason` when `signal` aborts. */
12
+ sleep(ms: number, signal?: AbortSignal): Promise<void>;
13
+ }
14
+ /** The real clock: `Date.now` and `setTimeout`. */
15
+ export declare const systemClock: Clock;
16
+ /**
17
+ * Options every device grant operation shares. Set exactly one of
18
+ * `credential` and `clientId`, and use the same one for every operation in
19
+ * a flow: the zone binds the device code to the client and how it
20
+ * authenticated.
21
+ */
22
+ export type DeviceClientOptions = ({
23
+ /**
24
+ * Authenticates each request with the credential's
25
+ * `clientAuthentication`, called once per request with the URL of the
26
+ * endpoint the request goes to.
27
+ */
28
+ credential: ApplicationCredential;
29
+ clientId?: never;
30
+ } | {
31
+ /** Public client. Sent as `client_id` in the body, with no other authentication. */
32
+ clientId: string;
33
+ credential?: never;
34
+ }) & {
35
+ /** Pre-discovered metadata. When set, no discovery request is made. */
36
+ metadata?: OAuthAuthorizationServerMetadata;
37
+ /** Aborting it rejects with `signal.reason`. No request is sent after the abort. */
38
+ signal?: AbortSignal;
39
+ /** Timeout in milliseconds for each request to the authorization server (default 10 seconds; 0 disables). */
40
+ timeoutMs?: number;
41
+ };
42
+ export type RequestDeviceAuthorizationOptions = DeviceClientOptions & {
43
+ /** Sent as one space-joined `scope` parameter. */
44
+ scopes?: readonly string[];
45
+ /** RFC 8707 resource indicators, sent as one `resource` parameter each. */
46
+ resources?: readonly string[];
47
+ /** Sets `expiresAt`. Default: `systemClock`. */
48
+ clock?: Clock;
49
+ };
50
+ /**
51
+ * The device authorization response (RFC 8628 §3.2). A plain value: the
52
+ * caller may persist it and poll from another process that authenticates as
53
+ * the same client.
54
+ */
55
+ export interface DeviceAuthorization {
56
+ /** The code the device polls with. NEVER show it to the person. */
57
+ deviceCode: string;
58
+ /** The code the person confirms. Always show it, so the person can compare it with the confirmation page. */
59
+ userCode: string;
60
+ /** Where the person enters `userCode`. */
61
+ verificationUri: string;
62
+ /** `verificationUri` with `userCode` filled in. Show it in place of `verificationUri` when it is set. */
63
+ verificationUriComplete?: string;
64
+ /** Lifetime of `deviceCode` and `userCode`, in seconds. */
65
+ expiresIn: number;
66
+ /** Minimum wait between polls, in seconds. 5 when the response omits it. */
67
+ interval: number;
68
+ /** The time the response was received plus `expiresIn`, in milliseconds since the Unix epoch, read from the clock. */
69
+ expiresAt: number;
70
+ }
71
+ export type PollDeviceTokenOptions = DeviceClientOptions & {
72
+ /** The response from `requestDeviceAuthorization`. `pollDeviceToken` reads only `deviceCode`. */
73
+ authorization: DeviceAuthorization;
74
+ };
75
+ export type WaitForDeviceTokenOptions = DeviceClientOptions & {
76
+ /** The response from `requestDeviceAuthorization`, or a copy persisted from it. */
77
+ authorization: DeviceAuthorization;
78
+ /**
79
+ * The wait in seconds before the first poll, and the starting interval.
80
+ * Default: `authorization.interval`. A value that is not a positive integer,
81
+ * or is below `authorization.interval`, throws `ConfigurationError`.
82
+ */
83
+ interval?: number;
84
+ /** Reads the time for the expiry check and waits between polls. Default: `systemClock`. */
85
+ clock?: Clock;
86
+ };
87
+ /**
88
+ * Ask the zone for a device code and a user code (RFC 8628 §3.1).
89
+ *
90
+ * The SDK does not deliver the user code. Show the person
91
+ * `verificationUriComplete` when it is set, and `verificationUri`
92
+ * otherwise, together with `userCode`.
93
+ *
94
+ * Throws `ConfigurationError` before any request when the client options
95
+ * are not exactly one of `credential` and `clientId`, when the credential
96
+ * has no `clientAuthentication`, or when `metadata` is not set and `issuer`
97
+ * is not an http or https URL. Throws `ConfigurationError` before the
98
+ * device authorization request when the metadata has no
99
+ * `device_authorization_endpoint` or it is not an http or https URL. An error
100
+ * from the credential's `clientAuthentication` is thrown as is. Every other
101
+ * failure throws `DeviceGrantError`, including a failed discovery request.
102
+ * A response that is missing a required
103
+ * field, or has an `interval` that is not a positive integer, throws
104
+ * `DeviceGrantError` `invalid_response`.
105
+ */
106
+ export declare function requestDeviceAuthorization(issuer: string, options: RequestDeviceAuthorizationOptions): Promise<DeviceAuthorization>;
107
+ /**
108
+ * Poll the token endpoint once (RFC 8628 §3.4) with
109
+ * `authorization.deviceCode`. Returns the token once the person approves.
110
+ *
111
+ * Without `metadata`, each call discovers it first. If you call it in your
112
+ * own loop, fetch the metadata once with `fetchAuthorizationServerMetadata`
113
+ * and pass it to every poll. Also wait longer after a timeout or other
114
+ * network error (RFC 8628 §3.5).
115
+ *
116
+ * Throws `ConfigurationError` before any request when the client options
117
+ * are not exactly one of `credential` and `clientId`, when `authorization`
118
+ * has no `deviceCode`, or when `metadata` is not set and `issuer` is not an
119
+ * http or https URL. Throws `ConfigurationError` before the poll when the
120
+ * metadata has no `token_endpoint` or it is not an http or https URL. An
121
+ * error from the credential's `clientAuthentication` is thrown as is. Every
122
+ * other failure throws `DeviceGrantError`, including a failed discovery
123
+ * request, `authorization_pending`, and `slow_down`.
124
+ */
125
+ export declare function pollDeviceToken(issuer: string, options: PollDeviceTokenOptions): Promise<TokenResponse>;
126
+ /**
127
+ * Poll until the person approves or denies the request, following
128
+ * RFC 8628 §3.5.
129
+ *
130
+ * - It waits the interval before each poll, including the first.
131
+ * - On `authorization_pending` it polls again.
132
+ * - On `slow_down` it adds 5 seconds to the interval for this poll and every later one.
133
+ * - On a network error, a timeout, an HTTP 5xx, or an HTTP 429 it stops and
134
+ * throws `DevicePollError`, also when the 5xx or 429 has an OAuth error
135
+ * body. It does not poll again. After a network error or a timeout, the
136
+ * error's `interval` is double the current interval.
137
+ * - On any other failure it stops and throws that error as is: a
138
+ * `DeviceGrantError` for any other OAuth error or HTTP error, or the error
139
+ * from the credential's `clientAuthentication`.
140
+ * - If the next poll would start after `authorization.expiresAt`, it stops
141
+ * without waiting or polling and throws `DeviceGrantError` with code
142
+ * `expired_token`.
143
+ *
144
+ * To resume after a `DevicePollError`, call it again before `expiresAt` with
145
+ * the same `authorization` and `interval` set to the error's `interval`.
146
+ *
147
+ * Polling again on `authorization_pending` and `slow_down` follows
148
+ * RFC 8628 §3.5 and is not a retry. `timeoutMs` bounds each request. It does
149
+ * not bound the waits or the whole loop, and it applies even when `signal`
150
+ * has a longer deadline.
151
+ *
152
+ * Throws `ConfigurationError` before any request when the client options
153
+ * are not exactly one of `credential` and `clientId`, when `authorization`
154
+ * has no `deviceCode`, no `expiresAt`, or an `interval` that is not a
155
+ * positive integer, when `interval` is not a positive integer or is below
156
+ * `authorization.interval`, or
157
+ * when `metadata` is not set and `issuer` is not an http or https URL. A
158
+ * failed discovery request throws `DeviceGrantError` before the first wait.
159
+ *
160
+ * When the device authorization request named more than one resource, the
161
+ * token is not for any one of them. NEVER store it as the token for one
162
+ * resource. To get a token for one resource, call `refreshAuthorization`
163
+ * with `resources` set to it.
164
+ */
165
+ export declare function waitForDeviceToken(issuer: string, options: WaitForDeviceTokenOptions): Promise<TokenResponse>;
166
+ //# sourceMappingURL=deviceAuthorization.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deviceAuthorization.d.ts","sourceRoot":"","sources":["../../src/deviceAuthorization.ts"],"names":[],"mappings":"AACA,OAAO,EAA+B,KAAK,qBAAqB,EAA4B,MAAM,kBAAkB,CAAC;AACrH,OAAO,EAAoC,KAAK,gCAAgC,EAAE,MAAM,gBAAgB,CAAC;AAEzG,OAAO,EAA4B,KAAK,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAUlF;;;GAGG;AACH,MAAM,WAAW,KAAK;IACpB,6DAA6D;IAC7D,GAAG,IAAI,MAAM,CAAC;IACd,2FAA2F;IAC3F,KAAK,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACxD;AAED,mDAAmD;AACnD,eAAO,MAAM,WAAW,EAAE,KAkBzB,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,mBAAmB,GAAG,CAC9B;IACE;;;;OAIG;IACH,UAAU,EAAE,qBAAqB,CAAC;IAClC,QAAQ,CAAC,EAAE,KAAK,CAAC;CAClB,GACD;IACE,oFAAoF;IACpF,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,CAAC,EAAE,KAAK,CAAC;CACpB,CACJ,GAAG;IACF,uEAAuE;IACvE,QAAQ,CAAC,EAAE,gCAA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,wBAAsB,eAAe,CACnC,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,sBAAsB,GAC9B,OAAO,CAAC,aAAa,CAAC,CAQxB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,wBAAsB,kBAAkB,CACtC,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,yBAAyB,GACjC,OAAO,CAAC,aAAa,CAAC,CA2DxB"}
@@ -0,0 +1,434 @@
1
+ import { requestSignal } from "./requestSignal.js";
2
+ import { requireClientAuthentication } from "./credentials.js";
3
+ import { fetchAuthorizationServerMetadata } from "./discovery.js";
4
+ import { ConfigurationError, DeviceGrantError, DevicePollError, HTTPError, OAuthError } from "./errors.js";
5
+ import { deserializeTokenResponse } from "./tokenExchange.js";
6
+ // =============================================================================
7
+ // Device Authorization Grant (RFC 8628), device side
8
+ // =============================================================================
9
+ const DEVICE_CODE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
10
+ const DEFAULT_INTERVAL_SECONDS = 5;
11
+ const SLOW_DOWN_INCREMENT_SECONDS = 5;
12
+ /** The real clock: `Date.now` and `setTimeout`. */
13
+ export const systemClock = {
14
+ now: () => Date.now(),
15
+ sleep: (ms, signal) => new Promise((resolve, reject) => {
16
+ if (signal?.aborted) {
17
+ reject(signal.reason);
18
+ return;
19
+ }
20
+ const onAbort = () => {
21
+ clearTimeout(timer);
22
+ reject(signal?.reason);
23
+ };
24
+ const timer = setTimeout(() => {
25
+ signal?.removeEventListener("abort", onAbort);
26
+ resolve();
27
+ }, ms);
28
+ signal?.addEventListener("abort", onAbort, { once: true });
29
+ }),
30
+ };
31
+ /**
32
+ * Ask the zone for a device code and a user code (RFC 8628 §3.1).
33
+ *
34
+ * The SDK does not deliver the user code. Show the person
35
+ * `verificationUriComplete` when it is set, and `verificationUri`
36
+ * otherwise, together with `userCode`.
37
+ *
38
+ * Throws `ConfigurationError` before any request when the client options
39
+ * are not exactly one of `credential` and `clientId`, when the credential
40
+ * has no `clientAuthentication`, or when `metadata` is not set and `issuer`
41
+ * is not an http or https URL. Throws `ConfigurationError` before the
42
+ * device authorization request when the metadata has no
43
+ * `device_authorization_endpoint` or it is not an http or https URL. An error
44
+ * from the credential's `clientAuthentication` is thrown as is. Every other
45
+ * failure throws `DeviceGrantError`, including a failed discovery request.
46
+ * A response that is missing a required
47
+ * field, or has an `interval` that is not a positive integer, throws
48
+ * `DeviceGrantError` `invalid_response`.
49
+ */
50
+ export async function requestDeviceAuthorization(issuer, options) {
51
+ const client = resolveClient(options, "requestDeviceAuthorization");
52
+ const metadata = await resolveMetadata(issuer, "requestDeviceAuthorization", options);
53
+ const endpoint = requireEndpoint(issuer, metadata, "device_authorization_endpoint");
54
+ const params = new URLSearchParams();
55
+ if (options.scopes && options.scopes.length > 0) {
56
+ params.set("scope", options.scopes.join(" "));
57
+ }
58
+ for (const resource of options.resources ?? []) {
59
+ params.append("resource", resource);
60
+ }
61
+ const what = "Device authorization request";
62
+ return withTransportError(what, options.signal, async () => {
63
+ const response = await post(issuer, endpoint, params, client, options);
64
+ if (!response.ok) {
65
+ throw await errorFromResponse(response, what);
66
+ }
67
+ const json = await readJsonObject(response);
68
+ return parseDeviceAuthorization(json, response.status, options.clock ?? systemClock);
69
+ });
70
+ }
71
+ /**
72
+ * Poll the token endpoint once (RFC 8628 §3.4) with
73
+ * `authorization.deviceCode`. Returns the token once the person approves.
74
+ *
75
+ * Without `metadata`, each call discovers it first. If you call it in your
76
+ * own loop, fetch the metadata once with `fetchAuthorizationServerMetadata`
77
+ * and pass it to every poll. Also wait longer after a timeout or other
78
+ * network error (RFC 8628 §3.5).
79
+ *
80
+ * Throws `ConfigurationError` before any request when the client options
81
+ * are not exactly one of `credential` and `clientId`, when `authorization`
82
+ * has no `deviceCode`, or when `metadata` is not set and `issuer` is not an
83
+ * http or https URL. Throws `ConfigurationError` before the poll when the
84
+ * metadata has no `token_endpoint` or it is not an http or https URL. An
85
+ * error from the credential's `clientAuthentication` is thrown as is. Every
86
+ * other failure throws `DeviceGrantError`, including a failed discovery
87
+ * request, `authorization_pending`, and `slow_down`.
88
+ */
89
+ export async function pollDeviceToken(issuer, options) {
90
+ const client = resolveClient(options, "pollDeviceToken");
91
+ requireDeviceCode(options.authorization);
92
+ const metadata = await resolveMetadata(issuer, "pollDeviceToken", options);
93
+ const tokenEndpoint = requireEndpoint(issuer, metadata, "token_endpoint");
94
+ return withTransportError("Device token poll", options.signal, () => poll(issuer, tokenEndpoint, client, options.authorization, options));
95
+ }
96
+ /**
97
+ * Poll until the person approves or denies the request, following
98
+ * RFC 8628 §3.5.
99
+ *
100
+ * - It waits the interval before each poll, including the first.
101
+ * - On `authorization_pending` it polls again.
102
+ * - On `slow_down` it adds 5 seconds to the interval for this poll and every later one.
103
+ * - On a network error, a timeout, an HTTP 5xx, or an HTTP 429 it stops and
104
+ * throws `DevicePollError`, also when the 5xx or 429 has an OAuth error
105
+ * body. It does not poll again. After a network error or a timeout, the
106
+ * error's `interval` is double the current interval.
107
+ * - On any other failure it stops and throws that error as is: a
108
+ * `DeviceGrantError` for any other OAuth error or HTTP error, or the error
109
+ * from the credential's `clientAuthentication`.
110
+ * - If the next poll would start after `authorization.expiresAt`, it stops
111
+ * without waiting or polling and throws `DeviceGrantError` with code
112
+ * `expired_token`.
113
+ *
114
+ * To resume after a `DevicePollError`, call it again before `expiresAt` with
115
+ * the same `authorization` and `interval` set to the error's `interval`.
116
+ *
117
+ * Polling again on `authorization_pending` and `slow_down` follows
118
+ * RFC 8628 §3.5 and is not a retry. `timeoutMs` bounds each request. It does
119
+ * not bound the waits or the whole loop, and it applies even when `signal`
120
+ * has a longer deadline.
121
+ *
122
+ * Throws `ConfigurationError` before any request when the client options
123
+ * are not exactly one of `credential` and `clientId`, when `authorization`
124
+ * has no `deviceCode`, no `expiresAt`, or an `interval` that is not a
125
+ * positive integer, when `interval` is not a positive integer or is below
126
+ * `authorization.interval`, or
127
+ * when `metadata` is not set and `issuer` is not an http or https URL. A
128
+ * failed discovery request throws `DeviceGrantError` before the first wait.
129
+ *
130
+ * When the device authorization request named more than one resource, the
131
+ * token is not for any one of them. NEVER store it as the token for one
132
+ * resource. To get a token for one resource, call `refreshAuthorization`
133
+ * with `resources` set to it.
134
+ */
135
+ export async function waitForDeviceToken(issuer, options) {
136
+ const client = resolveClient(options, "waitForDeviceToken");
137
+ const { authorization, signal } = options;
138
+ requireDeviceCode(authorization);
139
+ if (!Number.isFinite(authorization.expiresAt)) {
140
+ throw new ConfigurationError("waitForDeviceToken: the device authorization has no expiresAt");
141
+ }
142
+ if (!isPositiveInteger(authorization.interval)) {
143
+ throw new ConfigurationError(`waitForDeviceToken: the device authorization interval ${JSON.stringify(authorization.interval)} is not a positive integer`);
144
+ }
145
+ let interval = authorization.interval;
146
+ if (options.interval !== undefined) {
147
+ if (!isPositiveInteger(options.interval)) {
148
+ throw new ConfigurationError(`waitForDeviceToken: interval ${JSON.stringify(options.interval)} is not a positive integer`);
149
+ }
150
+ if (options.interval < authorization.interval) {
151
+ throw new ConfigurationError(`waitForDeviceToken: interval ${options.interval} is below the device authorization interval ${authorization.interval}`);
152
+ }
153
+ interval = options.interval;
154
+ }
155
+ const clock = options.clock ?? systemClock;
156
+ const tokenEndpoint = requireEndpoint(issuer, await resolveMetadata(issuer, "waitForDeviceToken", options), "token_endpoint");
157
+ for (;;) {
158
+ if (clock.now() + interval * 1000 > authorization.expiresAt) {
159
+ throw new DeviceGrantError("expired_token", {
160
+ errorDescription: "The device code expired before the request was approved",
161
+ });
162
+ }
163
+ await clock.sleep(interval * 1000, signal);
164
+ signal?.throwIfAborted();
165
+ try {
166
+ return await poll(issuer, tokenEndpoint, client, authorization, options);
167
+ }
168
+ catch (error) {
169
+ signal?.throwIfAborted();
170
+ if (error instanceof TransportFailure) {
171
+ throw new DevicePollError(interval * 2, error.cause);
172
+ }
173
+ if (error instanceof DeviceGrantError && isTransientStatus(error.status)) {
174
+ throw new DevicePollError(interval, error);
175
+ }
176
+ if (error instanceof DeviceGrantError && error.errorCode === "authorization_pending") {
177
+ continue;
178
+ }
179
+ if (error instanceof DeviceGrantError && error.errorCode === "slow_down") {
180
+ interval += SLOW_DOWN_INCREMENT_SECONDS;
181
+ continue;
182
+ }
183
+ throw error;
184
+ }
185
+ }
186
+ }
187
+ /**
188
+ * A request that ended without a complete response: a network error or a
189
+ * timeout, while sending the request or while reading the response body.
190
+ */
191
+ class TransportFailure {
192
+ constructor(cause) {
193
+ this.cause = cause;
194
+ }
195
+ }
196
+ function resolveClient(options, operation) {
197
+ const { credential, clientId } = options;
198
+ if (credential !== undefined && clientId !== undefined) {
199
+ throw new ConfigurationError(`${operation}: set either credential or clientId, not both`);
200
+ }
201
+ if (credential !== undefined) {
202
+ return { credential: requireClientAuthentication(credential, operation) };
203
+ }
204
+ if (typeof clientId === "string" && clientId) {
205
+ return { clientId };
206
+ }
207
+ throw new ConfigurationError(`${operation}: clientId or credential is required`);
208
+ }
209
+ function requireDeviceCode(authorization) {
210
+ if (!authorization || typeof authorization.deviceCode !== "string" || !authorization.deviceCode) {
211
+ throw new ConfigurationError("the device authorization has no deviceCode");
212
+ }
213
+ }
214
+ function requireEndpoint(issuer, metadata, field) {
215
+ const endpoint = metadata[field];
216
+ if (!endpoint) {
217
+ throw new ConfigurationError(`Authorization server "${issuer}" does not advertise a ${field}`);
218
+ }
219
+ if (!isHttpUrl(endpoint)) {
220
+ throw new ConfigurationError(`Authorization server "${issuer}" advertises a ${field} that is not an http or https URL: ${JSON.stringify(endpoint)}`);
221
+ }
222
+ return endpoint;
223
+ }
224
+ function isHttpUrl(value) {
225
+ try {
226
+ const { protocol } = new URL(value);
227
+ return protocol === "https:" || protocol === "http:";
228
+ }
229
+ catch {
230
+ return false;
231
+ }
232
+ }
233
+ function isPositiveInteger(value) {
234
+ return typeof value === "number" && Number.isInteger(value) && value > 0;
235
+ }
236
+ /**
237
+ * Returns `options.metadata`, or discovers it. A failed discovery throws
238
+ * `DeviceGrantError` `invalid_response` with the failure as `cause`.
239
+ */
240
+ async function resolveMetadata(issuer, operation, options) {
241
+ if (!options.metadata && !isHttpUrl(issuer)) {
242
+ throw new ConfigurationError(`${operation}: issuer ${JSON.stringify(issuer)} is not an http or https URL`);
243
+ }
244
+ options.signal?.throwIfAborted();
245
+ if (options.metadata)
246
+ return options.metadata;
247
+ try {
248
+ return await fetchAuthorizationServerMetadata(issuer, { signal: options.signal, timeoutMs: options.timeoutMs });
249
+ }
250
+ catch (cause) {
251
+ options.signal?.throwIfAborted();
252
+ const detail = cause instanceof Error ? cause.message : String(cause);
253
+ let retryable = !(cause instanceof OAuthError);
254
+ let status;
255
+ if (cause instanceof HTTPError) {
256
+ status = cause.status;
257
+ retryable = isTransientStatus(status);
258
+ }
259
+ throw new DeviceGrantError("invalid_response", {
260
+ errorDescription: `Discovery for "${issuer}" failed: ${detail}`,
261
+ status,
262
+ retryable,
263
+ cause,
264
+ });
265
+ }
266
+ }
267
+ function isTransientStatus(status) {
268
+ return status !== undefined && (status >= 500 || status === 429);
269
+ }
270
+ /**
271
+ * Runs `request`. A `TransportFailure` it throws becomes a retryable
272
+ * `DeviceGrantError` with the failure as `cause`. When `signal` has aborted,
273
+ * it rejects with `signal.reason` instead.
274
+ */
275
+ async function withTransportError(what, signal, request) {
276
+ try {
277
+ return await request();
278
+ }
279
+ catch (error) {
280
+ if (!(error instanceof TransportFailure))
281
+ throw error;
282
+ signal?.throwIfAborted();
283
+ throw new DeviceGrantError("invalid_response", {
284
+ errorDescription: `${what} failed: ${error.cause instanceof Error ? error.cause.message : String(error.cause)}`,
285
+ retryable: true,
286
+ cause: error.cause,
287
+ });
288
+ }
289
+ }
290
+ /** One device token poll. Throws `TransportFailure` when no complete response arrives. */
291
+ async function poll(issuer, tokenEndpoint, client, authorization, options) {
292
+ const params = new URLSearchParams();
293
+ params.set("grant_type", DEVICE_CODE_GRANT_TYPE);
294
+ params.set("device_code", authorization.deviceCode);
295
+ const response = await post(issuer, tokenEndpoint, params, client, options);
296
+ if (!response.ok) {
297
+ throw await errorFromResponse(response, "Device token poll");
298
+ }
299
+ const json = await readJsonObject(response);
300
+ try {
301
+ return deserializeTokenResponse(json);
302
+ }
303
+ catch (error) {
304
+ throw new DeviceGrantError("invalid_response", {
305
+ errorDescription: error instanceof Error ? error.message : String(error),
306
+ status: response.status,
307
+ });
308
+ }
309
+ }
310
+ /**
311
+ * POSTs `params` to `endpoint` with the client authentication added. Errors
312
+ * from the credential are thrown unchanged. A fetch failure is thrown as
313
+ * `TransportFailure`.
314
+ */
315
+ async function post(issuer, endpoint, params, client, options) {
316
+ const headers = {};
317
+ if ("credential" in client) {
318
+ const auth = await client.credential.clientAuthentication(issuer, endpoint);
319
+ Object.assign(headers, auth.headers);
320
+ for (const [name, value] of Object.entries(auth.form))
321
+ params.set(name, value);
322
+ }
323
+ else {
324
+ params.set("client_id", client.clientId);
325
+ }
326
+ headers["Content-Type"] = "application/x-www-form-urlencoded";
327
+ options.signal?.throwIfAborted();
328
+ try {
329
+ return await fetch(endpoint, {
330
+ method: "POST",
331
+ headers,
332
+ body: params.toString(),
333
+ signal: requestSignal(options.signal, options.timeoutMs),
334
+ });
335
+ }
336
+ catch (cause) {
337
+ throw new TransportFailure(cause);
338
+ }
339
+ }
340
+ /**
341
+ * Reads the body as JSON. Returns `undefined` when the body is not JSON.
342
+ * Throws `TransportFailure` when reading the body fails, such as on a
343
+ * timeout.
344
+ */
345
+ async function readJson(response) {
346
+ let text;
347
+ try {
348
+ text = await response.text();
349
+ }
350
+ catch (cause) {
351
+ throw new TransportFailure(cause);
352
+ }
353
+ try {
354
+ return JSON.parse(text);
355
+ }
356
+ catch {
357
+ return undefined;
358
+ }
359
+ }
360
+ /**
361
+ * A `DeviceGrantError` with the server's code for an RFC 6749 §5.2 error
362
+ * body. Otherwise a `DeviceGrantError` `invalid_response` that is retryable
363
+ * for a 5xx or 429.
364
+ */
365
+ async function errorFromResponse(response, what) {
366
+ const body = await readJson(response);
367
+ if (body && typeof body === "object" && !Array.isArray(body)) {
368
+ const fields = body;
369
+ if (typeof fields.error === "string" && fields.error) {
370
+ return new DeviceGrantError(fields.error, {
371
+ errorDescription: typeof fields.error_description === "string" ? fields.error_description : undefined,
372
+ errorUri: typeof fields.error_uri === "string" ? fields.error_uri : undefined,
373
+ status: response.status,
374
+ });
375
+ }
376
+ }
377
+ return new DeviceGrantError("invalid_response", {
378
+ errorDescription: `${what} failed (HTTP ${response.status})`,
379
+ status: response.status,
380
+ retryable: isTransientStatus(response.status),
381
+ });
382
+ }
383
+ async function readJsonObject(response) {
384
+ const json = await readJson(response);
385
+ if (!json || typeof json !== "object" || Array.isArray(json)) {
386
+ throw new DeviceGrantError("invalid_response", {
387
+ errorDescription: "Response is not a JSON object",
388
+ status: response.status,
389
+ });
390
+ }
391
+ return json;
392
+ }
393
+ function parseDeviceAuthorization(json, status, clock) {
394
+ const missing = [];
395
+ const text = (name) => {
396
+ const value = json[name];
397
+ if (typeof value === "string" && value)
398
+ return value;
399
+ missing.push(name);
400
+ return "";
401
+ };
402
+ const deviceCode = text("device_code");
403
+ const userCode = text("user_code");
404
+ const verificationUri = text("verification_uri");
405
+ const expiresIn = json.expires_in;
406
+ if (typeof expiresIn !== "number" || !(expiresIn > 0))
407
+ missing.push("expires_in");
408
+ if (missing.length > 0) {
409
+ throw new DeviceGrantError("invalid_response", {
410
+ errorDescription: `Device authorization response is missing ${missing.join(", ")}`,
411
+ status,
412
+ });
413
+ }
414
+ const interval = "interval" in json ? json.interval : DEFAULT_INTERVAL_SECONDS;
415
+ if (!isPositiveInteger(interval)) {
416
+ throw new DeviceGrantError("invalid_response", {
417
+ errorDescription: `Device authorization response interval ${JSON.stringify(interval)} is not a positive integer`,
418
+ status,
419
+ });
420
+ }
421
+ const authorization = {
422
+ deviceCode,
423
+ userCode,
424
+ verificationUri,
425
+ expiresIn: expiresIn,
426
+ interval,
427
+ expiresAt: clock.now() + expiresIn * 1000,
428
+ };
429
+ if (typeof json.verification_uri_complete === "string" && json.verification_uri_complete) {
430
+ authorization.verificationUriComplete = json.verification_uri_complete;
431
+ }
432
+ return authorization;
433
+ }
434
+ //# sourceMappingURL=deviceAuthorization.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deviceAuthorization.js","sourceRoot":"","sources":["../../src/deviceAuthorization.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,2BAA2B,EAAwD,MAAM,kBAAkB,CAAC;AACrH,OAAO,EAAE,gCAAgC,EAAyC,MAAM,gBAAgB,CAAC;AACzG,OAAO,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,eAAe,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAC3G,OAAO,EAAE,wBAAwB,EAAsB,MAAM,oBAAoB,CAAC;AAElF,gFAAgF;AAChF,qDAAqD;AACrD,gFAAgF;AAEhF,MAAM,sBAAsB,GAAG,8CAA8C,CAAC;AAC9E,MAAM,wBAAwB,GAAG,CAAC,CAAC;AACnC,MAAM,2BAA2B,GAAG,CAAC,CAAC;AAatC,mDAAmD;AACnD,MAAM,CAAC,MAAM,WAAW,GAAU;IAChC,GAAG,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE;IACrB,KAAK,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,CACpB,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACpC,IAAI,MAAM,EAAE,OAAO,EAAE,CAAC;YACpB,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YACtB,OAAO;QACT,CAAC;QACD,MAAM,OAAO,GAAG,GAAG,EAAE;YACnB,YAAY,CAAC,KAAK,CAAC,CAAC;YACpB,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QACzB,CAAC,CAAC;QACF,MAAM,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE;YAC5B,MAAM,EAAE,mBAAmB,CAAC,OAAO,EAAE,OA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