@postplus/cli 0.1.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/LICENSE ADDED
@@ -0,0 +1,186 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submitted" means any form of electronic, verbal,
51
+ or written communication sent to the Licensor or its representatives,
52
+ including but not limited to communication on electronic mailing lists,
53
+ source code control systems, and issue tracking systems that are managed
54
+ by, or on behalf of, the Licensor for the purpose of discussing and
55
+ improving the Work, but excluding communication that is conspicuously
56
+ marked or designated in writing by the copyright owner as "Not a
57
+ Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
+ whom a Contribution has been received by the Licensor and incorporated
61
+ within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of
64
+ this License, each Contributor hereby grants to You a perpetual,
65
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
+ copyright license to reproduce, prepare Derivative Works of,
67
+ publicly display, publicly perform, sublicense, and distribute the
68
+ Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ (except as stated in this section) patent license to make, have made,
74
+ use, offer to sell, sell, import, and otherwise transfer the Work,
75
+ where such license applies only to those patent claims licensable
76
+ by such Contributor that are necessarily infringed by their
77
+ Contribution(s) alone or by combination of their Contribution(s)
78
+ with the Work to which such Contribution(s) was submitted. If You
79
+ institute patent litigation against any entity (including a cross-claim
80
+ or counterclaim in a lawsuit) alleging that the Work or any
81
+ Contribution embodied within the Work constitutes direct or
82
+ contributory patent infringement, then any patent licenses granted
83
+ to You under this License for that Work shall terminate as of the
84
+ date such litigation is filed.
85
+
86
+ 4. Redistribution. You may reproduce and distribute copies of the
87
+ Work or Derivative Works thereof in any medium, with or without
88
+ modifications, and in Source or Object form, provided that You
89
+ meet the following conditions:
90
+
91
+ (a) You must give any other recipients of the Work or Derivative
92
+ Works a copy of this License; and
93
+
94
+ (b) You must cause any modified files to carry prominent notices
95
+ stating that You changed the files; and
96
+
97
+ (c) You must retain, in the Source form of any Derivative Works
98
+ that You distribute, all copyright, patent, trademark, and
99
+ attribution notices from the Source form of the Work,
100
+ excluding those notices that do not pertain to any part of
101
+ the Derivative Works; and
102
+
103
+ (d) If the Work includes a "NOTICE" text file as part of its
104
+ distribution, You must include a readable copy of the
105
+ attribution notices contained within such NOTICE file, in
106
+ at least one of the following places: within a NOTICE text
107
+ file distributed as part of the Derivative Works; within
108
+ the Source form or documentation, if provided along with the
109
+ Derivative Works; or, within a display generated by the
110
+ Derivative Works, if and wherever such third-party notices
111
+ normally appear. The contents of the NOTICE file are for
112
+ informational purposes only and do not modify the License.
113
+ You may add Your own attribution notices within Derivative
114
+ Works that You distribute, alongside or as an addendum to
115
+ the NOTICE text from the Work, provided that such additional
116
+ attribution notices cannot be construed as modifying the
117
+ License.
118
+
119
+ You may add Your own license statement for Your modifications and
120
+ may provide additional grant of rights to use, reproduce, modify,
121
+ and distribute Your modifications, or for such Combined Works as a
122
+ whole, under terms of Your choice, provided Your use, reproduction,
123
+ modification, and distribution of the Work otherwise complies with
124
+ the conditions stated in this License.
125
+
126
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
127
+ any Contribution intentionally submitted for inclusion in the Work
128
+ by You to the Licensor shall be under the terms and conditions of
129
+ this License, without any additional terms or conditions.
130
+ Notwithstanding the above, nothing herein shall supersede or modify
131
+ the terms of any separate license agreement you may have executed
132
+ with Licensor regarding such Contributions.
133
+
134
+ 6. Trademarks. This License does not grant permission to use the trade
135
+ names, trademarks, service marks, or product names of the Licensor,
136
+ except as required for reasonable and customary use in describing the
137
+ origin of the Work and reproducing the content of the NOTICE file.
138
+
139
+ 7. Disclaimer of Warranty. Unless required by applicable law or
140
+ agreed to in writing, Licensor provides the Work (and each
141
+ Contributor provides its Contributions) on an "AS IS" BASIS,
142
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
143
+ implied, including, without limitation, any warranties or conditions
144
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
145
+ PARTICULAR PURPOSE. You are solely responsible for determining the
146
+ appropriateness of using or reproducing the Work and assume any
147
+ risks associated with Your exercise of permissions under this License.
148
+
149
+ 8. Limitation of Liability. In no event and under no legal theory,
150
+ whether in tort (including negligence), contract, or otherwise,
151
+ unless required by applicable law (such as deliberate and grossly
152
+ negligent acts) or agreed to in writing, shall any Contributor be
153
+ liable to You for damages, including any direct, indirect, special,
154
+ incidental, or exemplary damages of any character arising as a
155
+ result of this License or out of the use or inability to use the
156
+ Work (including but not limited to damages for loss of goodwill,
157
+ work stoppage, computer failure or malfunction, or all other
158
+ commercial damages or losses), even if such Contributor has been
159
+ advised of the possibility of such damages.
160
+
161
+ 9. Accepting Warranty or Additional Liability. While redistributing
162
+ the Work or Derivative Works thereof, You may choose to offer,
163
+ and charge a fee for, acceptance of support, warranty, indemnity,
164
+ or other liability obligations and/or rights consistent with this
165
+ License. However, in accepting such obligations, You may act only
166
+ on Your own behalf and on Your sole responsibility, not on behalf
167
+ of any other Contributor, and only if You agree to indemnify,
168
+ defend, and hold each Contributor harmless for any liability
169
+ incurred by, or claims asserted against, such Contributor by reason
170
+ of your accepting any such warranty or additional liability.
171
+
172
+ END OF TERMS AND CONDITIONS
173
+
174
+ Copyright 2026 RealProductStudio
175
+
176
+ Licensed under the Apache License, Version 2.0 (the "License");
177
+ you may not use this file except in compliance with the License.
178
+ You may obtain a copy of the License at
179
+
180
+ http://www.apache.org/licenses/LICENSE-2.0
181
+
182
+ Unless required by applicable law or agreed to in writing, software
183
+ distributed under the License is distributed on an "AS IS" BASIS,
184
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
185
+ See the License for the specific language governing permissions and
186
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,14 @@
1
+ PostPlus CLI
2
+ Copyright 2026 RealProductStudio
3
+
4
+ This product is licensed under the Apache License, Version 2.0.
5
+ See the LICENSE file for the full text.
6
+
7
+ Third-Party Notices
8
+ -------------------
9
+
10
+ This project has no runtime npm dependencies. The compiled release artifact
11
+ contains only code authored in this repository.
12
+
13
+ Development tooling (TypeScript, tsx, @types/node) is used at build time only
14
+ and is not included in the distributed artifact.
package/README.md ADDED
@@ -0,0 +1,34 @@
1
+ # PostPlus CLI
2
+
3
+ `PostPlus CLI` signs you in to PostPlus Cloud and reports local account and
4
+ hosted capability readiness. PostPlus skills are added from the public
5
+ `postplus-skills` repository.
6
+
7
+ ## Install
8
+
9
+ Requires Node.js `>=20.10.0` and npm.
10
+
11
+ ```bash
12
+ npm install -g @postplus/cli
13
+ postplus auth login
14
+ npx -y skills add PostPlusAI/postplus-skills --all
15
+ ```
16
+
17
+ ## Commands
18
+
19
+ - `postplus auth login`
20
+ - `postplus auth status`
21
+ - `postplus auth validate`
22
+ - `postplus auth refresh`
23
+ - `postplus auth revoke`
24
+ - `postplus auth logout`
25
+ - `postplus doctor`
26
+ - `postplus list`
27
+ - `postplus status`
28
+
29
+ `postplus install`, `postplus update`, and `postplus uninstall` are not skill
30
+ installation commands. Use:
31
+
32
+ ```bash
33
+ npx -y skills add PostPlusAI/postplus-skills --all
34
+ ```
@@ -0,0 +1,102 @@
1
+ import { clearAuthState, generateAuthStatusReport } from './auth.js';
2
+ import { requireHostedBaseUrl } from './hosted-release.js';
3
+ import { resolveAccessTokenState, resolveRefreshTokenState, setLocalSession, } from './local-state.js';
4
+ export async function refreshRemoteAuth() {
5
+ const [apiBaseUrl, accessTokenState, refreshTokenState] = await Promise.all([
6
+ requireHostedBaseUrl(),
7
+ resolveAccessTokenState(),
8
+ resolveRefreshTokenState(),
9
+ ]);
10
+ if (!refreshTokenState.present || !refreshTokenState.value) {
11
+ throw new Error('Run `postplus auth login` before refreshing PostPlus auth.');
12
+ }
13
+ const response = await fetch(`${apiBaseUrl}/api/postplus-cli/auth/refresh`, {
14
+ method: 'POST',
15
+ headers: {
16
+ accept: 'application/json',
17
+ ...(accessTokenState.value
18
+ ? { authorization: `Bearer ${accessTokenState.value}` }
19
+ : {}),
20
+ 'content-type': 'application/json',
21
+ },
22
+ body: JSON.stringify({
23
+ refreshToken: refreshTokenState.value,
24
+ }),
25
+ signal: AbortSignal.timeout(15000),
26
+ });
27
+ const payload = (await response.json());
28
+ if (!response.ok) {
29
+ throw new Error('error' in payload && typeof payload.error === 'string'
30
+ ? payload.error
31
+ : 'Failed to refresh remote PostPlus auth.');
32
+ }
33
+ const successPayload = payload;
34
+ await setLocalSession({
35
+ accessToken: successPayload.accessToken,
36
+ accountId: successPayload.accountId,
37
+ apiBaseUrl,
38
+ refreshToken: successPayload.refreshToken,
39
+ sessionExpiresAt: successPayload.sessionExpiresAt,
40
+ userEmail: successPayload.userEmail,
41
+ userId: successPayload.userId,
42
+ });
43
+ return {
44
+ accessTokenExpiresAt: successPayload.sessionExpiresAt,
45
+ accountId: successPayload.accountId,
46
+ apiBaseUrl,
47
+ ok: true,
48
+ subscriptionStatus: successPayload.subscriptionStatus,
49
+ userEmail: successPayload.userEmail,
50
+ userId: successPayload.userId,
51
+ };
52
+ }
53
+ export function formatAuthRefreshReport(report) {
54
+ return [
55
+ 'PostPlus CLI auth refresh',
56
+ '',
57
+ `Remote auth: ${report.ok ? 'OK' : 'FAILED'}`,
58
+ `PostPlus Cloud: ${report.apiBaseUrl}`,
59
+ `Account: ${report.accountId}`,
60
+ `User: ${report.userEmail ?? report.userId}`,
61
+ `Subscription: ${report.subscriptionStatus ?? 'unknown'}`,
62
+ `Session expires at: ${typeof report.accessTokenExpiresAt === 'number'
63
+ ? new Date(report.accessTokenExpiresAt * 1000).toISOString()
64
+ : 'unknown'}`,
65
+ ].join('\n');
66
+ }
67
+ export async function revokeRemoteAuth() {
68
+ const [apiBaseUrl, accessTokenState, refreshTokenState] = await Promise.all([
69
+ requireHostedBaseUrl(),
70
+ resolveAccessTokenState(),
71
+ resolveRefreshTokenState(),
72
+ ]);
73
+ if (!accessTokenState.present || !accessTokenState.value) {
74
+ throw new Error('Run `postplus auth login` before revoking PostPlus auth.');
75
+ }
76
+ if (!refreshTokenState.present || !refreshTokenState.value) {
77
+ throw new Error('Run `postplus auth login` before revoking PostPlus auth.');
78
+ }
79
+ const response = await fetch(`${apiBaseUrl}/api/postplus-cli/auth/revoke`, {
80
+ method: 'POST',
81
+ headers: {
82
+ accept: 'application/json',
83
+ authorization: `Bearer ${accessTokenState.value}`,
84
+ 'content-type': 'application/json',
85
+ },
86
+ body: JSON.stringify({
87
+ refreshToken: refreshTokenState.value,
88
+ }),
89
+ signal: AbortSignal.timeout(15000),
90
+ });
91
+ const payload = (await response.json());
92
+ if (!response.ok) {
93
+ throw new Error('error' in payload && typeof payload.error === 'string'
94
+ ? payload.error
95
+ : 'Failed to revoke remote PostPlus auth.');
96
+ }
97
+ return clearAuthState();
98
+ }
99
+ export async function revokeRemoteAuthAndReport() {
100
+ await revokeRemoteAuth();
101
+ return generateAuthStatusReport();
102
+ }
@@ -0,0 +1,207 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { createServer } from 'node:http';
3
+ import { requireHostedBaseUrl } from './hosted-release.js';
4
+ import { setLocalSession } from './local-state.js';
5
+ export async function loginWithBrowserHandoff() {
6
+ const baseUrl = await requireHostedBaseUrl();
7
+ const handoff = await createCliAuthHandoffServer({
8
+ allowedOrigin: new URL(baseUrl).origin,
9
+ });
10
+ const loginUrl = buildCliLoginUrl({
11
+ baseUrl,
12
+ bridgeUrl: handoff.bridgeUrl,
13
+ requestId: handoff.requestId,
14
+ });
15
+ process.stdout.write([
16
+ 'PostPlus CLI login',
17
+ '',
18
+ 'Open this URL in your browser to continue:',
19
+ loginUrl,
20
+ '',
21
+ 'Waiting for browser sign-in...',
22
+ '',
23
+ ].join('\n'));
24
+ try {
25
+ const handoffPayload = await handoff.waitForPayload();
26
+ if ('error' in handoffPayload) {
27
+ throw new Error(handoffPayload.error);
28
+ }
29
+ const validated = await validateCliSession({
30
+ accessToken: handoffPayload.accessToken,
31
+ apiBaseUrl: baseUrl,
32
+ });
33
+ await setLocalSession({
34
+ accessToken: handoffPayload.accessToken,
35
+ accountId: validated.accountId,
36
+ apiBaseUrl: baseUrl,
37
+ refreshToken: handoffPayload.refreshToken,
38
+ sessionExpiresAt: validated.sessionExpiresAt ?? handoffPayload.expiresAt ?? null,
39
+ userEmail: validated.userEmail,
40
+ userId: validated.userId,
41
+ });
42
+ return {
43
+ accountId: validated.accountId,
44
+ apiBaseUrl: baseUrl,
45
+ ok: true,
46
+ sessionExpiresAt: validated.sessionExpiresAt ?? handoffPayload.expiresAt ?? null,
47
+ userEmail: validated.userEmail,
48
+ userId: validated.userId,
49
+ };
50
+ }
51
+ finally {
52
+ await handoff.close();
53
+ }
54
+ }
55
+ function buildCliLoginUrl(input) {
56
+ const nextPath = `/auth/cli-callback?bridgeUrl=${encodeURIComponent(input.bridgeUrl)}&requestId=${encodeURIComponent(input.requestId)}`;
57
+ return `${input.baseUrl}/auth/sign-in?next=${encodeURIComponent(nextPath)}`;
58
+ }
59
+ export async function validateCliSession(input) {
60
+ const response = await fetch(`${input.apiBaseUrl}/api/postplus-cli/auth/whoami`, {
61
+ method: 'GET',
62
+ headers: {
63
+ accept: 'application/json',
64
+ authorization: `Bearer ${input.accessToken}`,
65
+ },
66
+ signal: AbortSignal.timeout(15000),
67
+ });
68
+ const payload = (await response.json());
69
+ if (!response.ok) {
70
+ throw new Error(formatCliSessionAuthError(payload));
71
+ }
72
+ return payload;
73
+ }
74
+ export function formatCliSessionAuthError(payload) {
75
+ if (payload.code === 'postplus_cli_auth_not_initialized') {
76
+ return [
77
+ 'PostPlus CLI auth is not initialized on this environment yet.',
78
+ 'Finish the PostPlus CLI server registration flow, then run `postplus auth login` again.',
79
+ 'Once the environment is ready, the CLI will automatically obtain and store its session.',
80
+ ].join(' ');
81
+ }
82
+ if (typeof payload.error === 'string' && payload.error.trim().length > 0) {
83
+ return payload.error;
84
+ }
85
+ return 'Failed to validate the browser session for PostPlus CLI.';
86
+ }
87
+ async function createCliAuthHandoffServer(input) {
88
+ const requestId = randomUUID();
89
+ return new Promise((resolve, reject) => {
90
+ let settled = false;
91
+ let cleanupTimer = null;
92
+ let resolvePayload = null;
93
+ let rejectPayload = null;
94
+ const payloadPromise = new Promise((innerResolve, innerReject) => {
95
+ resolvePayload = innerResolve;
96
+ rejectPayload = innerReject;
97
+ });
98
+ const server = createServer((request, response) => {
99
+ const origin = request.headers.origin ?? null;
100
+ const allowOrigin = origin === input.allowedOrigin ? input.allowedOrigin : null;
101
+ if (request.method === 'OPTIONS') {
102
+ if (!allowOrigin) {
103
+ response.writeHead(403);
104
+ response.end();
105
+ return;
106
+ }
107
+ response.writeHead(204, {
108
+ 'Access-Control-Allow-Headers': 'Content-Type',
109
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
110
+ 'Access-Control-Allow-Origin': allowOrigin,
111
+ 'Access-Control-Max-Age': '600',
112
+ Vary: 'Origin',
113
+ });
114
+ response.end();
115
+ return;
116
+ }
117
+ if (request.method !== 'POST' || request.url !== '/handoff') {
118
+ response.writeHead(404);
119
+ response.end();
120
+ return;
121
+ }
122
+ if (!allowOrigin) {
123
+ response.writeHead(403);
124
+ response.end();
125
+ return;
126
+ }
127
+ const chunks = [];
128
+ request.on('data', (chunk) => {
129
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
130
+ });
131
+ request.on('end', () => {
132
+ try {
133
+ const payload = JSON.parse(Buffer.concat(chunks).toString('utf8'));
134
+ if (payload.requestId !== requestId) {
135
+ throw new Error('Mismatched CLI auth handoff request id.');
136
+ }
137
+ response.writeHead(200, {
138
+ 'Access-Control-Allow-Origin': allowOrigin,
139
+ 'Content-Type': 'application/json',
140
+ Vary: 'Origin',
141
+ });
142
+ response.end(JSON.stringify({ ok: true }));
143
+ if (!settled) {
144
+ settled = true;
145
+ resolvePayload?.(payload);
146
+ }
147
+ }
148
+ catch (error) {
149
+ response.writeHead(400, {
150
+ 'Access-Control-Allow-Origin': allowOrigin,
151
+ 'Content-Type': 'application/json',
152
+ Vary: 'Origin',
153
+ });
154
+ response.end(JSON.stringify({
155
+ error: error instanceof Error
156
+ ? error.message
157
+ : 'Invalid CLI auth handoff payload.',
158
+ }));
159
+ }
160
+ });
161
+ });
162
+ server.on('error', (error) => {
163
+ if (!settled) {
164
+ settled = true;
165
+ reject(error);
166
+ }
167
+ else {
168
+ rejectPayload?.(error);
169
+ }
170
+ });
171
+ server.listen(0, '127.0.0.1', () => {
172
+ const address = server.address();
173
+ if (!address || typeof address === 'string') {
174
+ const error = new Error('Failed to bind the local CLI auth bridge.');
175
+ if (!settled) {
176
+ settled = true;
177
+ reject(error);
178
+ }
179
+ return;
180
+ }
181
+ cleanupTimer = setTimeout(() => {
182
+ if (!settled) {
183
+ settled = true;
184
+ rejectPayload?.(new Error('Timed out waiting for the browser sign-in handoff.'));
185
+ }
186
+ server.close();
187
+ }, 5 * 60 * 1000);
188
+ resolve({
189
+ bridgeUrl: `http://127.0.0.1:${address.port}/handoff`,
190
+ close: async () => new Promise((innerResolve, innerReject) => {
191
+ if (cleanupTimer) {
192
+ clearTimeout(cleanupTimer);
193
+ }
194
+ server.close((error) => {
195
+ if (error) {
196
+ innerReject(error);
197
+ return;
198
+ }
199
+ innerResolve();
200
+ });
201
+ }),
202
+ requestId,
203
+ waitForPayload: () => payloadPromise,
204
+ });
205
+ });
206
+ });
207
+ }
@@ -0,0 +1,52 @@
1
+ import { requireHostedBaseUrl } from './hosted-release.js';
2
+ import { resolveAccessTokenState } from './local-state.js';
3
+ export async function validateRemoteAuth() {
4
+ const [apiBaseUrl, accessTokenState] = await Promise.all([
5
+ requireHostedBaseUrl(),
6
+ resolveAccessTokenState(),
7
+ ]);
8
+ if (!accessTokenState.present || !accessTokenState.value) {
9
+ throw new Error('Run `postplus auth login` before validating PostPlus auth.');
10
+ }
11
+ const response = await fetch(`${apiBaseUrl}/api/postplus-cli/auth/whoami`, {
12
+ method: 'GET',
13
+ headers: {
14
+ accept: 'application/json',
15
+ authorization: `Bearer ${accessTokenState.value}`,
16
+ },
17
+ signal: AbortSignal.timeout(15000),
18
+ });
19
+ const payload = (await response.json());
20
+ if (!response.ok) {
21
+ throw new Error('error' in payload && typeof payload.error === 'string'
22
+ ? payload.error
23
+ : 'Failed to validate remote PostPlus auth.');
24
+ }
25
+ const successPayload = payload;
26
+ return {
27
+ accountId: successPayload.accountId,
28
+ apiBaseUrl,
29
+ ok: true,
30
+ sessionExpiresAt: successPayload.sessionExpiresAt,
31
+ source: accessTokenState.source === 'missing'
32
+ ? 'config'
33
+ : accessTokenState.source,
34
+ subscriptionStatus: successPayload.subscriptionStatus,
35
+ userEmail: successPayload.userEmail,
36
+ userId: successPayload.userId,
37
+ };
38
+ }
39
+ export function formatAuthValidateReport(report) {
40
+ return [
41
+ 'PostPlus CLI auth validate',
42
+ '',
43
+ `Remote auth: ${report.ok ? 'OK' : 'FAILED'}`,
44
+ `PostPlus Cloud: ${report.apiBaseUrl}`,
45
+ `Account: ${report.accountId}`,
46
+ `User: ${report.userEmail ?? report.userId}`,
47
+ `Subscription: ${report.subscriptionStatus ?? 'unknown'}`,
48
+ `Session expires at: ${typeof report.sessionExpiresAt === 'number'
49
+ ? new Date(report.sessionExpiresAt * 1000).toISOString()
50
+ : 'unknown'}`,
51
+ ].join('\n');
52
+ }
package/build/auth.js ADDED
@@ -0,0 +1,87 @@
1
+ import { clearLocalAuthState, getPostPlusConfigPath, hasLocalConfigFile, maskSecret, readLocalConfig, resolveApiBaseUrlState, resolveLocalSessionState, setLocalAccessToken, setLocalApiBaseUrl, setLocalRefreshToken, } from './local-state.js';
2
+ export async function generateAuthStatusReport() {
3
+ const [sessionState, apiBaseUrlState, configExists, config] = await Promise.all([
4
+ resolveLocalSessionState(),
5
+ resolveApiBaseUrlState(),
6
+ hasLocalConfigFile(),
7
+ readLocalConfig(),
8
+ ]);
9
+ return {
10
+ ok: sessionState.accessToken.present &&
11
+ sessionState.refreshToken.present &&
12
+ apiBaseUrlState.present,
13
+ accessToken: {
14
+ source: sessionState.accessToken.source,
15
+ present: sessionState.accessToken.present,
16
+ maskedValue: maskSecret(sessionState.accessToken.value),
17
+ },
18
+ apiBaseUrl: {
19
+ source: apiBaseUrlState.source,
20
+ present: apiBaseUrlState.present,
21
+ value: apiBaseUrlState.value,
22
+ },
23
+ config: {
24
+ path: getPostPlusConfigPath(),
25
+ exists: configExists,
26
+ accountId: config?.accountId?.trim() || null,
27
+ userEmail: typeof config?.userEmail === 'string' ? config.userEmail.trim() : null,
28
+ userId: config?.userId?.trim() || null,
29
+ },
30
+ refreshToken: {
31
+ source: sessionState.refreshToken.source,
32
+ present: sessionState.refreshToken.present,
33
+ maskedValue: maskSecret(sessionState.refreshToken.value),
34
+ },
35
+ sessionExpiresAt: sessionState.expiresAt,
36
+ };
37
+ }
38
+ export function formatAuthStatusReport(report) {
39
+ const lines = ['PostPlus CLI auth status', ''];
40
+ lines.push(report.accessToken.present
41
+ ? `[PASS] Access token: present (${report.accessToken.source})`
42
+ : '[FAIL] Access token: missing');
43
+ lines.push(report.accessToken.maskedValue
44
+ ? ` Value: ${report.accessToken.maskedValue}`
45
+ : ' Value: not configured');
46
+ lines.push(report.refreshToken.present
47
+ ? `[PASS] Refresh token: present (${report.refreshToken.source})`
48
+ : '[FAIL] Refresh token: missing');
49
+ lines.push(report.refreshToken.maskedValue
50
+ ? ` Value: ${report.refreshToken.maskedValue}`
51
+ : ' Value: not configured');
52
+ lines.push(report.apiBaseUrl.present
53
+ ? `[PASS] PostPlus Cloud: configured (${report.apiBaseUrl.source})`
54
+ : '[FAIL] PostPlus Cloud: missing');
55
+ lines.push(report.apiBaseUrl.value
56
+ ? ` Value: ${report.apiBaseUrl.value}`
57
+ : ' Value: not configured');
58
+ lines.push(report.config.exists
59
+ ? `[PASS] local config: ${report.config.path}`
60
+ : `[PASS] local config path: ${report.config.path}`);
61
+ lines.push(` Account: ${report.config.accountId ?? 'not bound'}`);
62
+ lines.push(` User: ${report.config.userEmail ?? report.config.userId ?? 'not bound'}`);
63
+ lines.push(` Session expires at: ${typeof report.sessionExpiresAt === 'number'
64
+ ? new Date(report.sessionExpiresAt * 1000).toISOString()
65
+ : 'unknown'}`);
66
+ lines.push('', report.ok ? 'Auth status OK.' : 'Auth status incomplete.');
67
+ return lines.join('\n');
68
+ }
69
+ export async function configureAccessToken(accessToken) {
70
+ await setLocalAccessToken(accessToken);
71
+ return generateAuthStatusReport();
72
+ }
73
+ export async function configureRefreshToken(refreshToken) {
74
+ await setLocalRefreshToken(refreshToken);
75
+ return generateAuthStatusReport();
76
+ }
77
+ export async function configureApiBaseUrl(apiBaseUrl) {
78
+ await setLocalApiBaseUrl(apiBaseUrl);
79
+ return generateAuthStatusReport();
80
+ }
81
+ export async function clearAuthState() {
82
+ await clearLocalAuthState();
83
+ return generateAuthStatusReport();
84
+ }
85
+ export async function prepareAuthState() {
86
+ return generateAuthStatusReport();
87
+ }
@@ -0,0 +1,31 @@
1
+ import { resolveHostedBaseUrl } from './hosted-release.js';
2
+ function createPass(id, label, detail) {
3
+ return {
4
+ id,
5
+ label,
6
+ status: 'pass',
7
+ detail,
8
+ };
9
+ }
10
+ export async function generateDoctorReport() {
11
+ const hostedBaseUrl = await resolveHostedBaseUrl();
12
+ const checks = [
13
+ createPass('hosted_base_url', 'PostPlus Cloud', `Using ${hostedBaseUrl ?? 'https://postplus.io'}`),
14
+ ];
15
+ return {
16
+ ok: checks.every((check) => check.status === 'pass'),
17
+ checks,
18
+ };
19
+ }
20
+ export function formatDoctorReport(report) {
21
+ const lines = ['PostPlus CLI doctor', ''];
22
+ for (const check of report.checks) {
23
+ const marker = check.status === 'pass' ? '[PASS]' : '[FAIL]';
24
+ lines.push(`${marker} ${check.label}: ${check.detail}`);
25
+ if (check.fix) {
26
+ lines.push(` Fix: ${check.fix}`);
27
+ }
28
+ }
29
+ lines.push('', report.ok ? 'Doctor passed.' : 'Doctor failed.');
30
+ return lines.join('\n');
31
+ }
@@ -0,0 +1,18 @@
1
+ import { resolveApiBaseUrlState } from './local-state.js';
2
+ function normalizeHostedBaseUrl(value) {
3
+ const url = new URL(value.trim());
4
+ const pathname = url.pathname.replace(/\/+$/, '');
5
+ const normalizedPathname = pathname.length > 0 && pathname !== '/' ? pathname : '';
6
+ return `${url.origin}${normalizedPathname}`;
7
+ }
8
+ export async function resolveHostedBaseUrl() {
9
+ const state = await resolveApiBaseUrlState();
10
+ return state.value ? normalizeHostedBaseUrl(state.value) : null;
11
+ }
12
+ export async function requireHostedBaseUrl() {
13
+ const baseUrl = await resolveHostedBaseUrl();
14
+ if (!baseUrl) {
15
+ throw new Error('Could not resolve a PostPlus API base URL.');
16
+ }
17
+ return baseUrl;
18
+ }
package/build/index.js ADDED
@@ -0,0 +1,236 @@
1
+ #!/usr/bin/env node
2
+ import { formatAuthRefreshReport, refreshRemoteAuth, revokeRemoteAuthAndReport, } from './auth-lifecycle.js';
3
+ import { loginWithBrowserHandoff } from './auth-login.js';
4
+ import { formatAuthValidateReport, validateRemoteAuth, } from './auth-validate.js';
5
+ import { clearAuthState, formatAuthStatusReport, generateAuthStatusReport, } from './auth.js';
6
+ import { formatDoctorReport, generateDoctorReport, } from './doctor.js';
7
+ import { assertConfigFilePermissions } from './local-state.js';
8
+ import { POSTPLUS_SKILLS_INSTALL_COMMAND, loadPublicSkillCatalog, } from './skill-catalog.js';
9
+ import { formatStatusReport, generateStatusReport } from './status.js';
10
+ const REMOVED_SKILL_COMMAND_MESSAGE = `PostPlus CLI no longer installs skills directly. Run \`${POSTPLUS_SKILLS_INSTALL_COMMAND}\`.`;
11
+ function printAuthHelp() {
12
+ process.stdout.write(`PostPlus CLI — auth commands
13
+
14
+ Usage:
15
+ postplus auth login Sign in with your PostPlus account in a browser
16
+ postplus auth status Show current auth state (tokens, account, expiry)
17
+ postplus auth validate Validate the current session against PostPlus Cloud
18
+ postplus auth refresh Refresh the current session tokens
19
+ postplus auth revoke Revoke the current session on PostPlus Cloud
20
+ postplus auth logout Clear local auth state
21
+
22
+ Options:
23
+ --json Output results as JSON
24
+
25
+ Run \`postplus help\` for all commands.
26
+ `);
27
+ }
28
+ function printHelp() {
29
+ process.stdout.write(`PostPlus CLI
30
+
31
+ Usage:
32
+ postplus auth login
33
+ postplus auth refresh [--json]
34
+ postplus auth revoke [--json]
35
+ postplus auth status [--json]
36
+ postplus auth validate [--json]
37
+ postplus auth logout [--json]
38
+ postplus doctor [--json]
39
+ postplus list [--json]
40
+ postplus status [--json]
41
+ postplus help
42
+
43
+ Skills:
44
+ ${POSTPLUS_SKILLS_INSTALL_COMMAND}
45
+ `);
46
+ }
47
+ async function runDoctor(json) {
48
+ const report = await generateDoctorReport();
49
+ if (json) {
50
+ writeJson(report);
51
+ }
52
+ else {
53
+ process.stdout.write(`${formatDoctorReport(report)}\n`);
54
+ }
55
+ return report.ok ? 0 : 1;
56
+ }
57
+ async function runAuthStatus(json) {
58
+ const report = await generateAuthStatusReport();
59
+ if (json) {
60
+ writeJson(report);
61
+ }
62
+ else {
63
+ process.stdout.write(`${formatAuthStatusReport(report)}\n`);
64
+ }
65
+ return report.ok ? 0 : 1;
66
+ }
67
+ async function runStatus(json) {
68
+ const report = await generateStatusReport();
69
+ if (json) {
70
+ writeJson(report);
71
+ }
72
+ else {
73
+ process.stdout.write(`${formatStatusReport(report)}\n`);
74
+ }
75
+ return report.ok ? 0 : 1;
76
+ }
77
+ async function runList(json) {
78
+ const catalog = await loadPublicSkillCatalog();
79
+ if (json) {
80
+ writeJson(catalog);
81
+ return 0;
82
+ }
83
+ const lines = [
84
+ 'PostPlus skills',
85
+ '',
86
+ `Source: ${catalog.source}`,
87
+ `Install: ${catalog.installCommand}`,
88
+ '',
89
+ ];
90
+ for (const entry of catalog.skills) {
91
+ lines.push(entry.path ? `- ${entry.skillId}: ${entry.path}` : `- ${entry.skillId}`);
92
+ }
93
+ process.stdout.write(`${lines.join('\n')}\n`);
94
+ return 0;
95
+ }
96
+ function writeJson(value) {
97
+ process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
98
+ }
99
+ async function runAuthLogout(json) {
100
+ const report = await clearAuthState();
101
+ if (json) {
102
+ writeJson(report);
103
+ }
104
+ else {
105
+ process.stdout.write(`${formatAuthStatusReport(report)}\n`);
106
+ }
107
+ return 0;
108
+ }
109
+ async function runAuthRefresh(json) {
110
+ const report = await refreshRemoteAuth();
111
+ if (json) {
112
+ writeJson(report);
113
+ }
114
+ else {
115
+ process.stdout.write(`${formatAuthRefreshReport(report)}\n`);
116
+ }
117
+ return report.ok ? 0 : 1;
118
+ }
119
+ async function runAuthRevoke(json) {
120
+ const report = await revokeRemoteAuthAndReport();
121
+ if (json) {
122
+ writeJson(report);
123
+ }
124
+ else {
125
+ process.stdout.write(`${formatAuthStatusReport(report)}\n`);
126
+ }
127
+ return 0;
128
+ }
129
+ async function runAuthLogin() {
130
+ const report = await loginWithBrowserHandoff();
131
+ process.stdout.write([
132
+ '',
133
+ 'PostPlus CLI login complete.',
134
+ `Account: ${report.accountId}`,
135
+ `PostPlus Cloud: ${report.apiBaseUrl}`,
136
+ `User: ${report.userEmail ?? 'unknown'}`,
137
+ `Session expires at: ${typeof report.sessionExpiresAt === 'number'
138
+ ? new Date(report.sessionExpiresAt * 1000).toISOString()
139
+ : 'unknown'}`,
140
+ '',
141
+ ].join('\n'));
142
+ return report.ok ? 0 : 1;
143
+ }
144
+ async function runAuthValidate(json) {
145
+ const report = await validateRemoteAuth();
146
+ if (json) {
147
+ writeJson(report);
148
+ }
149
+ else {
150
+ process.stdout.write(`${formatAuthValidateReport(report)}\n`);
151
+ }
152
+ return report.ok ? 0 : 1;
153
+ }
154
+ async function main() {
155
+ const [command, ...rest] = process.argv.slice(2);
156
+ await assertConfigFilePermissions();
157
+ const json = rest.includes('--json');
158
+ switch (command) {
159
+ case undefined:
160
+ case '--help':
161
+ case '-h':
162
+ printHelp();
163
+ process.exitCode = 0;
164
+ return;
165
+ case 'help': {
166
+ const [helpTopic] = rest;
167
+ if (helpTopic === 'auth') {
168
+ printAuthHelp();
169
+ }
170
+ else {
171
+ printHelp();
172
+ }
173
+ process.exitCode = 0;
174
+ return;
175
+ }
176
+ case 'doctor':
177
+ process.exitCode = await runDoctor(json);
178
+ return;
179
+ case 'install':
180
+ case 'update':
181
+ case 'uninstall':
182
+ process.stderr.write(`${REMOVED_SKILL_COMMAND_MESSAGE}\n`);
183
+ process.exitCode = 1;
184
+ return;
185
+ case 'list':
186
+ process.exitCode = await runList(json);
187
+ return;
188
+ case 'status':
189
+ process.exitCode = await runStatus(json);
190
+ return;
191
+ case 'auth': {
192
+ const [subcommand, ...authRest] = rest;
193
+ switch (subcommand) {
194
+ case 'login':
195
+ process.exitCode = await runAuthLogin();
196
+ return;
197
+ case 'refresh':
198
+ process.exitCode = await runAuthRefresh(authRest.includes('--json'));
199
+ return;
200
+ case 'revoke':
201
+ process.exitCode = await runAuthRevoke(authRest.includes('--json'));
202
+ return;
203
+ case 'status':
204
+ process.exitCode = await runAuthStatus(authRest.includes('--json'));
205
+ return;
206
+ case 'validate':
207
+ process.exitCode = await runAuthValidate(authRest.includes('--json'));
208
+ return;
209
+ case 'logout':
210
+ process.exitCode = await runAuthLogout(authRest.includes('--json'));
211
+ return;
212
+ case 'help':
213
+ case '--help':
214
+ case '-h':
215
+ case undefined:
216
+ printAuthHelp();
217
+ process.exitCode = 0;
218
+ return;
219
+ default:
220
+ process.stderr.write(`Unknown auth command: ${subcommand}\n\n`);
221
+ printAuthHelp();
222
+ process.exitCode = 1;
223
+ return;
224
+ }
225
+ }
226
+ default:
227
+ process.stderr.write(`Unknown command: ${command}\n\n`);
228
+ printHelp();
229
+ process.exitCode = 1;
230
+ }
231
+ }
232
+ main().catch((error) => {
233
+ const message = error instanceof Error ? error.message : 'Unexpected PostPlus CLI error';
234
+ process.stderr.write(`${message}\n`);
235
+ process.exitCode = 1;
236
+ });
@@ -0,0 +1,268 @@
1
+ import { constants as fsConstants } from 'node:fs';
2
+ import { access, chmod, mkdir, readFile, stat, writeFile } from 'node:fs/promises';
3
+ import { homedir, platform } from 'node:os';
4
+ import { dirname, join, resolve } from 'node:path';
5
+ export const DEFAULT_POSTPLUS_API_BASE_URL = 'https://postplus.io';
6
+ function resolveConfigProfile() {
7
+ const value = process.env.POSTPLUS_PROFILE?.trim();
8
+ if (!value || value.toLowerCase() === 'default') {
9
+ return null;
10
+ }
11
+ return value.replace(/[^a-zA-Z0-9._-]+/g, '-');
12
+ }
13
+ function resolveDefaultConfigRoot() {
14
+ const profile = resolveConfigProfile();
15
+ const appendProfile = (basePath) => profile ? join(basePath, 'profiles', profile) : basePath;
16
+ switch (platform()) {
17
+ case 'darwin':
18
+ return appendProfile(join(homedir(), 'Library', 'Application Support', 'postplus'));
19
+ case 'win32': {
20
+ const appData = process.env.APPDATA?.trim();
21
+ return appendProfile(appData && appData.length > 0
22
+ ? join(appData, 'postplus')
23
+ : join(homedir(), 'AppData', 'Roaming', 'postplus'));
24
+ }
25
+ default: {
26
+ const xdgConfigHome = process.env.XDG_CONFIG_HOME?.trim();
27
+ return appendProfile(xdgConfigHome && xdgConfigHome.length > 0
28
+ ? join(xdgConfigHome, 'postplus')
29
+ : join(homedir(), '.config', 'postplus'));
30
+ }
31
+ }
32
+ }
33
+ export function getPostPlusConfigDir() {
34
+ const override = process.env.POSTPLUS_CONFIG_DIR?.trim();
35
+ return override && override.length > 0
36
+ ? resolve(override)
37
+ : resolveDefaultConfigRoot();
38
+ }
39
+ export function getPostPlusConfigPath() {
40
+ return join(getPostPlusConfigDir(), 'config.json');
41
+ }
42
+ export async function readLocalConfig() {
43
+ const configPath = getPostPlusConfigPath();
44
+ try {
45
+ const raw = await readFile(configPath, 'utf8');
46
+ const parsed = JSON.parse(raw);
47
+ return parsed && typeof parsed === 'object' ? parsed : null;
48
+ }
49
+ catch (error) {
50
+ const nodeError = error;
51
+ if (nodeError.code === 'ENOENT') {
52
+ return null;
53
+ }
54
+ throw error;
55
+ }
56
+ }
57
+ const CONFIG_FILE_MODE = 0o600;
58
+ export async function writeLocalConfig(config) {
59
+ const configPath = getPostPlusConfigPath();
60
+ await mkdir(dirname(configPath), { recursive: true });
61
+ await writeFile(configPath, `${JSON.stringify({
62
+ ...config,
63
+ updatedAt: new Date().toISOString(),
64
+ }, null, 2)}\n`, { encoding: 'utf8', mode: CONFIG_FILE_MODE });
65
+ // Repair permissions if the file pre-existed with broader access.
66
+ await chmod(configPath, CONFIG_FILE_MODE);
67
+ }
68
+ export async function assertConfigFilePermissions() {
69
+ const configPath = getPostPlusConfigPath();
70
+ try {
71
+ const info = await stat(configPath);
72
+ const mode = info.mode & 0o777;
73
+ if (mode !== CONFIG_FILE_MODE) {
74
+ process.stderr.write(`PostPlus CLI: repairing config file permissions at ${configPath} (was ${mode.toString(8)}, setting to ${CONFIG_FILE_MODE.toString(8)}).\n`);
75
+ await chmod(configPath, CONFIG_FILE_MODE);
76
+ }
77
+ }
78
+ catch (error) {
79
+ const nodeError = error;
80
+ if (nodeError.code !== 'ENOENT') {
81
+ throw error;
82
+ }
83
+ }
84
+ }
85
+ export async function updateLocalConfig(updater) {
86
+ const next = updater(await readLocalConfig());
87
+ await writeLocalConfig(next);
88
+ return next;
89
+ }
90
+ export async function clearLocalAuthState() {
91
+ return updateLocalConfig((current) => {
92
+ const next = {
93
+ ...(current ?? {}),
94
+ };
95
+ delete next.accessToken;
96
+ delete next.accountId;
97
+ delete next.apiKey;
98
+ delete next.machineId;
99
+ delete next.refreshToken;
100
+ delete next.sessionExpiresAt;
101
+ delete next.userEmail;
102
+ delete next.userId;
103
+ return next;
104
+ });
105
+ }
106
+ export async function setLocalAccessToken(accessToken) {
107
+ const normalizedAccessToken = accessToken.trim();
108
+ if (normalizedAccessToken.length === 0) {
109
+ throw new Error('POSTPLUS_ACCESS_TOKEN cannot be empty.');
110
+ }
111
+ return updateLocalConfig((current) => ({
112
+ ...(current ?? {}),
113
+ accessToken: normalizedAccessToken,
114
+ }));
115
+ }
116
+ export async function setLocalRefreshToken(refreshToken) {
117
+ const normalizedRefreshToken = refreshToken.trim();
118
+ if (normalizedRefreshToken.length === 0) {
119
+ throw new Error('POSTPLUS_REFRESH_TOKEN cannot be empty.');
120
+ }
121
+ return updateLocalConfig((current) => ({
122
+ ...(current ?? {}),
123
+ refreshToken: normalizedRefreshToken,
124
+ }));
125
+ }
126
+ export async function setLocalApiBaseUrl(apiBaseUrl) {
127
+ const normalizedApiBaseUrl = apiBaseUrl.trim();
128
+ if (normalizedApiBaseUrl.length === 0) {
129
+ throw new Error('POSTPLUS_API_BASE_URL cannot be empty.');
130
+ }
131
+ const normalizedUrl = new URL(normalizedApiBaseUrl).toString();
132
+ return updateLocalConfig((current) => ({
133
+ ...(current ?? {}),
134
+ apiBaseUrl: normalizedUrl.replace(/\/+$/, ''),
135
+ }));
136
+ }
137
+ export async function setLocalSession(input) {
138
+ const accessToken = input.accessToken.trim();
139
+ const refreshToken = input.refreshToken.trim();
140
+ const apiBaseUrl = input.apiBaseUrl.trim().replace(/\/+$/, '');
141
+ if (accessToken.length === 0) {
142
+ throw new Error('POSTPLUS_ACCESS_TOKEN cannot be empty.');
143
+ }
144
+ if (refreshToken.length === 0) {
145
+ throw new Error('POSTPLUS_REFRESH_TOKEN cannot be empty.');
146
+ }
147
+ if (apiBaseUrl.length === 0) {
148
+ throw new Error('POSTPLUS_API_BASE_URL cannot be empty.');
149
+ }
150
+ return updateLocalConfig((current) => ({
151
+ ...omitLegacyAuthFields(current),
152
+ accessToken,
153
+ accountId: input.accountId,
154
+ apiBaseUrl,
155
+ refreshToken,
156
+ sessionExpiresAt: input.sessionExpiresAt,
157
+ userEmail: input.userEmail,
158
+ userId: input.userId,
159
+ }));
160
+ }
161
+ export async function hasLocalConfigFile() {
162
+ try {
163
+ await access(getPostPlusConfigPath(), fsConstants.F_OK);
164
+ return true;
165
+ }
166
+ catch {
167
+ return false;
168
+ }
169
+ }
170
+ export async function resolveAccessTokenState() {
171
+ const envValue = process.env.POSTPLUS_ACCESS_TOKEN?.trim();
172
+ if (envValue && envValue.length > 0) {
173
+ return {
174
+ source: 'env',
175
+ present: true,
176
+ value: envValue,
177
+ };
178
+ }
179
+ const config = await readLocalConfig();
180
+ const configValue = config?.accessToken?.trim();
181
+ if (configValue && configValue.length > 0) {
182
+ return {
183
+ source: 'config',
184
+ present: true,
185
+ value: configValue,
186
+ };
187
+ }
188
+ return {
189
+ source: 'missing',
190
+ present: false,
191
+ value: null,
192
+ };
193
+ }
194
+ export async function resolveRefreshTokenState() {
195
+ const envValue = process.env.POSTPLUS_REFRESH_TOKEN?.trim();
196
+ if (envValue && envValue.length > 0) {
197
+ return {
198
+ source: 'env',
199
+ present: true,
200
+ value: envValue,
201
+ };
202
+ }
203
+ const config = await readLocalConfig();
204
+ const configValue = config?.refreshToken?.trim();
205
+ if (configValue && configValue.length > 0) {
206
+ return {
207
+ source: 'config',
208
+ present: true,
209
+ value: configValue,
210
+ };
211
+ }
212
+ return {
213
+ source: 'missing',
214
+ present: false,
215
+ value: null,
216
+ };
217
+ }
218
+ export async function resolveLocalSessionState() {
219
+ const [accessToken, refreshToken, config] = await Promise.all([
220
+ resolveAccessTokenState(),
221
+ resolveRefreshTokenState(),
222
+ readLocalConfig(),
223
+ ]);
224
+ return {
225
+ accessToken,
226
+ expiresAt: typeof config?.sessionExpiresAt === 'number'
227
+ ? config.sessionExpiresAt
228
+ : null,
229
+ refreshToken,
230
+ };
231
+ }
232
+ export async function resolveApiBaseUrlState() {
233
+ const envApiBaseUrl = process.env.POSTPLUS_API_BASE_URL?.trim();
234
+ if (envApiBaseUrl && envApiBaseUrl.length > 0) {
235
+ return {
236
+ source: 'env',
237
+ present: true,
238
+ value: envApiBaseUrl.replace(/\/+$/, ''),
239
+ };
240
+ }
241
+ const config = await readLocalConfig();
242
+ const configApiBaseUrl = config?.apiBaseUrl?.trim();
243
+ if (configApiBaseUrl && configApiBaseUrl.length > 0) {
244
+ return {
245
+ source: 'config',
246
+ present: true,
247
+ value: configApiBaseUrl.replace(/\/+$/, ''),
248
+ };
249
+ }
250
+ return {
251
+ source: 'default',
252
+ present: true,
253
+ value: DEFAULT_POSTPLUS_API_BASE_URL,
254
+ };
255
+ }
256
+ export function maskSecret(value) {
257
+ if (!value) {
258
+ return null;
259
+ }
260
+ if (value.length <= 8) {
261
+ return '*'.repeat(value.length);
262
+ }
263
+ return `${value.slice(0, 4)}…${value.slice(-4)}`;
264
+ }
265
+ function omitLegacyAuthFields(current) {
266
+ const { apiKey: _apiKey, machineId: _machineId, ...rest } = (current ?? {});
267
+ return rest;
268
+ }
@@ -0,0 +1,56 @@
1
+ export const POSTPLUS_SKILLS_REPO = 'PostPlusAI/postplus-skills';
2
+ export const POSTPLUS_SKILLS_INSTALL_COMMAND = 'npx -y skills add PostPlusAI/postplus-skills --all';
3
+ export const POSTPLUS_SKILLS_LIST_COMMAND = 'npx -y skills add PostPlusAI/postplus-skills --list';
4
+ const POSTPLUS_SKILLS_INDEX_URL = 'https://raw.githubusercontent.com/PostPlusAI/postplus-skills/main/skills/INDEX.md';
5
+ export async function loadPublicSkillCatalog() {
6
+ const response = await fetch(POSTPLUS_SKILLS_INDEX_URL, {
7
+ headers: {
8
+ accept: 'text/markdown,text/plain',
9
+ },
10
+ signal: AbortSignal.timeout(15000),
11
+ });
12
+ if (!response.ok) {
13
+ throw new Error(`Failed to load PostPlus skill catalog (${response.status}): ${response.statusText}`);
14
+ }
15
+ const indexText = await response.text();
16
+ return {
17
+ source: POSTPLUS_SKILLS_REPO,
18
+ indexUrl: POSTPLUS_SKILLS_INDEX_URL,
19
+ installCommand: POSTPLUS_SKILLS_INSTALL_COMMAND,
20
+ listCommand: POSTPLUS_SKILLS_LIST_COMMAND,
21
+ skills: parseSkillIndex(indexText),
22
+ };
23
+ }
24
+ function parseSkillIndex(indexText) {
25
+ const skills = [];
26
+ let inReleasedSkills = false;
27
+ let currentSkill = null;
28
+ for (const line of indexText.split('\n')) {
29
+ if (line.trim() === '## Released Skills') {
30
+ inReleasedSkills = true;
31
+ continue;
32
+ }
33
+ if (!inReleasedSkills) {
34
+ continue;
35
+ }
36
+ const skillMatch = line.match(/^- `([^`]+)`\s*$/);
37
+ if (skillMatch) {
38
+ currentSkill = skillMatch[1] ?? null;
39
+ if (currentSkill) {
40
+ skills.push({
41
+ skillId: currentSkill,
42
+ path: null,
43
+ });
44
+ }
45
+ continue;
46
+ }
47
+ const pathMatch = line.match(/^\s+- Path: `([^`]+)`\s*$/);
48
+ if (pathMatch && currentSkill) {
49
+ const last = skills.at(-1);
50
+ if (last?.skillId === currentSkill) {
51
+ last.path = pathMatch[1] ?? null;
52
+ }
53
+ }
54
+ }
55
+ return skills;
56
+ }
@@ -0,0 +1,24 @@
1
+ import { formatAuthStatusReport, generateAuthStatusReport, } from './auth.js';
2
+ import { formatDoctorReport, generateDoctorReport, } from './doctor.js';
3
+ export async function generateStatusReport() {
4
+ const [doctor, auth] = await Promise.all([
5
+ generateDoctorReport(),
6
+ generateAuthStatusReport(),
7
+ ]);
8
+ return {
9
+ ok: doctor.ok && auth.ok,
10
+ doctor,
11
+ auth,
12
+ };
13
+ }
14
+ export function formatStatusReport(report) {
15
+ return [
16
+ 'PostPlus CLI status',
17
+ '',
18
+ `Overall: ${report.ok ? 'OK' : 'INCOMPLETE'}`,
19
+ '',
20
+ formatDoctorReport(report.doctor),
21
+ '',
22
+ formatAuthStatusReport(report.auth),
23
+ ].join('\n');
24
+ }
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@postplus/cli",
3
+ "version": "0.1.7",
4
+ "packageManager": "pnpm@10.30.3+sha512.c961d1e0a2d8e354ecaa5166b822516668b7f44cb5bd95122d590dd81922f606f5473b6d23ec4a5be05e7fcd18e8488d47d978bbe981872f1145d06e9a740017",
5
+ "type": "module",
6
+ "description": "PostPlus CLI for PostPlus Cloud auth, status, and diagnostics.",
7
+ "license": "Apache-2.0",
8
+ "files": [
9
+ "build/**",
10
+ "LICENSE",
11
+ "NOTICE",
12
+ "README.md"
13
+ ],
14
+ "publishConfig": {
15
+ "access": "public",
16
+ "registry": "https://registry.npmjs.org/"
17
+ },
18
+ "engines": {
19
+ "node": ">=20.10.0"
20
+ },
21
+ "bin": {
22
+ "postplus": "./build/index.js"
23
+ },
24
+ "scripts": {
25
+ "build": "tsc",
26
+ "clean": "rm -rf .turbo node_modules build",
27
+ "release:package": "node ./scripts/package-release.mjs",
28
+ "start": "tsx src/index.ts",
29
+ "test:acceptance": "node ./scripts/acceptance.mjs",
30
+ "test": "tsx --test src/postplus-cli.test.ts",
31
+ "typecheck": "tsc --noEmit"
32
+ },
33
+ "devDependencies": {
34
+ "@types/node": "^24.6.2",
35
+ "tsx": "^4.21.0",
36
+ "typescript": "^5.9.3"
37
+ },
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/PostPlusAI/postplus-cli.git"
41
+ }
42
+ }