@sharpps/agent 0.0.0-stage → 1.0.1

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/client.js ADDED
@@ -0,0 +1,245 @@
1
+ import WebSocket from "ws";
2
+ import { decodeFrame, PROTOCOL_VERSION, encodeFrame, parseMessage } from "./protocol.js";
3
+ import { isEnabled, resolvePlugin, validateKeys } from "./setup.js";
4
+ const FATAL = new Set(["bad-token", "protocol-mismatch", "refused", "revoked"]);
5
+ export function createAgentClient(o) {
6
+ validateKeys(o.plugins);
7
+ const stored = o.config ?? { version: 1, plugins: {} };
8
+ const resolved = new Map();
9
+ const setupProblems = [];
10
+ for (const p of o.plugins) {
11
+ const r = resolvePlugin(p.name, p.config ?? [], stored, o.env);
12
+ resolved.set(p.name, r.values);
13
+ if (!isEnabled(r.values))
14
+ continue; // a switched-off plugin needs no answers
15
+ for (const m of r.missing)
16
+ setupProblems.push(`${p.name}: "${m.label}" (${m.key}) is needed; run the setup wizard`);
17
+ for (const i of r.invalid)
18
+ setupProblems.push(`${p.name}: ${i.message}`);
19
+ }
20
+ if (setupProblems.length)
21
+ throw new Error(`setup is not complete:\n ${setupProblems.join("\n ")}`);
22
+ // Only switched-on plugins take part: their names and capabilities are offered, and only they are started and stopped.
23
+ const active = o.plugins.filter((p) => isEnabled(resolved.get(p.name) ?? {}));
24
+ const names = new Set();
25
+ const routes = new Map();
26
+ for (const p of active) {
27
+ if (names.has(p.name))
28
+ throw new Error(`two plugins are named "${p.name}"`);
29
+ names.add(p.name);
30
+ for (const [cap, spec] of Object.entries(p.capabilities)) {
31
+ if (routes.has(cap))
32
+ throw new Error(`capability "${cap}" is offered by two plugins`);
33
+ routes.set(cap, { plugin: p, spec });
34
+ }
35
+ }
36
+ const capabilities = [...routes.keys()];
37
+ const log = o.log ?? (() => { });
38
+ const emit = (e) => { try {
39
+ o.onEvent?.(e);
40
+ }
41
+ catch { /* a listener must not break the client */ } };
42
+ const retry = o.reconnect ?? true;
43
+ const maxBackoff = o.maxBackoffMs ?? 30_000;
44
+ const heartbeatMs = o.heartbeatMs ?? 15_000;
45
+ let ws = null;
46
+ let stopped = false;
47
+ let connected = false;
48
+ let attempt = 0;
49
+ let heartbeat;
50
+ let retryTimer;
51
+ const running = new Map();
52
+ /** Streams the server announced: streamId -> the call they belong to. */
53
+ const incoming = new Map();
54
+ let resolveReady;
55
+ let rejectReady;
56
+ const ready = new Promise((res, rej) => { resolveReady = res; rejectReady = rej; });
57
+ ready.catch(() => { });
58
+ let readySettled = false;
59
+ const send = (m) => { if (ws?.readyState === WebSocket.OPEN)
60
+ ws.send(JSON.stringify(m)); };
61
+ const sendStream = (streamId, payload, kind) => { if (ws?.readyState === WebSocket.OPEN)
62
+ ws.send(encodeFrame(kind, streamId, payload), { binary: true }); };
63
+ const sendStreamEnd = (callId, streamId) => send({ t: "stream-end", callId, streamId });
64
+ function cancelAll(reason) {
65
+ for (const [callId, r] of running) {
66
+ r.controller.abort(new Error(reason));
67
+ running.delete(callId);
68
+ }
69
+ }
70
+ async function runCall(m) {
71
+ const route = routes.get(m.capability);
72
+ if (!route)
73
+ return send({ t: "error", callId: m.callId, code: "unknown-capability", message: `this agent does not offer "${m.capability}"` });
74
+ const controller = new AbortController();
75
+ const entry = { capability: m.capability, controller, data: [], end: [] };
76
+ running.set(m.callId, entry);
77
+ emit({ type: "call", capability: m.capability, callId: m.callId });
78
+ const announced = new Set();
79
+ const ctx = {
80
+ callId: m.callId,
81
+ signal: controller.signal,
82
+ inbound: (onData, onEnd) => { entry.data.push(onData); if (onEnd)
83
+ entry.end.push(onEnd); },
84
+ streamEnd: (streamId) => { announced.delete(streamId); sendStreamEnd(m.callId, streamId); },
85
+ event: (data) => send({ t: "event", callId: m.callId, data }),
86
+ stream: (streamId, payload, kind = "binary") => {
87
+ if (!announced.has(streamId)) {
88
+ announced.add(streamId);
89
+ send({ t: "stream", callId: m.callId, streamId });
90
+ }
91
+ sendStream(streamId, payload, kind);
92
+ },
93
+ };
94
+ try {
95
+ const output = await route.spec.handler(m.input, ctx);
96
+ if (!controller.signal.aborted)
97
+ send({ t: "result", callId: m.callId, output: output ?? null });
98
+ emit({ type: "call-done", callId: m.callId, ok: true });
99
+ }
100
+ catch (e) {
101
+ if (!controller.signal.aborted)
102
+ send({ t: "error", callId: m.callId, code: "failed", message: e instanceof Error ? e.message : String(e) });
103
+ emit({ type: "call-done", callId: m.callId, ok: false });
104
+ }
105
+ finally {
106
+ running.delete(m.callId);
107
+ for (const [streamId, callId] of incoming)
108
+ if (callId === m.callId)
109
+ incoming.delete(streamId);
110
+ }
111
+ }
112
+ function onMessage(data, isBinary) {
113
+ if (isBinary) {
114
+ const f = decodeFrame(new Uint8Array(data));
115
+ const callId = f && incoming.get(f.streamId);
116
+ const r = callId ? running.get(callId) : undefined;
117
+ if (f && r)
118
+ for (const h of r.data)
119
+ h(f.streamId, Uint8Array.from(f.payload), f.kind);
120
+ return;
121
+ }
122
+ const m = parseMessage(data.toString());
123
+ if (!m)
124
+ return;
125
+ switch (m.t) {
126
+ case "stream":
127
+ incoming.set(m.streamId, m.callId);
128
+ return;
129
+ case "stream-end": {
130
+ incoming.delete(m.streamId);
131
+ const r = running.get(m.callId);
132
+ if (r)
133
+ for (const h of r.end)
134
+ h(m.streamId);
135
+ return;
136
+ }
137
+ case "welcome":
138
+ connected = true;
139
+ attempt = 0;
140
+ emit({ type: "connected", agentId: m.agentId, name: m.name });
141
+ if (!readySettled) {
142
+ readySettled = true;
143
+ resolveReady({ agentId: m.agentId, name: m.name });
144
+ }
145
+ break;
146
+ case "reject":
147
+ emit({ type: "refused", code: m.code, message: m.message });
148
+ if (!readySettled) {
149
+ readySettled = true;
150
+ rejectReady(new Error(`refused: ${m.message}`));
151
+ }
152
+ stopped = stopped || FATAL.has(m.code);
153
+ ws?.close(4000, m.code);
154
+ break;
155
+ case "pong":
156
+ break;
157
+ case "call":
158
+ void runCall(m);
159
+ break;
160
+ case "cancel": {
161
+ const r = running.get(m.callId);
162
+ if (r)
163
+ r.controller.abort(new Error("cancelled by the server"));
164
+ break;
165
+ }
166
+ }
167
+ }
168
+ function connect() {
169
+ if (stopped)
170
+ return;
171
+ emit({ type: "connecting", server: o.server });
172
+ o.accessToken().then((token) => {
173
+ if (stopped)
174
+ return;
175
+ ws = new WebSocket(o.server, { headers: { authorization: `Bearer ${token}` }, maxPayload: 256 * 1024 * 1024 });
176
+ ws.on("open", () => {
177
+ send({ t: "hello", protocol: PROTOCOL_VERSION, agentVersion: o.agentVersion, machine: o.machine, capabilities, plugins: [...names] });
178
+ heartbeat = setInterval(() => send({ t: "ping" }), heartbeatMs);
179
+ });
180
+ ws.on("message", onMessage);
181
+ ws.on("close", (code, reason) => {
182
+ clearInterval(heartbeat);
183
+ const was = connected;
184
+ connected = false;
185
+ cancelAll("connection closed");
186
+ const why = reason.toString() || `closed (${code})`;
187
+ const willRetry = retry && !stopped;
188
+ emit({ type: "disconnected", reason: why, willRetry });
189
+ if (!readySettled) {
190
+ readySettled = true;
191
+ rejectReady(new Error(`could not connect to ${o.server}: ${why}`));
192
+ }
193
+ if (willRetry)
194
+ scheduleRetry(was);
195
+ });
196
+ ws.on("error", (e) => log("connection error", { message: String(e) }));
197
+ }).catch((e) => {
198
+ log("could not get an access token", { message: String(e) });
199
+ if (retry && !stopped)
200
+ scheduleRetry(false);
201
+ else if (!readySettled) {
202
+ readySettled = true;
203
+ rejectReady(e instanceof Error ? e : new Error(String(e)));
204
+ }
205
+ });
206
+ }
207
+ function scheduleRetry(wasConnected) {
208
+ if (wasConnected)
209
+ attempt = 0;
210
+ attempt++;
211
+ const wait = Math.min(maxBackoff, 1000 * 2 ** Math.min(attempt, 6));
212
+ retryTimer = setTimeout(connect, wait);
213
+ }
214
+ // Plugins start before the first connection; a failing plugin stops the client before it connects.
215
+ const starting = (async () => {
216
+ for (const p of active)
217
+ await p.start?.(resolved.get(p.name) ?? {});
218
+ connect();
219
+ })().catch((e) => {
220
+ stopped = true;
221
+ if (!readySettled) {
222
+ readySettled = true;
223
+ rejectReady(e instanceof Error ? e : new Error(String(e)));
224
+ }
225
+ });
226
+ return {
227
+ ready,
228
+ get connected() { return connected; },
229
+ capabilities,
230
+ async stop() {
231
+ stopped = true;
232
+ clearTimeout(retryTimer);
233
+ clearInterval(heartbeat);
234
+ await starting;
235
+ cancelAll("the agent is stopping");
236
+ try {
237
+ ws?.close(1000, "stopping");
238
+ }
239
+ catch { /* already closed */ }
240
+ for (const p of active)
241
+ await p.stop?.();
242
+ },
243
+ };
244
+ }
245
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,IAAI,CAAC;AAE3B,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AACzF,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,YAAY,EAA0D,MAAM,YAAY,CAAC;AAoF5H,MAAM,KAAK,GAAwB,IAAI,GAAG,CAAC,CAAC,WAAW,EAAE,mBAAmB,EAAE,SAAS,EAAE,SAAS,CAAC,CAAC,CAAC;AAErG,MAAM,UAAU,iBAAiB,CAAC,CAAgB;IAChD,YAAY,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;IACxB,MAAM,MAAM,GAAiB,CAAC,CAAC,MAAM,IAAI,EAAE,OAAO,EAAE,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC;IACrE,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAwB,CAAC;IACjD,MAAM,aAAa,GAAa,EAAE,CAAC;IACnC,KAAK,MAAM,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,CAAC;QAC1B,MAAM,CAAC,GAAG,aAAa,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,IAAI,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC,GAAG,CAAC,CA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,SAAS,CAAC,CAAC;YACzB,MAAM,QAAQ,CAAC;YACf,SAAS,CAAC,uBAAuB,CAAC,CAAC;YACnC,IAAI,CAAC;gBAAC,EAAE,EAAE,KAAK,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;YAAC,CAAC;YAAC,MAAM,CAAC,CAAC,oBAAoB,CAAC,CAAC;YACnE,KAAK,MAAM,CAAC,IAAI,MAAM;gBAAE,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;QAC3C,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,23 @@
1
+ import type { TokenSet } from "./device.js";
2
+ /**
3
+ * What the agent keeps on the machine after sign-in. The file is readable only by the user that runs the agent (mode 0600 where the
4
+ * operating system supports it). It holds the refresh token, which is as sensitive as a password: revoke it in the app to cut off the agent.
5
+ */
6
+ export interface StoredCredentials {
7
+ /** Which app the sign-in is for, e.g. "replayr". One file per app. */
8
+ app: string;
9
+ issuer: string;
10
+ clientId: string;
11
+ /** The server this machine connects to, as last given to `run`. */
12
+ server?: string;
13
+ /** Random id generated at first sign-in, identifying this install. */
14
+ machineId: string;
15
+ refreshToken?: string;
16
+ /** The last access token, so a restart does not need an immediate refresh. Replaced on every refresh. */
17
+ accessToken?: string;
18
+ accessExpiresAt?: number;
19
+ }
20
+ export declare function loadCredentials(path: string): Promise<StoredCredentials | null>;
21
+ export declare function saveCredentials(path: string, creds: StoredCredentials): Promise<void>;
22
+ /** Stores a fresh token set on top of what was there (keeps the refresh token when the provider did not send a new one). */
23
+ export declare function withTokens(creds: StoredCredentials, t: TokenSet): StoredCredentials;
@@ -0,0 +1,27 @@
1
+ import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import { dirname } from "node:path";
3
+ export async function loadCredentials(path) {
4
+ try {
5
+ return JSON.parse(await readFile(path, "utf8"));
6
+ }
7
+ catch (e) {
8
+ if (e.code === "ENOENT")
9
+ return null;
10
+ throw e;
11
+ }
12
+ }
13
+ export async function saveCredentials(path, creds) {
14
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
15
+ await writeFile(path, JSON.stringify(creds, null, 2) + "\n", { mode: 0o600 });
16
+ await chmod(path, 0o600).catch(() => { }); // on Windows the mode is ignored; the folder is per user there
17
+ }
18
+ /** Stores a fresh token set on top of what was there (keeps the refresh token when the provider did not send a new one). */
19
+ export function withTokens(creds, t) {
20
+ return {
21
+ ...creds,
22
+ refreshToken: t.refreshToken ?? creds.refreshToken,
23
+ accessToken: t.accessToken,
24
+ accessExpiresAt: t.issuedAt + t.expiresIn * 1000,
25
+ };
26
+ }
27
+ //# sourceMappingURL=credentials.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credentials.js","sourceRoot":"","sources":["../src/credentials.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACrE,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAsBpC,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,IAAY;IAChD,IAAI,CAAC;QACH,OAAO,IAAI,CAAC,KAAK,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC,CAAsB,CAAC;IACvE,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,IAAK,CAA2B,CAAC,IAAI,KAAK,QAAQ;YAAE,OAAO,IAAI,CAAC;QAChE,MAAM,CAAC,CAAC;IACV,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,IAAY,EAAE,KAAwB;IAC1E,MAAM,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;IAC7D,MAAM,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,GAAG,IAAI,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;IAC9E,MAAM,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC,CAAG,+DAA+D;AAC7G,CAAC;AAED,4HAA4H;AAC5H,MAAM,UAAU,UAAU,CAAC,KAAwB,EAAE,CAAW;IAC9D,OAAO;QACL,GAAG,KAAK;QACR,YAAY,EAAE,CAAC,CAAC,YAAY,IAAI,KAAK,CAAC,YAAY;QAClD,WAAW,EAAE,CAAC,CAAC,WAAW;QAC1B,eAAe,EAAE,CAAC,CAAC,QAAQ,GAAG,CAAC,CAAC,SAAS,GAAG,IAAI;KACjD,CAAC;AACJ,CAAC"}
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Sign-in for a machine without a browser (RFC 8628, the OAuth device flow). The agent asks the identity provider for a code, shows
3
+ * the user the code and a web address, then polls until the user approves it on any other device.
4
+ *
5
+ * Works with any OAuth provider that publishes OpenID discovery and supports the device grant (Clerk does). The client is public:
6
+ * no secret is stored on the machine.
7
+ */
8
+ export interface DeviceCode {
9
+ deviceCode: string;
10
+ userCode: string;
11
+ verificationUri: string;
12
+ verificationUriComplete?: string;
13
+ expiresIn: number;
14
+ interval: number;
15
+ }
16
+ export interface TokenSet {
17
+ accessToken: string;
18
+ refreshToken?: string;
19
+ /** Seconds until the access token expires, as the provider said when it was issued. */
20
+ expiresIn: number;
21
+ /** Epoch milliseconds when this set was issued, so callers can refresh before expiry. */
22
+ issuedAt: number;
23
+ }
24
+ export interface DeviceOptions {
25
+ /** The provider's issuer URL, e.g. https://clerk.example.com */
26
+ issuer: string;
27
+ clientId: string;
28
+ /** Space separated scopes, e.g. "profile email offline_access". */
29
+ scope: string;
30
+ fetch?: typeof fetch;
31
+ now?: () => number;
32
+ sleep?: (ms: number) => Promise<void>;
33
+ /** Called with the code while the agent waits, so the caller can print it. */
34
+ onCode?: (code: DeviceCode) => void;
35
+ }
36
+ export declare class DeviceLoginError extends Error {
37
+ readonly code: "access_denied" | "expired_token" | "server_error" | "invalid_response";
38
+ constructor(code: "access_denied" | "expired_token" | "server_error" | "invalid_response", message: string);
39
+ }
40
+ interface Endpoints {
41
+ deviceAuthorization: string;
42
+ token: string;
43
+ }
44
+ /** Reads the provider's endpoints from its OpenID discovery document. */
45
+ export declare function discover(issuer: string, f?: typeof fetch): Promise<Endpoints>;
46
+ /** Asks for a device code. Show `userCode` and `verificationUri` to the person; they approve it in a browser. */
47
+ export declare function startDeviceLogin(o: DeviceOptions): Promise<DeviceCode>;
48
+ /**
49
+ * Waits until the person approves the code, then returns the tokens. Follows RFC 8628: keeps polling on `authorization_pending`,
50
+ * slows down on `slow_down`, and stops with a clear error on `access_denied` or `expired_token`.
51
+ */
52
+ export declare function waitForApproval(o: DeviceOptions, code: DeviceCode): Promise<TokenSet>;
53
+ /** Trades a refresh token for a new access token. The provider may also return a new refresh token; the caller must keep it. */
54
+ export declare function refreshTokens(o: DeviceOptions, refreshToken: string): Promise<TokenSet>;
55
+ export {};
package/dist/device.js ADDED
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Sign-in for a machine without a browser (RFC 8628, the OAuth device flow). The agent asks the identity provider for a code, shows
3
+ * the user the code and a web address, then polls until the user approves it on any other device.
4
+ *
5
+ * Works with any OAuth provider that publishes OpenID discovery and supports the device grant (Clerk does). The client is public:
6
+ * no secret is stored on the machine.
7
+ */
8
+ export class DeviceLoginError extends Error {
9
+ code;
10
+ constructor(code, message) {
11
+ super(message);
12
+ this.code = code;
13
+ }
14
+ }
15
+ const defaultSleep = (ms) => new Promise((r) => setTimeout(r, ms));
16
+ /** Reads the provider's endpoints from its OpenID discovery document. */
17
+ export async function discover(issuer, f = fetch) {
18
+ const base = issuer.replace(/\/$/, "");
19
+ const res = await f(`${base}/.well-known/openid-configuration`, { headers: { accept: "application/json" } });
20
+ if (!res.ok)
21
+ throw new DeviceLoginError("server_error", `could not read ${base} discovery (HTTP ${res.status})`);
22
+ const d = (await res.json());
23
+ const deviceAuthorization = d.device_authorization_endpoint, token = d.token_endpoint;
24
+ if (typeof deviceAuthorization !== "string" || typeof token !== "string") {
25
+ throw new DeviceLoginError("invalid_response", `${base} does not offer the device sign-in`);
26
+ }
27
+ return { deviceAuthorization, token };
28
+ }
29
+ /** Asks for a device code. Show `userCode` and `verificationUri` to the person; they approve it in a browser. */
30
+ export async function startDeviceLogin(o) {
31
+ const f = o.fetch ?? fetch;
32
+ const ep = await discover(o.issuer, f);
33
+ const res = await f(ep.deviceAuthorization, {
34
+ method: "POST",
35
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
36
+ body: new URLSearchParams({ client_id: o.clientId, scope: o.scope }),
37
+ });
38
+ const d = (await res.json().catch(() => null));
39
+ if (!res.ok || !d)
40
+ throw new DeviceLoginError("server_error", `the provider refused the sign-in request (HTTP ${res.status})`);
41
+ if (typeof d.device_code !== "string" || typeof d.user_code !== "string" || typeof d.verification_uri !== "string") {
42
+ throw new DeviceLoginError("invalid_response", "the provider's answer had no device code");
43
+ }
44
+ return {
45
+ deviceCode: d.device_code,
46
+ userCode: d.user_code,
47
+ verificationUri: d.verification_uri,
48
+ verificationUriComplete: typeof d.verification_uri_complete === "string" ? d.verification_uri_complete : undefined,
49
+ expiresIn: typeof d.expires_in === "number" ? d.expires_in : 600,
50
+ interval: typeof d.interval === "number" ? d.interval : 5,
51
+ };
52
+ }
53
+ /**
54
+ * Waits until the person approves the code, then returns the tokens. Follows RFC 8628: keeps polling on `authorization_pending`,
55
+ * slows down on `slow_down`, and stops with a clear error on `access_denied` or `expired_token`.
56
+ */
57
+ export async function waitForApproval(o, code) {
58
+ const f = o.fetch ?? fetch, now = o.now ?? Date.now, sleep = o.sleep ?? defaultSleep;
59
+ const ep = await discover(o.issuer, f);
60
+ const deadline = now() + code.expiresIn * 1000;
61
+ let interval = code.interval;
62
+ for (;;) {
63
+ if (now() >= deadline)
64
+ throw new DeviceLoginError("expired_token", "the code expired before it was approved; start again");
65
+ await sleep(interval * 1000);
66
+ const res = await f(ep.token, {
67
+ method: "POST",
68
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
69
+ body: new URLSearchParams({ grant_type: "urn:ietf:params:oauth:grant-type:device_code", device_code: code.deviceCode, client_id: o.clientId }),
70
+ });
71
+ const body = (await res.json().catch(() => null));
72
+ if (res.ok && body && typeof body.access_token === "string")
73
+ return tokenSet(body, now());
74
+ const error = body && typeof body.error === "string" ? body.error : "";
75
+ if (error === "authorization_pending")
76
+ continue;
77
+ if (error === "slow_down") {
78
+ interval += 5;
79
+ continue;
80
+ }
81
+ if (error === "access_denied")
82
+ throw new DeviceLoginError("access_denied", "the sign-in was refused");
83
+ if (error === "expired_token")
84
+ throw new DeviceLoginError("expired_token", "the code expired before it was approved; start again");
85
+ throw new DeviceLoginError("server_error", `the provider returned HTTP ${res.status}${error ? ` (${error})` : ""}`);
86
+ }
87
+ }
88
+ /** Trades a refresh token for a new access token. The provider may also return a new refresh token; the caller must keep it. */
89
+ export async function refreshTokens(o, refreshToken) {
90
+ const f = o.fetch ?? fetch, now = o.now ?? Date.now;
91
+ const ep = await discover(o.issuer, f);
92
+ const res = await f(ep.token, {
93
+ method: "POST",
94
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
95
+ body: new URLSearchParams({ grant_type: "refresh_token", refresh_token: refreshToken, client_id: o.clientId }),
96
+ });
97
+ const body = (await res.json().catch(() => null));
98
+ if (!res.ok || !body || typeof body.access_token !== "string") {
99
+ throw new DeviceLoginError("server_error", `could not refresh the sign-in (HTTP ${res.status}); sign in again`);
100
+ }
101
+ return tokenSet(body, now(), refreshToken);
102
+ }
103
+ function tokenSet(body, issuedAt, keepRefresh) {
104
+ return {
105
+ accessToken: body.access_token,
106
+ refreshToken: typeof body.refresh_token === "string" ? body.refresh_token : keepRefresh,
107
+ expiresIn: typeof body.expires_in === "number" ? body.expires_in : 3600,
108
+ issuedAt,
109
+ };
110
+ }
111
+ //# sourceMapping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