@chaouidz/postpilot 0.0.0-stage → 1.0.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.
package/README.md CHANGED
@@ -1,3 +1,52 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # PostPilot CLI
2
+
3
+ Thin Node.js 20+ client for the same approval-based API used by MCP. No bundled server or provider credentials. Public docs: https://postpilot.yktis.com/docs.
4
+
5
+ Install from npm: `npm install -g @chaouidz/postpilot@1.0.0`, then run `postpilot help`.
6
+ Without a global install: `npx @chaouidz/postpilot@1.0.0 help`.
7
+ Package: https://www.npmjs.com/package/@chaouidz/postpilot.
8
+ The original versioned download remains available: `npm install -g https://postpilot.yktis.com/downloads/postpilot-1.0.0.tgz`.
9
+ For source review: run `npm pack` in `packages/cli`, then `npm install -g ./chaouidz-postpilot-1.0.0.tgz`. Packing does not publish to npm.
10
+
11
+ Python, PHP and other languages can call the HTTP API directly or invoke this CLI as a subprocess. npm distributes the Node.js CLI; it does not require your application to use JavaScript. There is no separate pip or Composer package.
12
+
13
+ ## Login and secrets
14
+
15
+ Create a token in PostPilot Settings with `social:read`, `social:write`, an expiry and only the channel you intend to use. Keep trusted automation disabled for human approval.
16
+
17
+ Run `postpilot login` and paste the token at the hidden prompt. Windows uses Credential Manager; macOS uses Keychain via `security`; Linux uses Secret Service via `secret-tool` (install your distribution's libsecret tools and unlock a desktop keychain). A missing/locked keychain fails explicitly. There is no plaintext-file fallback. Piped login requires `--token-stdin` and still stores in the OS keychain.
18
+
19
+ CI/cron: configure `POSTPILOT_TOKEN` through the runtime's secret store and use `--non-interactive --json`. Do not put it in a shell history, command argument, checked-in config or prompt. `POSTPILOT_URL` or `--url` selects an API origin; remote connections require HTTPS. Redirects are not followed with credentials.
20
+
21
+ `logout` removes only the local keychain entry. Revoke the token in PostPilot Settings to invalidate all copies; already scheduled posts must be cancelled separately.
22
+
23
+ ## Schedule a Short to ONE named channel
24
+
25
+ ```sh
26
+ postpilot login
27
+ postpilot whoami --json
28
+ postpilot accounts list --json
29
+ postpilot upload short.mp4 --idempotency-key my-short-import-001 --json
30
+ # Copy the returned uploadSessionId as UPLOAD_ID below.
31
+ postpilot draft create --account "My Tutorials" --asset UPLOAD_ID --title "My Short" --privacy private --idempotency-key my-short-draft-001 --json
32
+ # Copy the returned id as DRAFT_ID. Pick a FUTURE ISO timestamp with an offset.
33
+ postpilot schedule --post DRAFT_ID --account "My Tutorials" --at "2027-01-10T09:00:00+01:00" --timezone Europe/Zurich --dry-run --json
34
+ postpilot schedule --post DRAFT_ID --account "My Tutorials" --at "2027-01-10T09:00:00+01:00" --timezone Europe/Zurich --idempotency-key my-short-schedule-001 --json
35
+ # Exit code 5 means PENDING_APPROVAL. Open the returned approvalUrl while signed in.
36
+ # Review the exact single account, private visibility and time, then approve.
37
+ postpilot status --post DRAFT_ID --json
38
+ ```
39
+
40
+ Exact IDs are preferred. Names must uniquely match one visible channel; an ambiguous name fails. No platform-wide broadcast fallback. A scheduled/queued result does not mean published. Dry-run validates local inputs; dynamic provider capacity and plan allowances are not reserved. Publication is queued only after browser approval, unless this token explicitly enables trusted automation.
41
+
42
+ Other commands: `assets list [--limit 1-100] [--cursor CURSOR]`, `publish --post ID --account ID [--dry-run]`, `cancel --post ID`, `prepare-video input.mov --output compatible.mp4` (offline, requires ffmpeg, never overwrites an existing file). Set privacy on the draft before scheduling; the approval payload and stored draft determine publication privacy. Image/raw uploads accept PNG up to 20 MiB and MP4 up to 90 MiB. Preparation may produce larger files, which the raw upload API will reject.
43
+
44
+ All commands accept `--json` and `--non-interactive`. `--account`, `--at`, `--privacy` and `--dry-run` apply where relevant; help lists the full syntax. Keep an idempotency key identical on retries of one operation. Inspect failed/ambiguous delivery before attempting a new publication.
45
+
46
+ ## Exit codes
47
+
48
+ 0 success, 2 invalid usage/input, 3 authentication or scope failure, 4 not found, 5 pending browser approval, 6 rate limited, 7 provider/network/server failure. JSON errors include stable `code`, `message`, and available request/retry details. Honor Retry-After; provider quotas are not unlimited or guaranteed.
49
+
50
+ ## Tests
51
+
52
+ `npm test` uses a local mock server, fake account IDs and fixture media. Native keychain integration is opt-in with `POSTPILOT_TEST_NATIVE_KEYCHAIN=true`; it creates and removes only a unique fixture credential. No live publishing or real social-account calls occur.
@@ -0,0 +1,277 @@
1
+ #!/usr/bin/env node
2
+ import { execFile } from "node:child_process";
3
+ import { promisify } from "node:util";
4
+ import { Client, CliError, EXIT_CODES } from "../src/client.mjs";
5
+ import { keychain } from "../src/keychain.mjs";
6
+ const args = process.argv.slice(2),
7
+ options = {},
8
+ positionals = [];
9
+ const boolean = new Set(["json", "dry-run", "non-interactive", "token-stdin", "help"]);
10
+ const valued = new Set([
11
+ "url",
12
+ "account",
13
+ "at",
14
+ "privacy",
15
+ "post",
16
+ "approval",
17
+ "asset",
18
+ "title",
19
+ "content",
20
+ "output",
21
+ "idempotency-key",
22
+ "timezone",
23
+ "limit",
24
+ "cursor",
25
+ ]);
26
+ function required(name) {
27
+ if (!options[name]) throw new CliError(`--${name} is required.`);
28
+ return options[name];
29
+ }
30
+ function output(value) {
31
+ console.log(JSON.stringify(value, null, options.json ? 0 : 2));
32
+ if (value?.status === "PENDING_APPROVAL") process.exitCode = 5;
33
+ }
34
+ async function tokenInput() {
35
+ if (!process.stdin.isTTY) {
36
+ if (!options["token-stdin"])
37
+ throw new CliError("Use --token-stdin for piped login, or paste interactively.");
38
+ let value = "";
39
+ for await (const chunk of process.stdin) {
40
+ value += chunk;
41
+ if (value.length > 1024) throw new CliError("Invalid token length.");
42
+ }
43
+ return value.trim();
44
+ }
45
+ if (options["non-interactive"])
46
+ throw new CliError("Non-interactive login requires --token-stdin.");
47
+ process.stderr.write("Paste your PostPilot token (hidden): ");
48
+ return new Promise((resolve, reject) => {
49
+ let value = "";
50
+ process.stdin.setRawMode(true);
51
+ process.stdin.resume();
52
+ const done = (error) => {
53
+ process.stdin.setRawMode(false);
54
+ process.stdin.pause();
55
+ process.stdin.off("data", onData);
56
+ process.stderr.write("\n");
57
+ error ? reject(error) : resolve(value.trim());
58
+ };
59
+ const onData = (chunk) => {
60
+ for (const char of chunk.toString()) {
61
+ if (char === "\r" || char === "\n") return done();
62
+ if (char === "\u0003") return done(new CliError("Login cancelled."));
63
+ if (char === "\u007f" || char === "\b") value = value.slice(0, -1);
64
+ else value += char;
65
+ if (value.length > 512) return done(new CliError("Invalid token length."));
66
+ }
67
+ };
68
+ process.stdin.on("data", onData);
69
+ });
70
+ }
71
+ try {
72
+ for (let index = 0; index < args.length; index++) {
73
+ const value = args[index];
74
+ if (!value.startsWith("--")) {
75
+ positionals.push(value);
76
+ continue;
77
+ }
78
+ const name = value.slice(2);
79
+ if (boolean.has(name)) options[name] = true;
80
+ else if (valued.has(name) && args[index + 1] && !args[index + 1].startsWith("--"))
81
+ options[name] = args[++index];
82
+ else throw new CliError(`Unknown or incomplete option --${name}.`);
83
+ }
84
+ const [command, subcommand] = positionals;
85
+ const origin = new URL(options.url || process.env.POSTPILOT_URL || "https://postpilot.yktis.com")
86
+ .origin;
87
+ if (!command || command === "help" || options.help) {
88
+ output({
89
+ usage: "postpilot <command> [--json] [--non-interactive]",
90
+ commands: [
91
+ "login [--token-stdin]",
92
+ "whoami",
93
+ "logout",
94
+ "accounts list",
95
+ "assets list",
96
+ "upload <file>",
97
+ "prepare-video <file> --output <file>",
98
+ "draft create --account <id-or-name> --asset <id>",
99
+ "schedule --post <id> --account <id-or-name> --at <ISO-offset>",
100
+ "publish --post <id> --account <id-or-name>",
101
+ "status --post <id>",
102
+ "cancel --post <id>",
103
+ ],
104
+ flags: [
105
+ "--account",
106
+ "--at",
107
+ "--privacy",
108
+ "--dry-run",
109
+ "--json",
110
+ "--non-interactive",
111
+ "--idempotency-key",
112
+ "--timezone",
113
+ "--url",
114
+ ],
115
+ exitCodes: {
116
+ success: 0,
117
+ usage: 2,
118
+ auth: 3,
119
+ notFound: 4,
120
+ approvalPending: 5,
121
+ rateLimited: 6,
122
+ providerOrNetwork: 7,
123
+ },
124
+ docs: "https://postpilot.yktis.com/cli",
125
+ });
126
+ } else if (command === "prepare-video") {
127
+ const input = subcommand;
128
+ if (!input) throw new CliError("Choose an input video.");
129
+ const target = required("output");
130
+ const ffargs = [
131
+ "-hide_banner",
132
+ "-loglevel",
133
+ "error",
134
+ "-n",
135
+ "-threads",
136
+ "2",
137
+ "-filter_threads",
138
+ "1",
139
+ "-i",
140
+ input,
141
+ "-map",
142
+ "0:v:0",
143
+ "-map",
144
+ "0:a?",
145
+ "-vf",
146
+ "scale=w=min(1920\\,iw):h=min(1920\\,ih):force_original_aspect_ratio=decrease:force_divisible_by=2,format=yuv420p,fps=30",
147
+ "-c:v",
148
+ "libx264",
149
+ "-crf",
150
+ "20",
151
+ "-pix_fmt",
152
+ "yuv420p",
153
+ "-c:a",
154
+ "aac",
155
+ "-ar",
156
+ "48000",
157
+ "-ac",
158
+ "2",
159
+ "-movflags",
160
+ "+faststart",
161
+ target,
162
+ ];
163
+ if (options["dry-run"]) output({ dryRun: true, command: "ffmpeg", arguments: ffargs });
164
+ else {
165
+ try {
166
+ await promisify(execFile)("ffmpeg", ffargs, {
167
+ timeout: 180000,
168
+ maxBuffer: 1024 * 1024,
169
+ windowsHide: true,
170
+ });
171
+ } catch {
172
+ throw new CliError(
173
+ "Video preparation failed. Install ffmpeg, choose a fresh output path and check the input.",
174
+ "INTERNAL_FAILURE"
175
+ );
176
+ }
177
+ output({ output: target, uploaded: false });
178
+ }
179
+ } else if (command === "logout") {
180
+ await keychain("delete", origin);
181
+ output({
182
+ loggedOut: true,
183
+ message:
184
+ "Local credential removed. Revoke the token in Settings to invalidate it everywhere.",
185
+ });
186
+ } else if (command === "login") {
187
+ const token = await tokenInput();
188
+ const client = new Client(origin, token);
189
+ await client.tool("social_get_profile");
190
+ await keychain("set", origin, token);
191
+ output({ loggedIn: true, storage: "OS keychain", origin });
192
+ } else {
193
+ const client = new Client(
194
+ origin,
195
+ process.env.POSTPILOT_TOKEN || (await keychain("get", origin).catch(() => ""))
196
+ );
197
+ const key = options["idempotency-key"] ? { idempotencyKey: options["idempotency-key"] } : {};
198
+ const common = {
199
+ ...key,
200
+ ...(options.timezone ? { timezone: options.timezone } : {}),
201
+ ...(options["dry-run"] ? { dryRun: true } : {}),
202
+ };
203
+ if (command === "whoami") output(await client.tool("social_get_profile"));
204
+ else if (command === "accounts" && subcommand === "list")
205
+ output(await client.tool("accounts_list"));
206
+ else if (command === "assets" && subcommand === "list")
207
+ output(
208
+ await client.tool("assets_list", {
209
+ ...(options.limit ? { limit: Number(options.limit) } : {}),
210
+ ...(options.cursor ? { cursor: options.cursor } : {}),
211
+ })
212
+ );
213
+ else if (command === "upload") {
214
+ if (!subcommand) throw new CliError("Choose a PNG or MP4 file.");
215
+ if (options["dry-run"]) output({ dryRun: true, file: subcommand, uploaded: false });
216
+ else output(await client.upload(subcommand, options["idempotency-key"]));
217
+ } else if (command === "draft" && subcommand === "create") {
218
+ const account = await client.account(required("account"));
219
+ const post = {
220
+ content: options.content || "",
221
+ videoTitle: options.title || "",
222
+ youtubePrivacyStatus: options.privacy || "private",
223
+ platformTargets: [account.platform],
224
+ selectedAccountIds: [account.id],
225
+ ...(options.asset
226
+ ? {
227
+ uploadSessionId: options.asset,
228
+ mediaType: account.platform === "YOUTUBE" ? "VIDEO_SHORT" : "VIDEO",
229
+ }
230
+ : {}),
231
+ };
232
+ if (options["dry-run"]) output({ dryRun: true, post, created: false });
233
+ else output(await client.tool("post_create_draft", { post, ...key }));
234
+ } else if (["schedule", "publish"].includes(command)) {
235
+ const account = await client.account(required("account"));
236
+ const postId = required("post");
237
+ if (
238
+ command === "schedule" &&
239
+ (!options.at ||
240
+ !/T.*(?:Z|[+-]\d{2}:\d{2})$/.test(options.at) ||
241
+ !Number.isFinite(Date.parse(options.at)))
242
+ )
243
+ throw new CliError("--at requires an ISO timestamp with Z or a numeric offset.");
244
+ if (options.privacy)
245
+ throw new CliError("Set privacy when creating the draft; review it in the approval page.");
246
+ output(
247
+ await client.tool(command === "schedule" ? "post_schedule" : "post_publish", {
248
+ postId,
249
+ accountIds: [account.id],
250
+ ...(command === "schedule" ? { scheduledAt: options.at } : {}),
251
+ ...common,
252
+ })
253
+ );
254
+ } else if (command === "status")
255
+ output(
256
+ await client.tool(
257
+ options.approval ? "approval_status" : "post_status",
258
+ options.approval ? { approvalId: options.approval } : { postId: required("post") }
259
+ )
260
+ );
261
+ else if (command === "cancel")
262
+ output(await client.tool("post_cancel", { postId: required("post"), ...key }));
263
+ else throw new CliError("Unknown command. Run postpilot help.");
264
+ }
265
+ } catch (error) {
266
+ const code = error instanceof CliError ? error.code : "INTERNAL_FAILURE";
267
+ const message =
268
+ error instanceof CliError
269
+ ? error.message
270
+ : "The operation failed. Check your input and OS keychain, then try again.";
271
+ console.error(
272
+ JSON.stringify({
273
+ error: { code, message, ...(error instanceof CliError ? error.details : {}) },
274
+ })
275
+ );
276
+ process.exitCode = EXIT_CODES[code] || 7;
277
+ }
package/package.json CHANGED
@@ -1,6 +1,27 @@
1
- {
2
- "name": "@chaouidz/postpilot",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@chaouidz/postpilot",
3
+ "version": "1.0.0",
4
+ "description": "PostPilot CLI for scoped, approval-based social publishing and analytics",
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
+ }
package/src/client.mjs ADDED
@@ -0,0 +1,145 @@
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
+ this.code = code;
9
+ this.details = details;
10
+ }
11
+ }
12
+ export const EXIT_CODES = {
13
+ INVALID_PARAMETERS: 2,
14
+ AUTHENTICATION_EXPIRED: 3,
15
+ INSUFFICIENT_SCOPE: 3,
16
+ NOT_FOUND: 4,
17
+ PENDING_APPROVAL: 5,
18
+ RATE_LIMITED: 6,
19
+ PROVIDER_REJECTED: 7,
20
+ INTERNAL_FAILURE: 7,
21
+ };
22
+ export class Client {
23
+ constructor(origin, token, fetcher = fetch) {
24
+ this.origin = new URL(origin).origin;
25
+ this.token = token;
26
+ this.fetch = fetcher;
27
+ if (!token)
28
+ throw new CliError(
29
+ "Run postpilot login or configure POSTPILOT_TOKEN.",
30
+ "AUTHENTICATION_EXPIRED"
31
+ );
32
+ if (
33
+ !/^https:/.test(this.origin) &&
34
+ !["127.0.0.1", "localhost", "[::1]"].includes(new URL(origin).hostname)
35
+ )
36
+ throw new CliError("Remote API connections require HTTPS.");
37
+ }
38
+ async request(path, init = {}) {
39
+ let response;
40
+ try {
41
+ response = await this.fetch(this.origin + path, {
42
+ ...init,
43
+ redirect: "error",
44
+ signal: AbortSignal.timeout(150000),
45
+ headers: { ...init.headers, Authorization: `Bearer ${this.token}` },
46
+ });
47
+ } catch {
48
+ throw new CliError(
49
+ "Could not reach PostPilot. Check the URL and network; do not blindly retry publication.",
50
+ "INTERNAL_FAILURE"
51
+ );
52
+ }
53
+ const body = await response.json().catch(() => ({}));
54
+ const error = body.error?.data || body.error;
55
+ if (!response.ok)
56
+ throw new CliError(
57
+ typeof error === "string" ? error : error?.message || `HTTP ${response.status}`,
58
+ error?.code ||
59
+ (response.status === 401
60
+ ? "AUTHENTICATION_EXPIRED"
61
+ : response.status === 403
62
+ ? "INSUFFICIENT_SCOPE"
63
+ : response.status === 429
64
+ ? "RATE_LIMITED"
65
+ : "INTERNAL_FAILURE"),
66
+ {
67
+ requestId: response.headers.get("X-Request-Id"),
68
+ retryAfter: response.headers.get("Retry-After"),
69
+ }
70
+ );
71
+ if (body.error)
72
+ throw new CliError(
73
+ error?.message || "MCP request failed",
74
+ error?.code || "INVALID_PARAMETERS",
75
+ error
76
+ );
77
+ if (body.result?.isError) {
78
+ const detail = body.result.structuredContent?.error || {};
79
+ throw new CliError(
80
+ detail.message || body.result.content?.[0]?.text || "Tool failed",
81
+ detail.code || "INTERNAL_FAILURE",
82
+ detail
83
+ );
84
+ }
85
+ return body;
86
+ }
87
+ async tool(name, args = {}) {
88
+ const body = await this.request("/api/mcp", {
89
+ method: "POST",
90
+ headers: { "Content-Type": "application/json", "MCP-Protocol-Version": "2025-06-18" },
91
+ body: JSON.stringify({
92
+ jsonrpc: "2.0",
93
+ id: randomUUID(),
94
+ method: "tools/call",
95
+ params: { name, arguments: args },
96
+ }),
97
+ });
98
+ return body.result?.structuredContent ?? JSON.parse(body.result?.content?.[0]?.text || "null");
99
+ }
100
+ async account(selector) {
101
+ const data = await this.tool("accounts_list");
102
+ const items = Array.isArray(data) ? data : (data.items ?? data.accounts ?? []);
103
+ const exact = items.filter((a) => a.id === selector);
104
+ const matches = exact.length
105
+ ? exact
106
+ : items.filter(
107
+ (a) => String(a.platformUsername || a.name || "").toLowerCase() === selector.toLowerCase()
108
+ );
109
+ if (matches.length !== 1)
110
+ throw new CliError(
111
+ "Choose exactly one account ID or a unique channel name from accounts list."
112
+ );
113
+ return matches[0];
114
+ }
115
+ async upload(file, key) {
116
+ const info = await stat(file);
117
+ if (!info.isFile()) throw new CliError("Select one regular file.");
118
+ const mime =
119
+ extname(file).toLowerCase() === ".png"
120
+ ? "image/png"
121
+ : extname(file).toLowerCase() === ".mp4"
122
+ ? "video/mp4"
123
+ : null;
124
+ if (!mime)
125
+ throw new CliError(
126
+ "Raw uploads accept PNG or MP4. Use prepare-video for other video formats."
127
+ );
128
+ if (info.size > (mime === "image/png" ? 20 : 90) * 1024 * 1024)
129
+ throw new CliError("File exceeds the raw media upload size limit.");
130
+ const hash = createHash("sha256");
131
+ for await (const chunk of createReadStream(file)) hash.update(chunk);
132
+ return this.request("/api/mcp/media", {
133
+ method: "POST",
134
+ headers: {
135
+ "Content-Type": mime,
136
+ "Content-Length": String(info.size),
137
+ "X-File-Name": encodeURIComponent(basename(file)),
138
+ "Idempotency-Key": key || randomUUID(),
139
+ "X-Content-SHA256": hash.digest("hex"),
140
+ },
141
+ body: createReadStream(file),
142
+ duplex: "half",
143
+ });
144
+ }
145
+ }
@@ -0,0 +1,92 @@
1
+ import { spawn } from "node:child_process";
2
+ import { fileURLToPath } from "node:url";
3
+ export async function keychain(
4
+ action,
5
+ origin,
6
+ token = "",
7
+ platform = process.platform,
8
+ run = runCommand
9
+ ) {
10
+ if (!["get", "set", "delete"].includes(action)) throw Error("Unknown keychain action.");
11
+ const target = `PostPilotCLI:${new URL(origin).origin}`;
12
+ if (token && !/^[\w.:-]{8,512}$/.test(token)) throw Error("Invalid token format.");
13
+ let value;
14
+ if (platform === "win32")
15
+ value = await run(
16
+ "powershell.exe",
17
+ [
18
+ "-NoProfile",
19
+ "-NonInteractive",
20
+ "-File",
21
+ fileURLToPath(new URL("./keychain.ps1", import.meta.url)),
22
+ action,
23
+ target,
24
+ ],
25
+ action === "set" ? token : ""
26
+ );
27
+ else if (platform === "darwin") {
28
+ if (action === "set")
29
+ value = await run(
30
+ "/usr/bin/security",
31
+ ["-i"],
32
+ `add-generic-password -U -a PostPilot -s "${target}" -w "${token}"\n`
33
+ );
34
+ else
35
+ value = await run("/usr/bin/security", [
36
+ action === "get" ? "find-generic-password" : "delete-generic-password",
37
+ "-a",
38
+ "PostPilot",
39
+ "-s",
40
+ target,
41
+ ...(action === "get" ? ["-w"] : []),
42
+ ]);
43
+ } else if (platform === "linux") {
44
+ value = await run(
45
+ "secret-tool",
46
+ [
47
+ action === "set" ? "store" : action === "get" ? "lookup" : "clear",
48
+ ...(action === "set" ? ["--label=PostPilot CLI"] : []),
49
+ "service",
50
+ "postpilot",
51
+ "origin",
52
+ origin,
53
+ ],
54
+ action === "set" ? `${token}\n` : ""
55
+ );
56
+ } else
57
+ throw Error("No supported OS keychain. Use POSTPILOT_TOKEN from your runtime secret store.");
58
+ return action === "get" ? value.trim() : undefined;
59
+ }
60
+ async function runCommand(command, args, input = "") {
61
+ return new Promise((resolve, reject) => {
62
+ const child = spawn(command, args, { stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
63
+ let output = "";
64
+ const timer = setTimeout(() => {
65
+ child.kill();
66
+ reject(Error("OS keychain timed out or is locked."));
67
+ }, 30000);
68
+ child.stdout.on("data", (chunk) => {
69
+ output += chunk;
70
+ if (output.length > 4096) child.kill();
71
+ });
72
+ child.stderr.resume();
73
+ child.on("error", () => {
74
+ clearTimeout(timer);
75
+ reject(
76
+ Error(
77
+ "OS keychain unavailable. Unlock it or use a protected POSTPILOT_TOKEN environment variable."
78
+ )
79
+ );
80
+ });
81
+ child.on("close", (code) => {
82
+ clearTimeout(timer);
83
+ code === 0
84
+ ? resolve(output)
85
+ : reject(
86
+ Error("OS keychain refused the operation or no credential exists. Run postpilot login.")
87
+ );
88
+ });
89
+ child.stdin.on("error", () => {});
90
+ child.stdin.end(input);
91
+ });
92
+ }
@@ -0,0 +1,37 @@
1
+ param([string]$Action,[string]$Target)
2
+ $ErrorActionPreference = 'Stop'
3
+ Add-Type @'
4
+ using System;
5
+ using System.Runtime.InteropServices;
6
+ public static class PostPilotCredential {
7
+ [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
8
+ public struct CREDENTIAL { public int Flags; public int Type; public string TargetName; public string Comment; public long LastWritten; public int CredentialBlobSize; public IntPtr CredentialBlob; public int Persist; public int AttributeCount; public IntPtr Attributes; public string TargetAlias; public string UserName; }
9
+ [DllImport("advapi32.dll",EntryPoint="CredWriteW",CharSet=CharSet.Unicode,SetLastError=true)] public static extern bool Write(ref CREDENTIAL value,int flags);
10
+ [DllImport("advapi32.dll",EntryPoint="CredReadW",CharSet=CharSet.Unicode,SetLastError=true)] public static extern bool Read(string target,int type,int flags,out IntPtr pointer);
11
+ [DllImport("advapi32.dll",EntryPoint="CredDeleteW",CharSet=CharSet.Unicode,SetLastError=true)] public static extern bool Delete(string target,int type,int flags);
12
+ [DllImport("advapi32.dll")] public static extern void CredFree(IntPtr pointer);
13
+ }
14
+ '@
15
+ if ($Action -eq 'set') {
16
+ $token = [Console]::In.ReadToEnd().Trim()
17
+ $bytes = [Text.Encoding]::Unicode.GetBytes($token)
18
+ $pointer = [Runtime.InteropServices.Marshal]::AllocHGlobal($bytes.Length)
19
+ try {
20
+ [Runtime.InteropServices.Marshal]::Copy($bytes,0,$pointer,$bytes.Length)
21
+ $credential = New-Object PostPilotCredential+CREDENTIAL
22
+ $credential.Type=1; $credential.TargetName=$Target; $credential.UserName='PostPilot'; $credential.Persist=2
23
+ $credential.CredentialBlobSize=$bytes.Length; $credential.CredentialBlob=$pointer
24
+ if (-not [PostPilotCredential]::Write([ref]$credential,0)) { exit 1 }
25
+ } finally {
26
+ for ($index=0;$index -lt $bytes.Length;$index++) { [Runtime.InteropServices.Marshal]::WriteByte($pointer,$index,0) }
27
+ [Runtime.InteropServices.Marshal]::FreeHGlobal($pointer)
28
+ }
29
+ } elseif ($Action -eq 'get') {
30
+ $pointer=[IntPtr]::Zero
31
+ if (-not [PostPilotCredential]::Read($Target,1,0,[ref]$pointer)) { exit 1 }
32
+ try {
33
+ $credential=[Runtime.InteropServices.Marshal]::PtrToStructure($pointer,[type][PostPilotCredential+CREDENTIAL])
34
+ [Console]::Out.Write([Runtime.InteropServices.Marshal]::PtrToStringUni($credential.CredentialBlob,$credential.CredentialBlobSize/2))
35
+ } finally { [PostPilotCredential]::CredFree($pointer) }
36
+ } elseif ($Action -eq 'delete') { if (-not [PostPilotCredential]::Delete($Target,1,0)) { exit 1 } }
37
+ else { exit 1 }