@chaouidz/postpilot 1.1.1 → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,27 +1,27 @@
1
- {
2
- "name": "@chaouidz/postpilot",
3
- "version": "1.1.1",
4
- "description": "PostPilot CLI for scoped, approval-based social publishing and batch scheduling",
5
- "type": "module",
6
- "bin": {
7
- "postpilot": "bin/postpilot.mjs"
8
- },
9
- "files": [
10
- "bin",
11
- "src",
12
- "README.md"
13
- ],
14
- "engines": {
15
- "node": ">=20"
16
- },
17
- "license": "UNLICENSED",
18
- "repository": {
19
- "type": "git",
20
- "url": "https://github.com/yktis/postpilot.git",
21
- "directory": "packages/cli"
22
- },
23
- "homepage": "https://postpilot.yktis.com/cli",
24
- "scripts": {
25
- "test": "node --test test/*.test.mjs"
26
- }
27
- }
1
+ {
2
+ "name": "@chaouidz/postpilot",
3
+ "version": "1.1.2",
4
+ "description": "PostPilot CLI for scoped, autonomous social publishing and batch scheduling",
5
+ "type": "module",
6
+ "bin": {
7
+ "postpilot": "bin/postpilot.mjs"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "src",
12
+ "README.md"
13
+ ],
14
+ "engines": {
15
+ "node": ">=20"
16
+ },
17
+ "license": "UNLICENSED",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "https://github.com/yktis/postpilot.git",
21
+ "directory": "packages/cli"
22
+ },
23
+ "homepage": "https://postpilot.yktis.com/cli",
24
+ "scripts": {
25
+ "test": "node --test test/*.test.mjs"
26
+ }
27
+ }
@@ -0,0 +1,53 @@
1
+ import { CliError } from "./client.mjs";
2
+
3
+ // Uses the existing credentials/session and token APIs. No new auth endpoint,
4
+ // password store, provider-consent bypass or account privilege is introduced.
5
+ export async function bootstrapToken(url, credentials, fetcher = fetch) {
6
+ const origin = new URL(url).origin;
7
+ if (!origin.startsWith("https:") && !["localhost", "127.0.0.1", "[::1]"].includes(new URL(origin).hostname))
8
+ throw new CliError("Remote authentication requires HTTPS.");
9
+ if (!credentials || typeof credentials.email !== "string" || typeof credentials.password !== "string")
10
+ throw new CliError("Credentials JSON requires email and password strings.");
11
+ const cookies = new Map();
12
+ async function request(path, init = {}) {
13
+ let response;
14
+ try {
15
+ response = await fetcher(origin + path, {
16
+ ...init, redirect: "error", signal: AbortSignal.timeout(30_000),
17
+ headers: { ...init.headers, Origin: origin, Cookie: [...cookies].map(([key, value]) => `${key}=${value}`).join("; ") },
18
+ });
19
+ } catch { throw new CliError("Could not reach PostPilot during login.", "INTERNAL_FAILURE"); }
20
+ for (const cookie of response.headers.getSetCookie()) {
21
+ const pair = cookie.split(";", 1)[0];
22
+ const index = pair.indexOf("=");
23
+ if (index > 0) cookies.set(pair.slice(0, index), pair.slice(index + 1));
24
+ }
25
+ const data = await response.json().catch(() => ({}));
26
+ if (!response.ok) throw new CliError("PostPilot login or token creation failed. Check credentials and token policy.", response.status === 429 ? "RATE_LIMITED" : "AUTHENTICATION_EXPIRED");
27
+ return data;
28
+ }
29
+ try {
30
+ const { csrfToken } = await request("/api/auth/csrf");
31
+ if (!csrfToken) throw new CliError("PostPilot did not provide a CSRF challenge.", "AUTHENTICATION_EXPIRED");
32
+ const result = await request("/api/auth/callback/credentials", {
33
+ method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", "X-Auth-Return-Redirect": "1" },
34
+ body: new URLSearchParams({ csrfToken, email: credentials.email, password: credentials.password, callbackUrl: origin }).toString(),
35
+ });
36
+ if (result.error || (result.url && new URL(result.url, origin).searchParams.has("error")))
37
+ throw new CliError("PostPilot credentials were not accepted.", "AUTHENTICATION_EXPIRED");
38
+ const session = await request("/api/auth/session");
39
+ if (!session.user?.id) throw new CliError("PostPilot credentials did not establish a session.", "AUTHENTICATION_EXPIRED");
40
+ const data = await request("/api/mcp/tokens", {
41
+ method: "POST", headers: { "Content-Type": "application/json" },
42
+ body: JSON.stringify({
43
+ name: credentials.tokenName || "PostPilot CLI",
44
+ scopes: credentials.scopes || ["social:read", "social:write"],
45
+ allowedAccountIds: credentials.allowedAccountIds ?? null,
46
+ expiresInDays: credentials.expiresInDays ?? null,
47
+ requireHumanApproval: credentials.requireHumanApproval === true,
48
+ }),
49
+ });
50
+ if (!data.token) throw new CliError("PostPilot did not return a token.", "AUTHENTICATION_EXPIRED");
51
+ return data.token;
52
+ } finally { cookies.clear(); }
53
+ }
package/src/client.mjs CHANGED
@@ -1,168 +1,168 @@
1
- import { randomUUID, createHash } from "node:crypto";
2
- import { createReadStream } from "node:fs";
3
- import { stat } from "node:fs/promises";
4
- import { basename, extname } from "node:path";
5
- export class CliError extends Error {
6
- constructor(message, code = "INVALID_PARAMETERS", details = {}) {
7
- super(message);
8
- // Older servers labeled plan capacity as throttling. Normalize that precise
9
- // legacy classification during rollout; never infer it from a message.
10
- const capacity =
11
- code === "CAPACITY_EXCEEDED" ||
12
- (code === "RATE_LIMITED" &&
13
- (details.limitType === "ACCOUNT_CALENDAR_DAY" ||
14
- details.details?.limitType === "ACCOUNT_CALENDAR_DAY"));
15
- this.code = capacity ? "CAPACITY_EXCEEDED" : code;
16
- this.details = { ...details };
17
- delete this.details.code;
18
- delete this.details.message;
19
- if (this.code !== "RATE_LIMITED") {
20
- delete this.details.retryAfter;
21
- if (this.details.details) {
22
- this.details.details = { ...this.details.details };
23
- delete this.details.details.retryAfter;
24
- }
25
- }
26
- if (capacity) this.details.retryable = false;
27
- }
28
- }
29
- export const EXIT_CODES = {
30
- INVALID_PARAMETERS: 2,
31
- AUTHENTICATION_EXPIRED: 3,
32
- INSUFFICIENT_SCOPE: 3,
33
- NOT_FOUND: 4,
34
- PENDING_APPROVAL: 5,
35
- RATE_LIMITED: 6,
36
- CAPACITY_EXCEEDED: 8,
37
- PROVIDER_REJECTED: 7,
38
- INTERNAL_FAILURE: 7,
39
- };
40
- export class Client {
41
- constructor(origin, token, fetcher = fetch) {
42
- this.origin = new URL(origin).origin;
43
- this.token = token;
44
- this.fetch = fetcher;
45
- if (!token)
46
- throw new CliError(
47
- "Run postpilot login or configure POSTPILOT_TOKEN.",
48
- "AUTHENTICATION_EXPIRED"
49
- );
50
- if (
51
- !/^https:/.test(this.origin) &&
52
- !["127.0.0.1", "localhost", "[::1]"].includes(new URL(origin).hostname)
53
- )
54
- throw new CliError("Remote API connections require HTTPS.");
55
- }
56
- async request(path, init = {}) {
57
- let response;
58
- try {
59
- response = await this.fetch(this.origin + path, {
60
- ...init,
61
- redirect: "error",
62
- signal: AbortSignal.timeout(150000),
63
- headers: { ...init.headers, Authorization: `Bearer ${this.token}` },
64
- });
65
- } catch {
66
- throw new CliError(
67
- "Could not reach PostPilot. Check the URL and network; do not blindly retry publication.",
68
- "INTERNAL_FAILURE"
69
- );
70
- }
71
- const body = await response.json().catch(() => ({}));
72
- const error =
73
- (body.result?.isError ? body.result.structuredContent?.error : null) ||
74
- body.error?.data ||
75
- body.error;
76
- if (!response.ok)
77
- throw new CliError(
78
- typeof error === "string" ? error : error?.message || `HTTP ${response.status}`,
79
- error?.code ||
80
- (response.status === 401
81
- ? "AUTHENTICATION_EXPIRED"
82
- : response.status === 403
83
- ? "INSUFFICIENT_SCOPE"
84
- : response.status === 429
85
- ? "RATE_LIMITED"
86
- : "INTERNAL_FAILURE"),
87
- {
88
- ...error?.details,
89
- requestId: response.headers.get("X-Request-Id") || error?.requestId,
90
- retryAfter:
91
- response.headers.get("Retry-After") || error?.retryAfter || error?.details?.retryAfter,
92
- }
93
- );
94
- if (body.error)
95
- throw new CliError(
96
- error?.message || "MCP request failed",
97
- error?.code || "INVALID_PARAMETERS",
98
- error
99
- );
100
- if (body.result?.isError) {
101
- const detail = body.result.structuredContent?.error || {};
102
- throw new CliError(
103
- detail.message || body.result.content?.[0]?.text || "Tool failed",
104
- detail.code || "INTERNAL_FAILURE",
105
- detail
106
- );
107
- }
108
- return body;
109
- }
110
- async tool(name, args = {}) {
111
- const body = await this.request("/api/mcp", {
112
- method: "POST",
113
- headers: { "Content-Type": "application/json", "MCP-Protocol-Version": "2025-06-18" },
114
- body: JSON.stringify({
115
- jsonrpc: "2.0",
116
- id: randomUUID(),
117
- method: "tools/call",
118
- params: { name, arguments: args },
119
- }),
120
- });
121
- return body.result?.structuredContent ?? JSON.parse(body.result?.content?.[0]?.text || "null");
122
- }
123
- async account(selector) {
124
- const data = await this.tool("accounts_list");
125
- const items = Array.isArray(data) ? data : (data.items ?? data.accounts ?? []);
126
- const exact = items.filter((a) => a.id === selector);
127
- const matches = exact.length
128
- ? exact
129
- : items.filter(
130
- (a) => String(a.platformUsername || a.name || "").toLowerCase() === selector.toLowerCase()
131
- );
132
- if (matches.length !== 1)
133
- throw new CliError(
134
- "Choose exactly one account ID or a unique channel name from accounts list."
135
- );
136
- return matches[0];
137
- }
138
- async upload(file, key) {
139
- const info = await stat(file);
140
- if (!info.isFile()) throw new CliError("Select one regular file.");
141
- const mime =
142
- extname(file).toLowerCase() === ".png"
143
- ? "image/png"
144
- : extname(file).toLowerCase() === ".mp4"
145
- ? "video/mp4"
146
- : null;
147
- if (!mime)
148
- throw new CliError(
149
- "Raw uploads accept PNG or MP4. Use prepare-video for other video formats."
150
- );
151
- if (info.size > (mime === "image/png" ? 20 : 90) * 1024 * 1024)
152
- throw new CliError("File exceeds the raw media upload size limit.");
153
- const hash = createHash("sha256");
154
- for await (const chunk of createReadStream(file)) hash.update(chunk);
155
- return this.request("/api/mcp/media", {
156
- method: "POST",
157
- headers: {
158
- "Content-Type": mime,
159
- "Content-Length": String(info.size),
160
- "X-File-Name": encodeURIComponent(basename(file)),
161
- "Idempotency-Key": key || randomUUID(),
162
- "X-Content-SHA256": hash.digest("hex"),
163
- },
164
- body: createReadStream(file),
165
- duplex: "half",
166
- });
167
- }
168
- }
1
+ import { randomUUID, createHash } from "node:crypto";
2
+ import { createReadStream } from "node:fs";
3
+ import { stat } from "node:fs/promises";
4
+ import { basename, extname } from "node:path";
5
+ export class CliError extends Error {
6
+ constructor(message, code = "INVALID_PARAMETERS", details = {}) {
7
+ super(message);
8
+ // Older servers labeled plan capacity as throttling. Normalize that precise
9
+ // legacy classification during rollout; never infer it from a message.
10
+ const capacity =
11
+ code === "CAPACITY_EXCEEDED" ||
12
+ (code === "RATE_LIMITED" &&
13
+ (details.limitType === "ACCOUNT_CALENDAR_DAY" ||
14
+ details.details?.limitType === "ACCOUNT_CALENDAR_DAY"));
15
+ this.code = capacity ? "CAPACITY_EXCEEDED" : code;
16
+ this.details = { ...details };
17
+ delete this.details.code;
18
+ delete this.details.message;
19
+ if (this.code !== "RATE_LIMITED") {
20
+ delete this.details.retryAfter;
21
+ if (this.details.details) {
22
+ this.details.details = { ...this.details.details };
23
+ delete this.details.details.retryAfter;
24
+ }
25
+ }
26
+ if (capacity) this.details.retryable = false;
27
+ }
28
+ }
29
+ export const EXIT_CODES = {
30
+ INVALID_PARAMETERS: 2,
31
+ AUTHENTICATION_EXPIRED: 3,
32
+ INSUFFICIENT_SCOPE: 3,
33
+ NOT_FOUND: 4,
34
+ PENDING_APPROVAL: 5,
35
+ RATE_LIMITED: 6,
36
+ CAPACITY_EXCEEDED: 8,
37
+ PROVIDER_REJECTED: 7,
38
+ INTERNAL_FAILURE: 7,
39
+ };
40
+ export class Client {
41
+ constructor(origin, token, fetcher = fetch) {
42
+ this.origin = new URL(origin).origin;
43
+ this.token = token;
44
+ this.fetch = fetcher;
45
+ if (!token)
46
+ throw new CliError(
47
+ "Run postpilot login or configure POSTPILOT_TOKEN.",
48
+ "AUTHENTICATION_EXPIRED"
49
+ );
50
+ if (
51
+ !/^https:/.test(this.origin) &&
52
+ !["127.0.0.1", "localhost", "[::1]"].includes(new URL(origin).hostname)
53
+ )
54
+ throw new CliError("Remote API connections require HTTPS.");
55
+ }
56
+ async request(path, init = {}) {
57
+ let response;
58
+ try {
59
+ response = await this.fetch(this.origin + path, {
60
+ ...init,
61
+ redirect: "error",
62
+ signal: AbortSignal.timeout(150000),
63
+ headers: { ...init.headers, Authorization: `Bearer ${this.token}` },
64
+ });
65
+ } catch {
66
+ throw new CliError(
67
+ "Could not reach PostPilot. Check the URL and network; do not blindly retry publication.",
68
+ "INTERNAL_FAILURE"
69
+ );
70
+ }
71
+ const body = await response.json().catch(() => ({}));
72
+ const error =
73
+ (body.result?.isError ? body.result.structuredContent?.error : null) ||
74
+ body.error?.data ||
75
+ body.error;
76
+ if (!response.ok)
77
+ throw new CliError(
78
+ typeof error === "string" ? error : error?.message || `HTTP ${response.status}`,
79
+ error?.code ||
80
+ (response.status === 401
81
+ ? "AUTHENTICATION_EXPIRED"
82
+ : response.status === 403
83
+ ? "INSUFFICIENT_SCOPE"
84
+ : response.status === 429
85
+ ? "RATE_LIMITED"
86
+ : "INTERNAL_FAILURE"),
87
+ {
88
+ ...error?.details,
89
+ requestId: response.headers.get("X-Request-Id") || error?.requestId,
90
+ retryAfter:
91
+ response.headers.get("Retry-After") || error?.retryAfter || error?.details?.retryAfter,
92
+ }
93
+ );
94
+ if (body.error)
95
+ throw new CliError(
96
+ error?.message || "MCP request failed",
97
+ error?.code || "INVALID_PARAMETERS",
98
+ error
99
+ );
100
+ if (body.result?.isError) {
101
+ const detail = body.result.structuredContent?.error || {};
102
+ throw new CliError(
103
+ detail.message || body.result.content?.[0]?.text || "Tool failed",
104
+ detail.code || "INTERNAL_FAILURE",
105
+ detail
106
+ );
107
+ }
108
+ return body;
109
+ }
110
+ async tool(name, args = {}) {
111
+ const body = await this.request("/api/mcp", {
112
+ method: "POST",
113
+ headers: { "Content-Type": "application/json", "MCP-Protocol-Version": "2025-06-18" },
114
+ body: JSON.stringify({
115
+ jsonrpc: "2.0",
116
+ id: randomUUID(),
117
+ method: "tools/call",
118
+ params: { name, arguments: args },
119
+ }),
120
+ });
121
+ return body.result?.structuredContent ?? JSON.parse(body.result?.content?.[0]?.text || "null");
122
+ }
123
+ async account(selector) {
124
+ const data = await this.tool("accounts_list");
125
+ const items = Array.isArray(data) ? data : (data.items ?? data.accounts ?? []);
126
+ const exact = items.filter((a) => a.id === selector);
127
+ const matches = exact.length
128
+ ? exact
129
+ : items.filter(
130
+ (a) => String(a.platformUsername || a.name || "").toLowerCase() === selector.toLowerCase()
131
+ );
132
+ if (matches.length !== 1)
133
+ throw new CliError(
134
+ "Choose exactly one account ID or a unique channel name from accounts list."
135
+ );
136
+ return matches[0];
137
+ }
138
+ async upload(file, key) {
139
+ const info = await stat(file);
140
+ if (!info.isFile()) throw new CliError("Select one regular file.");
141
+ const mime =
142
+ extname(file).toLowerCase() === ".png"
143
+ ? "image/png"
144
+ : extname(file).toLowerCase() === ".mp4"
145
+ ? "video/mp4"
146
+ : null;
147
+ if (!mime)
148
+ throw new CliError(
149
+ "Raw uploads accept PNG or MP4. Use prepare-video for other video formats."
150
+ );
151
+ if (info.size > (mime === "image/png" ? 20 : 90) * 1024 * 1024)
152
+ throw new CliError("File exceeds the raw media upload size limit.");
153
+ const hash = createHash("sha256");
154
+ for await (const chunk of createReadStream(file)) hash.update(chunk);
155
+ return this.request("/api/mcp/media", {
156
+ method: "POST",
157
+ headers: {
158
+ "Content-Type": mime,
159
+ "Content-Length": String(info.size),
160
+ "X-File-Name": encodeURIComponent(basename(file)),
161
+ "Idempotency-Key": key || randomUUID(),
162
+ "X-Content-SHA256": hash.digest("hex"),
163
+ },
164
+ body: createReadStream(file),
165
+ duplex: "half",
166
+ });
167
+ }
168
+ }