@perspectask/sdk 0.0.6 → 0.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -194,7 +194,7 @@ const { data: task } = await pt.tasks.get('abc');
194
194
  console.log(task?.pr_token); // "pt-abc12f4" — put it in the branch or PR title
195
195
 
196
196
  const { data: prs } = await pt.tasks.pullRequests.list('abc');
197
- // [{ id, repo, number, title, url, state, checks?, review?, preview_url?, draft?, linked_by }]
197
+ // [{ id, repo, number, title, url, state, checks?, review?, preview_url?, preview_status?, draft?, linked_by }]
198
198
 
199
199
  await pt.tasks.pullRequests.link('abc', 'https://github.com/owner/repo/pull/12'); // or 'owner/repo#12'
200
200
  await pt.tasks.pullRequests.unlink('abc', prs![0].id);
@@ -0,0 +1,120 @@
1
+ // src/oauth.ts
2
+ var CLI_CLIENT_ID = "perspectask-cli";
3
+ var DEFAULT_BASE_URL = "https://api.perspectask.com/v1";
4
+ var DEVICE_CODE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
5
+ var SLOW_DOWN_STEP_SECONDS = 5;
6
+ var OAuthTokenError = class extends Error {
7
+ constructor(code, message) {
8
+ super(message);
9
+ this.code = code;
10
+ this.name = "OAuthTokenError";
11
+ }
12
+ code;
13
+ };
14
+ function oauthUrl(baseUrl, path) {
15
+ return new URL(path, new URL(baseUrl ?? DEFAULT_BASE_URL).origin).toString();
16
+ }
17
+ async function postForm(url, params, fetchImpl = fetch) {
18
+ const response = await fetchImpl(url, {
19
+ method: "POST",
20
+ headers: {
21
+ "Content-Type": "application/x-www-form-urlencoded",
22
+ Accept: "application/json"
23
+ },
24
+ body: new URLSearchParams(params).toString()
25
+ });
26
+ const body = await response.json().catch(() => ({}));
27
+ if (!response.ok) {
28
+ throw new OAuthTokenError(
29
+ typeof body.error === "string" ? body.error : `http_${response.status}`,
30
+ typeof body.error_description === "string" ? body.error_description : `OAuth request failed (${response.status})`
31
+ );
32
+ }
33
+ return body;
34
+ }
35
+ function toTokens(body) {
36
+ return {
37
+ accessToken: String(body.access_token),
38
+ refreshToken: String(body.refresh_token),
39
+ expiresAt: Date.now() + Number(body.expires_in) * 1e3,
40
+ scope: typeof body.scope === "string" ? body.scope : ""
41
+ };
42
+ }
43
+ async function startDeviceLogin(options = {}) {
44
+ const body = await postForm(
45
+ oauthUrl(options.baseUrl, "/oauth/device"),
46
+ {
47
+ client_id: CLI_CLIENT_ID,
48
+ ...options.scope ? { scope: options.scope } : {},
49
+ ...options.deviceName ? { device_name: options.deviceName } : {}
50
+ },
51
+ options.fetch
52
+ );
53
+ return {
54
+ deviceCode: String(body.device_code),
55
+ userCode: String(body.user_code),
56
+ verificationUri: String(body.verification_uri),
57
+ verificationUriComplete: String(body.verification_uri_complete),
58
+ expiresIn: Number(body.expires_in),
59
+ interval: Number(body.interval)
60
+ };
61
+ }
62
+ async function waitForDeviceLogin(login, options = {}) {
63
+ const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
64
+ let interval = login.interval;
65
+ for (; ; ) {
66
+ await sleep(interval * 1e3);
67
+ try {
68
+ return toTokens(
69
+ await postForm(
70
+ oauthUrl(options.baseUrl, "/oauth/token"),
71
+ {
72
+ grant_type: DEVICE_CODE_GRANT_TYPE,
73
+ device_code: login.deviceCode,
74
+ client_id: CLI_CLIENT_ID
75
+ },
76
+ options.fetch
77
+ )
78
+ );
79
+ } catch (error) {
80
+ if (!(error instanceof OAuthTokenError)) throw error;
81
+ if (error.code === "authorization_pending") continue;
82
+ if (error.code === "slow_down") {
83
+ interval += SLOW_DOWN_STEP_SECONDS;
84
+ continue;
85
+ }
86
+ throw error;
87
+ }
88
+ }
89
+ }
90
+ async function refreshTokens(refreshToken, options = {}) {
91
+ return toTokens(
92
+ await postForm(
93
+ oauthUrl(options.baseUrl, "/oauth/token"),
94
+ {
95
+ grant_type: "refresh_token",
96
+ refresh_token: refreshToken,
97
+ client_id: CLI_CLIENT_ID
98
+ },
99
+ options.fetch
100
+ )
101
+ );
102
+ }
103
+ async function revokeTokens(token, options = {}) {
104
+ await postForm(
105
+ oauthUrl(options.baseUrl, "/oauth/revoke"),
106
+ { token, client_id: CLI_CLIENT_ID },
107
+ options.fetch
108
+ ).catch(() => void 0);
109
+ }
110
+
111
+ export {
112
+ CLI_CLIENT_ID,
113
+ DEFAULT_BASE_URL,
114
+ OAuthTokenError,
115
+ startDeviceLogin,
116
+ waitForDeviceLogin,
117
+ refreshTokens,
118
+ revokeTokens
119
+ };
120
+ //# sourceMappingURL=chunk-56FPFSE2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/oauth.ts"],"sourcesContent":["export const CLI_CLIENT_ID = \"perspectask-cli\";\nexport const DEFAULT_BASE_URL = \"https://api.perspectask.com/v1\";\n\nconst DEVICE_CODE_GRANT_TYPE = \"urn:ietf:params:oauth:grant-type:device_code\";\nconst SLOW_DOWN_STEP_SECONDS = 5;\n\nexport interface OAuthTokens {\n accessToken: string;\n refreshToken: string;\n /** Milliseconds since the epoch. */\n expiresAt: number;\n scope: string;\n}\n\nexport interface DeviceLogin {\n deviceCode: string;\n userCode: string;\n verificationUri: string;\n verificationUriComplete: string;\n expiresIn: number;\n interval: number;\n}\n\nexport interface OAuthRequestOptions {\n /** The API base URL, e.g. `https://api.perspectask.com/v1`. OAuth endpoints live on the same origin. */\n baseUrl?: string;\n fetch?: typeof fetch;\n}\n\n/** An OAuth error response. `code` is the RFC 6749 error, e.g. `invalid_grant`. */\nexport class OAuthTokenError extends Error {\n constructor(\n public readonly code: string,\n message: string,\n ) {\n super(message);\n this.name = \"OAuthTokenError\";\n }\n}\n\nfunction oauthUrl(baseUrl: string | undefined, path: string): string {\n return new URL(path, new URL(baseUrl ?? DEFAULT_BASE_URL).origin).toString();\n}\n\nasync function postForm(\n url: string,\n params: Record<string, string>,\n fetchImpl: typeof fetch = fetch,\n): Promise<Record<string, unknown>> {\n const response = await fetchImpl(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Accept: \"application/json\",\n },\n body: new URLSearchParams(params).toString(),\n });\n const body = (await response.json().catch(() => ({}))) as Record<\n string,\n unknown\n >;\n\n if (!response.ok) {\n throw new OAuthTokenError(\n typeof body.error === \"string\" ? body.error : `http_${response.status}`,\n typeof body.error_description === \"string\"\n ? body.error_description\n : `OAuth request failed (${response.status})`,\n );\n }\n return body;\n}\n\nfunction toTokens(body: Record<string, unknown>): OAuthTokens {\n return {\n accessToken: String(body.access_token),\n refreshToken: String(body.refresh_token),\n expiresAt: Date.now() + Number(body.expires_in) * 1000,\n scope: typeof body.scope === \"string\" ? body.scope : \"\",\n };\n}\n\n/** Start a browser login for a terminal. Show `verificationUriComplete` to the user, then call `waitForDeviceLogin`. */\nexport async function startDeviceLogin(\n options: OAuthRequestOptions & {\n scope?: string;\n /** Shown on the approval page and under Connected apps, e.g. the machine's hostname. */\n deviceName?: string;\n } = {},\n): Promise<DeviceLogin> {\n const body = await postForm(\n oauthUrl(options.baseUrl, \"/oauth/device\"),\n {\n client_id: CLI_CLIENT_ID,\n ...(options.scope ? { scope: options.scope } : {}),\n ...(options.deviceName ? { device_name: options.deviceName } : {}),\n },\n options.fetch,\n );\n\n return {\n deviceCode: String(body.device_code),\n userCode: String(body.user_code),\n verificationUri: String(body.verification_uri),\n verificationUriComplete: String(body.verification_uri_complete),\n expiresIn: Number(body.expires_in),\n interval: Number(body.interval),\n };\n}\n\n/** Poll until the user approves (resolves with tokens) or denies or lets the code expire (rejects with an `OAuthTokenError`). */\nexport async function waitForDeviceLogin(\n login: DeviceLogin,\n options: OAuthRequestOptions & {\n sleep?: (ms: number) => Promise<void>;\n } = {},\n): Promise<OAuthTokens> {\n const sleep =\n options.sleep ??\n ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));\n let interval = login.interval;\n\n for (;;) {\n await sleep(interval * 1000);\n try {\n return toTokens(\n await postForm(\n oauthUrl(options.baseUrl, \"/oauth/token\"),\n {\n grant_type: DEVICE_CODE_GRANT_TYPE,\n device_code: login.deviceCode,\n client_id: CLI_CLIENT_ID,\n },\n options.fetch,\n ),\n );\n } catch (error) {\n if (!(error instanceof OAuthTokenError)) throw error;\n if (error.code === \"authorization_pending\") continue;\n if (error.code === \"slow_down\") {\n interval += SLOW_DOWN_STEP_SECONDS;\n continue;\n }\n throw error;\n }\n }\n}\n\n/** Trade a refresh token for new tokens. The old refresh token stops working. */\nexport async function refreshTokens(\n refreshToken: string,\n options: OAuthRequestOptions = {},\n): Promise<OAuthTokens> {\n return toTokens(\n await postForm(\n oauthUrl(options.baseUrl, \"/oauth/token\"),\n {\n grant_type: \"refresh_token\",\n refresh_token: refreshToken,\n client_id: CLI_CLIENT_ID,\n },\n options.fetch,\n ),\n );\n}\n\n/** Sign out: the access and refresh token both stop working. */\nexport async function revokeTokens(\n token: string,\n options: OAuthRequestOptions = {},\n): Promise<void> {\n await postForm(\n oauthUrl(options.baseUrl, \"/oauth/revoke\"),\n { token, client_id: CLI_CLIENT_ID },\n options.fetch,\n ).catch(() => undefined);\n}\n"],"mappings":";AAAO,IAAM,gBAAgB;AACtB,IAAM,mBAAmB;AAEhC,IAAM,yBAAyB;AAC/B,IAAM,yBAAyB;AA0BxB,IAAM,kBAAN,cAA8B,MAAM;AAAA,EACzC,YACkB,MAChB,SACA;AACA,UAAM,OAAO;AAHG;AAIhB,SAAK,OAAO;AAAA,EACd;AAAA,EALkB;AAMpB;AAEA,SAAS,SAAS,SAA6B,MAAsB;AACnE,SAAO,IAAI,IAAI,MAAM,IAAI,IAAI,WAAW,gBAAgB,EAAE,MAAM,EAAE,SAAS;AAC7E;AAEA,eAAe,SACb,KACA,QACA,YAA0B,OACQ;AAClC,QAAM,WAAW,MAAM,UAAU,KAAK;AAAA,IACpC,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,gBAAgB;AAAA,MAChB,QAAQ;AAAA,IACV;AAAA,IACA,MAAM,IAAI,gBAAgB,MAAM,EAAE,SAAS;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AW,SAAS,EAAE,CAAC;AACzE,MAAI,WAAW,MAAM;AAErB,aAAS;AACP,UAAM,MAAM,WAAW,GAAI;AAC3B,QAAI;AACF,aAAO;AAAA,QACL,MAAM;AAAA,UACJ,SAAS,QAAQ,SAAS,cAAc;AAAA,UACxC;AAAA,YACE,YAAY;AAAA,YACZ,aAAa,MAAM;AAAA,YACnB,WAAW;AAAA,UACb;AAAA,UACA,QAAQ;AAAA,QACV;AAAA,MACF;AAAA,IACF,SAAS,OAAO;AACd,UAAI,EAAE,iBAAiB,iBAAkB,OAAM;AAC/C,UAAI,MAAM,SAAS,wBAAyB;AAC5C,UAAI,MAAM,SAAS,aAAa;AAC9B,oBAAY;AACZ;AAAA,MACF;AACA,YAAM;AAAA,IACR;AAAA,EACF;AACF;AAGA,eAAsB,cACpB,cACA,UAA+B,CAAC,GACV;AACtB,SAAO;AAAA,IACL,MAAM;AAAA,MACJ,SAAS,QAAQ,SAAS,cAAc;AAAA,MACxC;AAAA,QACE,YAAY;AAAA,QACZ,eAAe;AAAA,QACf,WAAW;AAAA,MACb;AAAA,MACA,QAAQ;AAAA,IACV;AAAA,EACF;AACF;AAGA,eAAsB,aACpB,OACA,UAA+B,CAAC,GACjB;AACf,QAAM;AAAA,IACJ,SAAS,QAAQ,SAAS,eAAe;AAAA,IACzC,EAAE,OAAO,WAAW,cAAc;AAAA,IAClC,QAAQ;AAAA,EACV,EAAE,MAAM,MAAM,MAAS;AACzB;","names":[]}
@@ -0,0 +1,169 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/credentials.ts
21
+ var credentials_exports = {};
22
+ __export(credentials_exports, {
23
+ CONFIG_PATH: () => CONFIG_PATH,
24
+ LoginExpiredError: () => LoginExpiredError,
25
+ readConfig: () => readConfig,
26
+ resolveCredential: () => resolveCredential,
27
+ writeConfig: () => writeConfig
28
+ });
29
+ module.exports = __toCommonJS(credentials_exports);
30
+ var import_node_fs = require("fs");
31
+ var import_node_os = require("os");
32
+ var import_node_path = require("path");
33
+
34
+ // src/oauth.ts
35
+ var CLI_CLIENT_ID = "perspectask-cli";
36
+ var DEFAULT_BASE_URL = "https://api.perspectask.com/v1";
37
+ var OAuthTokenError = class extends Error {
38
+ constructor(code, message) {
39
+ super(message);
40
+ this.code = code;
41
+ this.name = "OAuthTokenError";
42
+ }
43
+ code;
44
+ };
45
+ function oauthUrl(baseUrl, path) {
46
+ return new URL(path, new URL(baseUrl ?? DEFAULT_BASE_URL).origin).toString();
47
+ }
48
+ async function postForm(url, params, fetchImpl = fetch) {
49
+ const response = await fetchImpl(url, {
50
+ method: "POST",
51
+ headers: {
52
+ "Content-Type": "application/x-www-form-urlencoded",
53
+ Accept: "application/json"
54
+ },
55
+ body: new URLSearchParams(params).toString()
56
+ });
57
+ const body = await response.json().catch(() => ({}));
58
+ if (!response.ok) {
59
+ throw new OAuthTokenError(
60
+ typeof body.error === "string" ? body.error : `http_${response.status}`,
61
+ typeof body.error_description === "string" ? body.error_description : `OAuth request failed (${response.status})`
62
+ );
63
+ }
64
+ return body;
65
+ }
66
+ function toTokens(body) {
67
+ return {
68
+ accessToken: String(body.access_token),
69
+ refreshToken: String(body.refresh_token),
70
+ expiresAt: Date.now() + Number(body.expires_in) * 1e3,
71
+ scope: typeof body.scope === "string" ? body.scope : ""
72
+ };
73
+ }
74
+ async function refreshTokens(refreshToken, options = {}) {
75
+ return toTokens(
76
+ await postForm(
77
+ oauthUrl(options.baseUrl, "/oauth/token"),
78
+ {
79
+ grant_type: "refresh_token",
80
+ refresh_token: refreshToken,
81
+ client_id: CLI_CLIENT_ID
82
+ },
83
+ options.fetch
84
+ )
85
+ );
86
+ }
87
+
88
+ // src/credentials.ts
89
+ var CONFIG_PATH = (0, import_node_path.join)((0, import_node_os.homedir)(), ".perspectask", "config.json");
90
+ var REFRESH_MARGIN_MS = 6e4;
91
+ function readConfig() {
92
+ try {
93
+ return JSON.parse((0, import_node_fs.readFileSync)(CONFIG_PATH, "utf8"));
94
+ } catch {
95
+ return {};
96
+ }
97
+ }
98
+ function writeConfig(config) {
99
+ (0, import_node_fs.mkdirSync)((0, import_node_path.dirname)(CONFIG_PATH), { recursive: true, mode: 448 });
100
+ (0, import_node_fs.writeFileSync)(CONFIG_PATH, JSON.stringify(config, null, 2), { mode: 384 });
101
+ (0, import_node_fs.chmodSync)(CONFIG_PATH, 384);
102
+ return CONFIG_PATH;
103
+ }
104
+ var LoginExpiredError = class extends Error {
105
+ constructor() {
106
+ super("Your PerspecTask login has expired. Run `pt login` again.");
107
+ this.name = "LoginExpiredError";
108
+ }
109
+ };
110
+ var refreshing = null;
111
+ async function refreshStoredLogin(stored, baseUrl) {
112
+ try {
113
+ const oauth = await refreshTokens(stored.refreshToken, { baseUrl });
114
+ writeConfig({ ...readConfig(), oauth });
115
+ return oauth.accessToken;
116
+ } catch (error) {
117
+ const latest = readConfig().oauth;
118
+ if (latest && latest.refreshToken !== stored.refreshToken && latest.expiresAt > Date.now()) {
119
+ return latest.accessToken;
120
+ }
121
+ if (error.code === "invalid_grant") {
122
+ throw new LoginExpiredError();
123
+ }
124
+ throw error;
125
+ }
126
+ }
127
+ async function currentAccessToken(baseUrl) {
128
+ const stored = readConfig().oauth;
129
+ if (!stored) throw new LoginExpiredError();
130
+ if (stored.expiresAt - REFRESH_MARGIN_MS > Date.now()) {
131
+ return stored.accessToken;
132
+ }
133
+ refreshing ??= refreshStoredLogin(stored, baseUrl).finally(() => {
134
+ refreshing = null;
135
+ });
136
+ return refreshing;
137
+ }
138
+ function resolveCredential() {
139
+ const config = readConfig();
140
+ const baseUrl = process.env.PERSPECTASK_API_URL ?? config.baseUrl;
141
+ const withBaseUrl = baseUrl ? { baseUrl } : {};
142
+ if (process.env.PERSPECTASK_API_KEY) {
143
+ return {
144
+ apiKey: process.env.PERSPECTASK_API_KEY,
145
+ source: "environment",
146
+ ...withBaseUrl
147
+ };
148
+ }
149
+ if (config.oauth) {
150
+ return {
151
+ apiKey: () => currentAccessToken(baseUrl),
152
+ source: "login",
153
+ ...withBaseUrl
154
+ };
155
+ }
156
+ if (config.apiKey) {
157
+ return { apiKey: config.apiKey, source: "api_key", ...withBaseUrl };
158
+ }
159
+ return null;
160
+ }
161
+ // Annotate the CommonJS export names for ESM import in node:
162
+ 0 && (module.exports = {
163
+ CONFIG_PATH,
164
+ LoginExpiredError,
165
+ readConfig,
166
+ resolveCredential,
167
+ writeConfig
168
+ });
169
+ //# sourceMappingURL=credentials.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/credentials.ts","../src/oauth.ts"],"sourcesContent":["import { chmodSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport { type DeviceLogin, type OAuthTokens, refreshTokens } from \"./oauth\";\n\nexport const CONFIG_PATH = join(homedir(), \".perspectask\", \"config.json\");\n\nconst REFRESH_MARGIN_MS = 60_000;\n\nexport interface StoredConfig {\n apiKey?: string;\n baseUrl?: string;\n oauth?: OAuthTokens;\n /** A `pt login --no-wait` that has not been approved yet. `expiresAt` is in ms. */\n pendingLogin?: DeviceLogin & { expiresAt: number; baseUrl?: string };\n}\n\nexport function readConfig(): StoredConfig {\n try {\n return JSON.parse(readFileSync(CONFIG_PATH, \"utf8\")) as StoredConfig;\n } catch {\n return {};\n }\n}\n\n/** Writes `~/.perspectask/config.json` readable by the owning user only. */\nexport function writeConfig(config: StoredConfig): string {\n mkdirSync(dirname(CONFIG_PATH), { recursive: true, mode: 0o700 });\n writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2), { mode: 0o600 });\n chmodSync(CONFIG_PATH, 0o600);\n return CONFIG_PATH;\n}\n\nexport class LoginExpiredError extends Error {\n constructor() {\n super(\"Your PerspecTask login has expired. Run `pt login` again.\");\n this.name = \"LoginExpiredError\";\n }\n}\n\nlet refreshing: Promise<string> | null = null;\n\nasync function refreshStoredLogin(\n stored: OAuthTokens,\n baseUrl: string | undefined,\n): Promise<string> {\n try {\n const oauth = await refreshTokens(stored.refreshToken, { baseUrl });\n writeConfig({ ...readConfig(), oauth });\n return oauth.accessToken;\n } catch (error) {\n const latest = readConfig().oauth;\n if (\n latest &&\n latest.refreshToken !== stored.refreshToken &&\n latest.expiresAt > Date.now()\n ) {\n return latest.accessToken;\n }\n if ((error as { code?: string }).code === \"invalid_grant\") {\n throw new LoginExpiredError();\n }\n throw error;\n }\n}\n\nasync function currentAccessToken(\n baseUrl: string | undefined,\n): Promise<string> {\n const stored = readConfig().oauth;\n if (!stored) throw new LoginExpiredError();\n if (stored.expiresAt - REFRESH_MARGIN_MS > Date.now()) {\n return stored.accessToken;\n }\n\n refreshing ??= refreshStoredLogin(stored, baseUrl).finally(() => {\n refreshing = null;\n });\n return refreshing;\n}\n\nexport interface ResolvedCredential {\n apiKey: string | (() => Promise<string>);\n baseUrl?: string;\n source: \"environment\" | \"login\" | \"api_key\";\n}\n\n/**\n * The credential the CLI and the local MCP server use, in order: `PERSPECTASK_API_KEY`,\n * the login saved by `pt login` (refreshed when it expires), then a key saved\n * with `pt auth set`. `PERSPECTASK_API_URL` overrides the saved base URL.\n */\nexport function resolveCredential(): ResolvedCredential | null {\n const config = readConfig();\n const baseUrl = process.env.PERSPECTASK_API_URL ?? config.baseUrl;\n const withBaseUrl = baseUrl ? { baseUrl } : {};\n\n if (process.env.PERSPECTASK_API_KEY) {\n return {\n apiKey: process.env.PERSPECTASK_API_KEY,\n source: \"environment\",\n ...withBaseUrl,\n };\n }\n if (config.oauth) {\n return {\n apiKey: () => currentAccessToken(baseUrl),\n source: \"login\",\n ...withBaseUrl,\n };\n }\n if (config.apiKey) {\n return { apiKey: config.apiKey, source: \"api_key\", ...withBaseUrl };\n }\n return null;\n}\n","export const CLI_CLIENT_ID = \"perspectask-cli\";\nexport const DEFAULT_BASE_URL = \"https://api.perspectask.com/v1\";\n\nconst DEVICE_CODE_GRANT_TYPE = \"urn:ietf:params:oauth:grant-type:device_code\";\nconst SLOW_DOWN_STEP_SECONDS = 5;\n\nexport interface OAuthTokens {\n accessToken: string;\n refreshToken: string;\n /** Milliseconds since the epoch. */\n expiresAt: number;\n scope: string;\n}\n\nexport interface DeviceLogin {\n deviceCode: string;\n userCode: string;\n verificationUri: string;\n verificationUriComplete: string;\n expiresIn: number;\n interval: number;\n}\n\nexport interface OAuthRequestOptions {\n /** The API base URL, e.g. `https://api.perspectask.com/v1`. OAuth endpoints live on the same origin. */\n baseUrl?: string;\n fetch?: typeof fetch;\n}\n\n/** An OAuth error response. `code` is the RFC 6749 error, e.g. `invalid_grant`. */\nexport class OAuthTokenError extends Error {\n constructor(\n public readonly code: string,\n message: string,\n ) {\n super(message);\n this.name = \"OAuthTokenError\";\n }\n}\n\nfunction oauthUrl(baseUrl: string | undefined, path: string): string {\n return new URL(path, new URL(baseUrl ?? DEFAULT_BASE_URL).origin).toString();\n}\n\nasync function postForm(\n url: string,\n params: Record<string, string>,\n fetchImpl: typeof fetch = fetch,\n): Promise<Record<string, unknown>> {\n const response = await fetchImpl(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Accept: \"application/json\",\n },\n body: new URLSearchParams(params).toString(),\n });\n const body = (await response.json().catch(() => ({}))) as Record<\n string,\n unknown\n >;\n\n if (!response.ok) {\n throw new OAuthTokenError(\n typeof body.error === \"string\" ? body.error : `http_${response.status}`,\n typeof body.error_description === \"string\"\n ? body.error_description\n : `OAuth request failed (${response.status})`,\n );\n }\n return body;\n}\n\nfunction toTokens(body: Record<string, unknown>): OAuthTokens {\n return {\n accessToken: String(body.access_token),\n refreshToken: String(body.refresh_token),\n expiresAt: Date.now() + Number(body.expires_in) * 1000,\n scope: typeof body.scope === \"string\" ? body.scope : \"\",\n };\n}\n\n/** Start a browser login for a terminal. Show `verificationUriComplete` to the user, then call `waitForDeviceLogin`. */\nexport async function startDeviceLogin(\n options: OAuthRequestOptions & {\n scope?: string;\n /** Shown on the approval page and under Connected apps, e.g. the machine's hostname. */\n deviceName?: string;\n } = {},\n): Promise<DeviceLogin> {\n const body = await postForm(\n oauthUrl(options.baseUrl, \"/oauth/device\"),\n {\n client_id: CLI_CLIENT_ID,\n ...(options.scope ? { scope: options.scope } : {}),\n ...(options.deviceName ? { device_name: options.deviceName } : {}),\n },\n options.fetch,\n );\n\n return {\n deviceCode: String(body.device_code),\n userCode: String(body.user_code),\n verificationUri: String(body.verification_uri),\n verificationUriComplete: String(body.verification_uri_complete),\n expiresIn: Number(body.expires_in),\n interval: Number(body.interval),\n };\n}\n\n/** Poll until the user approves (resolves with tokens) or denies or lets the code expire (rejects with an `OAuthTokenError`). */\nexport async function waitForDeviceLogin(\n login: DeviceLogin,\n options: OAuthRequestOptions & {\n sleep?: (ms: number) => Promise<void>;\n } = {},\n): Promise<OAuthTokens> {\n const sleep =\n options.sleep ??\n ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));\n let interval = login.interval;\n\n for (;;) {\n await sleep(interval * 1000);\n try {\n return toTokens(\n await postForm(\n oauthUrl(options.baseUrl, \"/oauth/token\"),\n {\n grant_type: DEVICE_CODE_GRANT_TYPE,\n device_code: login.deviceCode,\n client_id: CLI_CLIENT_ID,\n },\n options.fetch,\n ),\n );\n } catch (error) {\n if (!(error instanceof OAuthTokenError)) throw error;\n if (error.code === \"authorization_pending\") continue;\n if (error.code === \"slow_down\") {\n interval += SLOW_DOWN_STEP_SECONDS;\n continue;\n }\n throw error;\n }\n }\n}\n\n/** Trade a refresh token for new tokens. The old refresh token stops working. */\nexport async function refreshTokens(\n refreshToken: string,\n options: OAuthRequestOptions = {},\n): Promise<OAuthTokens> {\n return toTokens(\n await postForm(\n oauthUrl(options.baseUrl, \"/oauth/token\"),\n {\n grant_type: \"refresh_token\",\n refresh_token: refreshToken,\n client_id: CLI_CLIENT_ID,\n },\n options.fetch,\n ),\n );\n}\n\n/** Sign out: the access and refresh token both stop working. */\nexport async function revokeTokens(\n token: string,\n options: OAuthRequestOptions = {},\n): Promise<void> {\n await postForm(\n oauthUrl(options.baseUrl, \"/oauth/revoke\"),\n { token, client_id: CLI_CLIENT_ID },\n options.fetch,\n ).catch(() => undefined);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAAkE;AAClE,qBAAwB;AACxB,uBAA8B;;;ACFvB,IAAM,gBAAgB;AACtB,IAAM,mBAAmB;AA6BzB,IAAM,kBAAN,cAA8B,MAAM;AAAA,EACzC,YACkB,MAChB,SACA;AACA,UAAM,OAAO;AAHG;AAIhB,SAAK,OAAO;AAAA,EACd;AAAA,EALkB;AAMpB;AAEA,SAAS,SAAS,SAA6B,MAAsB;AACnE,SAAO,IAAI,IAAI,MAAM,IAAI,IAAI,WAAW,gBAAgB,EAAE,MAAM,EAAE,SAAS;AAC7E;AAEA,eAAe,SACb,KACA,QACA,YAA0B,OACQ;AAClC,QAAM,WAAW,MAAM,UAAU,KAAK;AAAA,IACpC,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,gBAAgB;AAAA,MAChB,QAAQ;AAAA,IACV;AAAA,IACA,MAAM,IAAI,gBAAgB,MAAM,EAAE,SAAS;AAAA,EAC7C,CAAC;AACD,QAAM,OAAQ,MAAM,SAAS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AAO,QAAQ,QAAQ,WAAW,GAAG,YAAY;AAAA,EACpE;AACA,SAAO;AACT;","names":[]}
@@ -0,0 +1,32 @@
1
+ import { O as OAuthTokens, D as DeviceLogin } from './oauth-kp6GpoOV.cjs';
2
+
3
+ declare const CONFIG_PATH: string;
4
+ interface StoredConfig {
5
+ apiKey?: string;
6
+ baseUrl?: string;
7
+ oauth?: OAuthTokens;
8
+ /** A `pt login --no-wait` that has not been approved yet. `expiresAt` is in ms. */
9
+ pendingLogin?: DeviceLogin & {
10
+ expiresAt: number;
11
+ baseUrl?: string;
12
+ };
13
+ }
14
+ declare function readConfig(): StoredConfig;
15
+ /** Writes `~/.perspectask/config.json` readable by the owning user only. */
16
+ declare function writeConfig(config: StoredConfig): string;
17
+ declare class LoginExpiredError extends Error {
18
+ constructor();
19
+ }
20
+ interface ResolvedCredential {
21
+ apiKey: string | (() => Promise<string>);
22
+ baseUrl?: string;
23
+ source: "environment" | "login" | "api_key";
24
+ }
25
+ /**
26
+ * The credential the CLI and the local MCP server use, in order: `PERSPECTASK_API_KEY`,
27
+ * the login saved by `pt login` (refreshed when it expires), then a key saved
28
+ * with `pt auth set`. `PERSPECTASK_API_URL` overrides the saved base URL.
29
+ */
30
+ declare function resolveCredential(): ResolvedCredential | null;
31
+
32
+ export { CONFIG_PATH, LoginExpiredError, type ResolvedCredential, type StoredConfig, readConfig, resolveCredential, writeConfig };
@@ -0,0 +1,32 @@
1
+ import { O as OAuthTokens, D as DeviceLogin } from './oauth-kp6GpoOV.js';
2
+
3
+ declare const CONFIG_PATH: string;
4
+ interface StoredConfig {
5
+ apiKey?: string;
6
+ baseUrl?: string;
7
+ oauth?: OAuthTokens;
8
+ /** A `pt login --no-wait` that has not been approved yet. `expiresAt` is in ms. */
9
+ pendingLogin?: DeviceLogin & {
10
+ expiresAt: number;
11
+ baseUrl?: string;
12
+ };
13
+ }
14
+ declare function readConfig(): StoredConfig;
15
+ /** Writes `~/.perspectask/config.json` readable by the owning user only. */
16
+ declare function writeConfig(config: StoredConfig): string;
17
+ declare class LoginExpiredError extends Error {
18
+ constructor();
19
+ }
20
+ interface ResolvedCredential {
21
+ apiKey: string | (() => Promise<string>);
22
+ baseUrl?: string;
23
+ source: "environment" | "login" | "api_key";
24
+ }
25
+ /**
26
+ * The credential the CLI and the local MCP server use, in order: `PERSPECTASK_API_KEY`,
27
+ * the login saved by `pt login` (refreshed when it expires), then a key saved
28
+ * with `pt auth set`. `PERSPECTASK_API_URL` overrides the saved base URL.
29
+ */
30
+ declare function resolveCredential(): ResolvedCredential | null;
31
+
32
+ export { CONFIG_PATH, LoginExpiredError, type ResolvedCredential, type StoredConfig, readConfig, resolveCredential, writeConfig };
@@ -0,0 +1,88 @@
1
+ import {
2
+ refreshTokens
3
+ } from "./chunk-56FPFSE2.js";
4
+
5
+ // src/credentials.ts
6
+ import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "fs";
7
+ import { homedir } from "os";
8
+ import { dirname, join } from "path";
9
+ var CONFIG_PATH = join(homedir(), ".perspectask", "config.json");
10
+ var REFRESH_MARGIN_MS = 6e4;
11
+ function readConfig() {
12
+ try {
13
+ return JSON.parse(readFileSync(CONFIG_PATH, "utf8"));
14
+ } catch {
15
+ return {};
16
+ }
17
+ }
18
+ function writeConfig(config) {
19
+ mkdirSync(dirname(CONFIG_PATH), { recursive: true, mode: 448 });
20
+ writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2), { mode: 384 });
21
+ chmodSync(CONFIG_PATH, 384);
22
+ return CONFIG_PATH;
23
+ }
24
+ var LoginExpiredError = class extends Error {
25
+ constructor() {
26
+ super("Your PerspecTask login has expired. Run `pt login` again.");
27
+ this.name = "LoginExpiredError";
28
+ }
29
+ };
30
+ var refreshing = null;
31
+ async function refreshStoredLogin(stored, baseUrl) {
32
+ try {
33
+ const oauth = await refreshTokens(stored.refreshToken, { baseUrl });
34
+ writeConfig({ ...readConfig(), oauth });
35
+ return oauth.accessToken;
36
+ } catch (error) {
37
+ const latest = readConfig().oauth;
38
+ if (latest && latest.refreshToken !== stored.refreshToken && latest.expiresAt > Date.now()) {
39
+ return latest.accessToken;
40
+ }
41
+ if (error.code === "invalid_grant") {
42
+ throw new LoginExpiredError();
43
+ }
44
+ throw error;
45
+ }
46
+ }
47
+ async function currentAccessToken(baseUrl) {
48
+ const stored = readConfig().oauth;
49
+ if (!stored) throw new LoginExpiredError();
50
+ if (stored.expiresAt - REFRESH_MARGIN_MS > Date.now()) {
51
+ return stored.accessToken;
52
+ }
53
+ refreshing ??= refreshStoredLogin(stored, baseUrl).finally(() => {
54
+ refreshing = null;
55
+ });
56
+ return refreshing;
57
+ }
58
+ function resolveCredential() {
59
+ const config = readConfig();
60
+ const baseUrl = process.env.PERSPECTASK_API_URL ?? config.baseUrl;
61
+ const withBaseUrl = baseUrl ? { baseUrl } : {};
62
+ if (process.env.PERSPECTASK_API_KEY) {
63
+ return {
64
+ apiKey: process.env.PERSPECTASK_API_KEY,
65
+ source: "environment",
66
+ ...withBaseUrl
67
+ };
68
+ }
69
+ if (config.oauth) {
70
+ return {
71
+ apiKey: () => currentAccessToken(baseUrl),
72
+ source: "login",
73
+ ...withBaseUrl
74
+ };
75
+ }
76
+ if (config.apiKey) {
77
+ return { apiKey: config.apiKey, source: "api_key", ...withBaseUrl };
78
+ }
79
+ return null;
80
+ }
81
+ export {
82
+ CONFIG_PATH,
83
+ LoginExpiredError,
84
+ readConfig,
85
+ resolveCredential,
86
+ writeConfig
87
+ };
88
+ //# sourceMappingURL=credentials.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/credentials.ts"],"sourcesContent":["import { chmodSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport { type DeviceLogin, type OAuthTokens, refreshTokens } from \"./oauth\";\n\nexport const CONFIG_PATH = join(homedir(), \".perspectask\", \"config.json\");\n\nconst REFRESH_MARGIN_MS = 60_000;\n\nexport interface StoredConfig {\n apiKey?: string;\n baseUrl?: string;\n oauth?: OAuthTokens;\n /** A `pt login --no-wait` that has not been approved yet. `expiresAt` is in ms. */\n pendingLogin?: DeviceLogin & { expiresAt: number; baseUrl?: string };\n}\n\nexport function readConfig(): StoredConfig {\n try {\n return JSON.parse(readFileSync(CONFIG_PATH, \"utf8\")) as StoredConfig;\n } catch {\n return {};\n }\n}\n\n/** Writes `~/.perspectask/config.json` readable by the owning user only. */\nexport function writeConfig(config: StoredConfig): string {\n mkdirSync(dirname(CONFIG_PATH), { recursive: true, mode: 0o700 });\n writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2), { mode: 0o600 });\n chmodSync(CONFIG_PATH, 0o600);\n return CONFIG_PATH;\n}\n\nexport class LoginExpiredError extends Error {\n constructor() {\n super(\"Your PerspecTask login has expired. Run `pt login` again.\");\n this.name = \"LoginExpiredError\";\n }\n}\n\nlet refreshing: Promise<string> | null = null;\n\nasync function refreshStoredLogin(\n stored: OAuthTokens,\n baseUrl: string | undefined,\n): Promise<string> {\n try {\n const oauth = await refreshTokens(stored.refreshToken, { baseUrl });\n writeConfig({ ...readConfig(), oauth });\n return oauth.accessToken;\n } catch (error) {\n const latest = readConfig().oauth;\n if (\n latest &&\n latest.refreshToken !== stored.refreshToken &&\n latest.expiresAt > Date.now()\n ) {\n return latest.accessToken;\n }\n if ((error as { code?: string }).code === \"invalid_grant\") {\n throw new LoginExpiredError();\n }\n throw error;\n }\n}\n\nasync function currentAccessToken(\n baseUrl: string | undefined,\n): Promise<string> {\n const stored = readConfig().oauth;\n if (!stored) throw new LoginExpiredError();\n if (stored.expiresAt - REFRESH_MARGIN_MS > Date.now()) {\n return stored.accessToken;\n }\n\n refreshing ??= refreshStoredLogin(stored, baseUrl).finally(() => {\n refreshing = null;\n });\n return refreshing;\n}\n\nexport interface ResolvedCredential {\n apiKey: string | (() => Promise<string>);\n baseUrl?: string;\n source: \"environment\" | \"login\" | \"api_key\";\n}\n\n/**\n * The credential the CLI and the local MCP server use, in order: `PERSPECTASK_API_KEY`,\n * the login saved by `pt login` (refreshed when it expires), then a key saved\n * with `pt auth set`. `PERSPECTASK_API_URL` overrides the saved base URL.\n */\nexport function resolveCredential(): ResolvedCredential | null {\n const config = readConfig();\n const baseUrl = process.env.PERSPECTASK_API_URL ?? config.baseUrl;\n const withBaseUrl = baseUrl ? { baseUrl } : {};\n\n if (process.env.PERSPECTASK_API_KEY) {\n return {\n apiKey: process.env.PERSPECTASK_API_KEY,\n source: \"environment\",\n ...withBaseUrl,\n };\n }\n if (config.oauth) {\n return {\n apiKey: () => currentAccessToken(baseUrl),\n source: \"login\",\n ...withBaseUrl,\n };\n }\n if (config.apiKey) {\n return { apiKey: config.apiKey, source: \"api_key\", ...withBaseUrl };\n }\n return null;\n}\n"],"mappings":";;;;;AAAA,SAAS,WAAW,WAAW,cAAc,qBAAqB;AAClE,SAAS,eAAe;AACxB,SAAS,SAAS,YAAY;AAIvB,IAAM,cAAc,KAAK,QAAQ,GAAG,gBAAgB,aAAa;AAExE,IAAM,oBAAoB;AAUnB,SAAS,aAA2B;AACzC,MAAI;AACF,WAAO,KAAK,MAAM,aAAa,aAAa,MAAM,CAAC;AAAA,EACrD,QAAQ;AACN,WAAO,CAAC;AAAA,EACV;AACF;AAGO,SAAS,YAAY,QAA8B;AACxD,YAAU,QAAQ,WAAW,GAAG,EAAE,WAAW,MAAM,MAAM,IAAM,CAAC;AAChE,gBAAc,aAAa,KAAK,UAAU,QAAQ,MAAM,CAAC,GAAG,EAAE,MAAM,IAAM,CAAC;AAC3E,YAAU,aAAa,GAAK;AAC5B,SAAO;AACT;AAEO,IAAM,oBAAN,cAAgC,MAAM;AAAA,EAC3C,cAAc;AACZ,UAAM,2DAA2D;AACjE,SAAK,OAAO;AAAA,EACd;AACF;AAEA,IAAI,aAAqC;AAEzC,eAAe,mBACb,QACA,SACiB;AACjB,MAAI;AACF,UAAM,QAAQ,MAAM,cAAc,OAAO,cAAc,EAAE,QAAQ,CAAC;AAClE,gBAAY,EA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