@optima-chat/dev-skills 0.7.33 → 0.7.36
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/AGENTS.md +3 -0
- package/bin/helpers/billing-http.ts +191 -0
- package/bin/helpers/confirm-prompt.ts +23 -0
- package/bin/helpers/entitlement/grant.ts +70 -0
- package/bin/helpers/entitlement/list.ts +77 -0
- package/bin/helpers/entitlement/revoke.ts +116 -0
- package/bin/helpers/entitlement.ts +32 -0
- package/bin/helpers/infisical-secrets.ts +41 -0
- package/bin/helpers/plugin/set-default.ts +65 -0
- package/bin/helpers/plugin/set-paid.ts +69 -0
- package/bin/helpers/plugin/show.ts +42 -0
- package/bin/helpers/plugin.ts +32 -0
- package/bin/helpers/product/add-channel.ts +78 -0
- package/bin/helpers/product/create.ts +96 -0
- package/bin/helpers/product/show.ts +43 -0
- package/bin/helpers/product/toggle-channel.ts +56 -0
- package/bin/helpers/product/update.ts +72 -0
- package/bin/helpers/product.ts +46 -0
- package/dist/bin/helpers/billing-http.js +153 -0
- package/dist/bin/helpers/confirm-prompt.js +54 -0
- package/dist/bin/helpers/entitlement/grant.js +73 -0
- package/dist/bin/helpers/entitlement/list.js +62 -0
- package/dist/bin/helpers/entitlement/revoke.js +105 -0
- package/dist/bin/helpers/entitlement.js +39 -0
- package/dist/bin/helpers/infisical-secrets.js +33 -0
- package/dist/bin/helpers/plugin/set-default.js +61 -0
- package/dist/bin/helpers/plugin/set-paid.js +65 -0
- package/dist/bin/helpers/plugin/show.js +45 -0
- package/dist/bin/helpers/plugin.js +39 -0
- package/dist/bin/helpers/product/add-channel.js +95 -0
- package/dist/bin/helpers/product/create.js +124 -0
- package/dist/bin/helpers/product/show.js +46 -0
- package/dist/bin/helpers/product/toggle-channel.js +61 -0
- package/dist/bin/helpers/product/update.js +92 -0
- package/dist/bin/helpers/product.js +53 -0
- package/docs/superpowers/plans/2026-05-24-marketplace-admin-cli-impl.md +1973 -0
- package/docs/superpowers/plans/2026-05-25-optima-plugin-cli-impl.md +700 -0
- package/docs/superpowers/specs/2026-05-24-marketplace-admin-cli-design.md +324 -0
- package/docs/superpowers/specs/2026-05-25-optima-plugin-cli-design.md +156 -0
- package/package.json +8 -5
package/AGENTS.md
CHANGED
|
@@ -11,6 +11,9 @@ Prefer the installed CLI tools over reimplementing long shell workflows:
|
|
|
11
11
|
- `optima-generate-test-token [options]`
|
|
12
12
|
- `optima-grant-subscription <email> [options]`
|
|
13
13
|
- `optima-grant-balance <email> --amount <usd> [options]`
|
|
14
|
+
- `optima-product <create|update|add-channel|toggle-channel|show> [options]` — manage paid-plugin marketplace Products + Stripe channels (Wave 1.5 admin endpoints; stage default)
|
|
15
|
+
- `optima-entitlement <grant|revoke|list> [options]` — admin-grant / revoke / list paid-plugin entitlements (refuses revoke of PAYMENT / PARTNER source)
|
|
16
|
+
- `optima-plugin <show|set-paid|set-default> [options]` — flip a plugin's skills-side paid/free state (isPaid) + defaultForUser (the user-facing gate; pairs with optima-product for the billing side)
|
|
14
17
|
|
|
15
18
|
For code-reading tasks across Optima repositories, use `gh` commands against `Optima-Chat/<repo>`.
|
|
16
19
|
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { execSync } from 'child_process';
|
|
2
|
+
import { fetchInfisicalSecret } from './infisical-secrets';
|
|
3
|
+
import { getInfisicalConfig, getInfisicalToken } from './db-utils';
|
|
4
|
+
|
|
5
|
+
const USER_AUTH_URLS: Record<string, string> = {
|
|
6
|
+
stage: 'https://auth.stage.optima.onl',
|
|
7
|
+
prod: 'https://auth.optima.onl',
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Validate the --env flag value at command entry, before any I/O.
|
|
12
|
+
*
|
|
13
|
+
* Without this, a typo like `--env staging` flows downstream and surfaces as
|
|
14
|
+
* a confusing error: entitlement subcommands hit resolveUserId first (SSH
|
|
15
|
+
* tunnel to RDS_HOSTS[undefined] → cryptic ssh failure), product subcommands
|
|
16
|
+
* reach getServiceToken (USER_AUTH_URLS[undefined] → "Unknown env"). All
|
|
17
|
+
* fail-closed (no wrong-env write), but the UX diverges per subcommand.
|
|
18
|
+
* Every runX handler calls this first so the error is uniform and immediate.
|
|
19
|
+
*/
|
|
20
|
+
export function validateEnv(env: string): 'stage' | 'prod' {
|
|
21
|
+
if (env !== 'stage' && env !== 'prod') {
|
|
22
|
+
throw new Error(`--env must be "stage" or "prod" (got: ${env})`);
|
|
23
|
+
}
|
|
24
|
+
return env;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// T1 discovered: client_id differs per env (stage=dev-skills-ubd3qz6n,
|
|
28
|
+
// prod=dev-skills-hinxa0rs). Both stored in Infisical alongside the
|
|
29
|
+
// secret at /shared-secrets/oauth-clients/.
|
|
30
|
+
const DEV_SKILLS_OAUTH_PATH = '/shared-secrets/oauth-clients';
|
|
31
|
+
const DEV_SKILLS_CLIENT_ID_KEY = 'DEV_SKILLS_OAUTH_CLIENT_ID';
|
|
32
|
+
const DEV_SKILLS_CLIENT_SECRET_KEY = 'DEV_SKILLS_OAUTH_CLIENT_SECRET';
|
|
33
|
+
|
|
34
|
+
// ───── Cache (process-lifetime) ─────────────────────────────────────────────
|
|
35
|
+
// One CLI invocation does at most a handful of HTTP calls. We mint the M2M
|
|
36
|
+
// token once and reuse it. Cross-invocation re-mint is fine — JWT TTL is
|
|
37
|
+
// typically ≥1h, far longer than any single CLI run.
|
|
38
|
+
//
|
|
39
|
+
// NOT handled (acceptable for admin CLI):
|
|
40
|
+
// * Token expiry mid-invocation — a long-stalled revoke (list call + 5min
|
|
41
|
+
// pause + refund call) could in theory expire. Operator can retry.
|
|
42
|
+
// * Infisical 5xx retry — getInfisicalToken is sync execSync curl with no
|
|
43
|
+
// retry; any transient failure surfaces immediately. Re-run the CLI.
|
|
44
|
+
const tokenCache: Record<string, string> = {};
|
|
45
|
+
const billingUrlCache: Record<string, string> = {};
|
|
46
|
+
const skillsUrlCache: Record<string, string> = {};
|
|
47
|
+
|
|
48
|
+
function getBillingUrl(env: string): string {
|
|
49
|
+
if (billingUrlCache[env]) return billingUrlCache[env];
|
|
50
|
+
const url = fetchInfisicalSecret(env, '/shared-secrets/domain-urls', 'BILLING_URL');
|
|
51
|
+
billingUrlCache[env] = url;
|
|
52
|
+
return url;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function getSkillsUrl(env: string): string {
|
|
56
|
+
if (skillsUrlCache[env]) return skillsUrlCache[env];
|
|
57
|
+
const url = fetchInfisicalSecret(env, '/shared-secrets/domain-urls', 'SKILLS_REGISTRY_URL');
|
|
58
|
+
skillsUrlCache[env] = url;
|
|
59
|
+
return url;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function getServiceToken(env: string): string {
|
|
63
|
+
if (tokenCache[env]) return tokenCache[env];
|
|
64
|
+
|
|
65
|
+
const cfg = getInfisicalConfig();
|
|
66
|
+
const tok = getInfisicalToken(cfg);
|
|
67
|
+
// Fetch BOTH client_id and client_secret from Infisical — they differ per env.
|
|
68
|
+
const clientId = fetchInfisicalSecret(env, DEV_SKILLS_OAUTH_PATH, DEV_SKILLS_CLIENT_ID_KEY, cfg, tok);
|
|
69
|
+
const clientSecret = fetchInfisicalSecret(env, DEV_SKILLS_OAUTH_PATH, DEV_SKILLS_CLIENT_SECRET_KEY, cfg, tok);
|
|
70
|
+
|
|
71
|
+
const authUrl = USER_AUTH_URLS[env];
|
|
72
|
+
if (!authUrl) throw new Error(`Unknown env: ${env}`);
|
|
73
|
+
|
|
74
|
+
const body = `grant_type=client_credentials&client_id=${encodeURIComponent(clientId)}&client_secret=${encodeURIComponent(clientSecret)}`;
|
|
75
|
+
const response = execSync(
|
|
76
|
+
`curl -s -X POST '${authUrl}/api/v1/oauth/token' -H 'Content-Type: application/x-www-form-urlencoded' -d '${body}'`,
|
|
77
|
+
{ encoding: 'utf-8' },
|
|
78
|
+
);
|
|
79
|
+
|
|
80
|
+
let parsed: { access_token?: string; error?: string };
|
|
81
|
+
try {
|
|
82
|
+
parsed = JSON.parse(response);
|
|
83
|
+
} catch {
|
|
84
|
+
throw new Error(`user-auth token endpoint returned non-JSON (${env}): ${response.slice(0, 200)}`);
|
|
85
|
+
}
|
|
86
|
+
if (!parsed.access_token) {
|
|
87
|
+
throw new Error(`user-auth token mint failed (${env}): ${response.slice(0, 200)}`);
|
|
88
|
+
}
|
|
89
|
+
tokenCache[env] = parsed.access_token;
|
|
90
|
+
return parsed.access_token;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// ───── Error envelope ───────────────────────────────────────────────────────
|
|
94
|
+
interface BillingErrorEnvelope {
|
|
95
|
+
error?: { code?: string; message?: string } | string;
|
|
96
|
+
message?: string;
|
|
97
|
+
code?: string;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function formatServiceError(status: number, statusText: string, body: string): string {
|
|
101
|
+
let parsed: BillingErrorEnvelope | null = null;
|
|
102
|
+
try { parsed = JSON.parse(body); } catch { /* non-JSON */ }
|
|
103
|
+
|
|
104
|
+
// Dominant Wave 1.5 envelope: flat { error: "CODE_STRING", message: "..." }
|
|
105
|
+
// emitted by billing's global error handler (app.ts:99-118) for ALL
|
|
106
|
+
// BillingError throws + validation errors + internal errors. Most inline
|
|
107
|
+
// route returns also use this shape (admin-products.ts:110,144,184-185,etc).
|
|
108
|
+
if (parsed && typeof parsed.error === 'string') {
|
|
109
|
+
return `❌ Error [${status}] ${parsed.error}: ${parsed.message ?? '(no message)'}`;
|
|
110
|
+
}
|
|
111
|
+
// Less-common nested envelope: { error: { code, message } } — used by a
|
|
112
|
+
// few inline 400/404 returns in admin-products.ts toggle-channel handler
|
|
113
|
+
// (lines 92-93, 100-101, 114-117). Possibly extends to other routes
|
|
114
|
+
// post-Wave-1.5 as standardization lands.
|
|
115
|
+
if (parsed && typeof parsed.error === 'object' && parsed.error !== null) {
|
|
116
|
+
const code = (parsed.error as { code?: string }).code ?? 'UNKNOWN';
|
|
117
|
+
const msg = (parsed.error as { message?: string }).message ?? '(no message)';
|
|
118
|
+
return `❌ Error [${status}] ${code}: ${msg}`;
|
|
119
|
+
}
|
|
120
|
+
// Non-envelope fallback (raw 502 from upstream LB, crashed handler before
|
|
121
|
+
// error middleware, plain-text body, etc.)
|
|
122
|
+
return `❌ Error [${status}] ${statusText}\n Response body (first 500 bytes): ${body.slice(0, 500)}`;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// ───── Public: callService / callBilling / callSkills ───────────────────────
|
|
126
|
+
export interface ServiceResponse<T> {
|
|
127
|
+
status: number;
|
|
128
|
+
body: T;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Authenticated call to an Optima service (billing or skills — same dev-skills
|
|
133
|
+
* M2M token works for both). Returns `{status, body}` on 2xx; throws Error with
|
|
134
|
+
* formatted message on non-2xx. Single retry on 5xx (no backoff — admin CLI).
|
|
135
|
+
*/
|
|
136
|
+
async function callService<T>(
|
|
137
|
+
baseUrl: string,
|
|
138
|
+
env: string,
|
|
139
|
+
method: 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE',
|
|
140
|
+
path: string,
|
|
141
|
+
body?: object,
|
|
142
|
+
): Promise<ServiceResponse<T>> {
|
|
143
|
+
const url = `${baseUrl}${path}`;
|
|
144
|
+
const token = getServiceToken(env);
|
|
145
|
+
|
|
146
|
+
const doFetch = async () => fetch(url, {
|
|
147
|
+
method,
|
|
148
|
+
headers: {
|
|
149
|
+
Authorization: `Bearer ${token}`,
|
|
150
|
+
'Content-Type': 'application/json',
|
|
151
|
+
},
|
|
152
|
+
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
let res = await doFetch();
|
|
156
|
+
if (res.status >= 500) {
|
|
157
|
+
res = await doFetch();
|
|
158
|
+
}
|
|
159
|
+
const text = await res.text();
|
|
160
|
+
if (!res.ok) {
|
|
161
|
+
throw new Error(formatServiceError(res.status, res.statusText, text));
|
|
162
|
+
}
|
|
163
|
+
let parsed: T;
|
|
164
|
+
try {
|
|
165
|
+
parsed = text ? (JSON.parse(text) as T) : (undefined as unknown as T);
|
|
166
|
+
} catch {
|
|
167
|
+
throw new Error(`Service returned non-JSON 2xx body: ${text.slice(0, 200)}`);
|
|
168
|
+
}
|
|
169
|
+
return { status: res.status, body: parsed };
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Kept as an alias for billing-side callers that reference the response type. */
|
|
173
|
+
export interface BillingResponse<T> extends ServiceResponse<T> {}
|
|
174
|
+
|
|
175
|
+
export async function callBilling<T = unknown>(
|
|
176
|
+
env: string,
|
|
177
|
+
method: 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE',
|
|
178
|
+
path: string,
|
|
179
|
+
body?: object,
|
|
180
|
+
): Promise<ServiceResponse<T>> {
|
|
181
|
+
return callService<T>(getBillingUrl(env), env, method, path, body);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export async function callSkills<T = unknown>(
|
|
185
|
+
env: string,
|
|
186
|
+
method: 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE',
|
|
187
|
+
path: string,
|
|
188
|
+
body?: object,
|
|
189
|
+
): Promise<ServiceResponse<T>> {
|
|
190
|
+
return callService<T>(getSkillsUrl(env), env, method, path, body);
|
|
191
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import * as readline from 'readline';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* On prod, print the resolved action and require typing "yes" to proceed.
|
|
5
|
+
* No-op on stage or when --yes was passed. Exits 1 if user declines.
|
|
6
|
+
*/
|
|
7
|
+
export async function confirmIfProd(
|
|
8
|
+
env: string,
|
|
9
|
+
actionDescription: string,
|
|
10
|
+
skipFlag: boolean,
|
|
11
|
+
): Promise<void> {
|
|
12
|
+
if (env !== 'prod' || skipFlag) return;
|
|
13
|
+
|
|
14
|
+
console.log(`\n⚠️ About to perform on PROD:\n${actionDescription}\n`);
|
|
15
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
16
|
+
const answer = await new Promise<string>((resolve) => {
|
|
17
|
+
rl.question('Type "yes" to confirm: ', (a) => { rl.close(); resolve(a.trim()); });
|
|
18
|
+
});
|
|
19
|
+
if (answer !== 'yes') {
|
|
20
|
+
console.error('❌ Aborted by user.');
|
|
21
|
+
process.exit(1);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { callBilling, validateEnv } from '../billing-http';
|
|
2
|
+
import { confirmIfProd } from '../confirm-prompt';
|
|
3
|
+
import { getInfisicalConfig, getInfisicalToken, resolveUserId } from '../db-utils';
|
|
4
|
+
|
|
5
|
+
interface GrantArgs {
|
|
6
|
+
email: string;
|
|
7
|
+
productKey: string;
|
|
8
|
+
justification: string;
|
|
9
|
+
yes: boolean;
|
|
10
|
+
env: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function parseArgs(argv: string[]): GrantArgs {
|
|
14
|
+
if (argv.length === 0 || argv[0] === '-h' || argv[0] === '--help') {
|
|
15
|
+
console.log(`Usage: optima-entitlement grant --email <user> --product-key <slug> --justification "..." [options]
|
|
16
|
+
|
|
17
|
+
Required:
|
|
18
|
+
--email <user-email> Resolved to userId via user-auth DB
|
|
19
|
+
--product-key <productKey>
|
|
20
|
+
--justification "..." Required by billing (400 otherwise); stored on entitlement.justification
|
|
21
|
+
|
|
22
|
+
Optional:
|
|
23
|
+
--yes Skip prod confirmation prompt (no-op on stage)
|
|
24
|
+
--env stage|prod (default: stage)
|
|
25
|
+
|
|
26
|
+
Hardcoded server-side: source=ADMIN_GRANT, priceCents=0, currency=USD, grantedBy=<clientId>.`);
|
|
27
|
+
process.exit(0);
|
|
28
|
+
}
|
|
29
|
+
const out: Partial<GrantArgs> = { env: 'stage', yes: false };
|
|
30
|
+
for (let i = 0; i < argv.length; i++) {
|
|
31
|
+
const a = argv[i];
|
|
32
|
+
const next = argv[i + 1];
|
|
33
|
+
switch (a) {
|
|
34
|
+
case '--email': out.email = next; i++; break;
|
|
35
|
+
case '--product-key': out.productKey = next; i++; break;
|
|
36
|
+
case '--justification': out.justification = next; i++; break;
|
|
37
|
+
case '--yes': out.yes = true; break;
|
|
38
|
+
case '--env': out.env = next; i++; break;
|
|
39
|
+
default: throw new Error(`Unknown arg: ${a}`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
if (!out.email) throw new Error('--email required');
|
|
43
|
+
if (!out.productKey) throw new Error('--product-key required');
|
|
44
|
+
if (!out.justification) throw new Error('--justification required (billing returns 400 otherwise)');
|
|
45
|
+
return out as GrantArgs;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export async function runGrant(argv: string[]): Promise<void> {
|
|
49
|
+
const args = parseArgs(argv);
|
|
50
|
+
validateEnv(args.env);
|
|
51
|
+
|
|
52
|
+
const cfg = getInfisicalConfig();
|
|
53
|
+
const token = getInfisicalToken(cfg);
|
|
54
|
+
const userId = await resolveUserId(args.email, args.env, cfg, token);
|
|
55
|
+
|
|
56
|
+
await confirmIfProd(
|
|
57
|
+
args.env,
|
|
58
|
+
`Action: GRANT product '${args.productKey}' to user ${args.email} (userId=${userId}) on ${args.env.toUpperCase()}\nJustification: ${args.justification}`,
|
|
59
|
+
args.yes,
|
|
60
|
+
);
|
|
61
|
+
|
|
62
|
+
console.log(`\n🎁 Granting ${args.productKey} to ${args.email}...`);
|
|
63
|
+
const res = await callBilling(args.env, 'POST', '/api/billing/admin/grant-entitlement', {
|
|
64
|
+
userId,
|
|
65
|
+
productKey: args.productKey,
|
|
66
|
+
justification: args.justification,
|
|
67
|
+
});
|
|
68
|
+
console.log(`✓ Granted entitlement (HTTP ${res.status}):`);
|
|
69
|
+
console.log(JSON.stringify(res.body, null, 2));
|
|
70
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { callBilling, validateEnv } from '../billing-http';
|
|
2
|
+
import { getInfisicalConfig, getInfisicalToken, resolveUserId } from '../db-utils';
|
|
3
|
+
|
|
4
|
+
interface ListArgs {
|
|
5
|
+
email: string;
|
|
6
|
+
env: string;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
function parseArgs(argv: string[]): ListArgs {
|
|
10
|
+
if (argv.length === 0 || argv[0] === '-h' || argv[0] === '--help') {
|
|
11
|
+
console.log(`Usage: optima-entitlement list --email <user-email> [options]
|
|
12
|
+
|
|
13
|
+
Required:
|
|
14
|
+
--email <user-email> Resolved to userId via user-auth DB
|
|
15
|
+
|
|
16
|
+
Optional:
|
|
17
|
+
--env stage|prod (default: stage)`);
|
|
18
|
+
process.exit(0);
|
|
19
|
+
}
|
|
20
|
+
const out: Partial<ListArgs> = { env: 'stage' };
|
|
21
|
+
for (let i = 0; i < argv.length; i++) {
|
|
22
|
+
const a = argv[i];
|
|
23
|
+
const next = argv[i + 1];
|
|
24
|
+
switch (a) {
|
|
25
|
+
case '--email': out.email = next; i++; break;
|
|
26
|
+
case '--env': out.env = next; i++; break;
|
|
27
|
+
default: throw new Error(`Unknown arg: ${a}`);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
if (!out.email) throw new Error('--email required');
|
|
31
|
+
return out as ListArgs;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
interface EntitlementRow {
|
|
35
|
+
id: string;
|
|
36
|
+
productKey: string;
|
|
37
|
+
status: string;
|
|
38
|
+
source: string;
|
|
39
|
+
purchasedAt: string;
|
|
40
|
+
refundedAt: string | null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export async function runList(argv: string[]): Promise<void> {
|
|
44
|
+
const args = parseArgs(argv);
|
|
45
|
+
validateEnv(args.env);
|
|
46
|
+
|
|
47
|
+
const cfg = getInfisicalConfig();
|
|
48
|
+
const token = getInfisicalToken(cfg);
|
|
49
|
+
const userId = await resolveUserId(args.email, args.env, cfg, token);
|
|
50
|
+
|
|
51
|
+
const res = await callBilling<{ entitlements: EntitlementRow[] }>(
|
|
52
|
+
args.env,
|
|
53
|
+
'GET',
|
|
54
|
+
`/api/billing/admin/entitlements?userId=${encodeURIComponent(userId)}`,
|
|
55
|
+
);
|
|
56
|
+
|
|
57
|
+
const rows = res.body.entitlements ?? [];
|
|
58
|
+
if (rows.length === 0) {
|
|
59
|
+
console.log(`(no entitlements for ${args.email} on ${args.env})`);
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
// Newest first per spec
|
|
63
|
+
rows.sort((a, b) => b.purchasedAt.localeCompare(a.purchasedAt));
|
|
64
|
+
console.log(`${rows.length} entitlement(s) for ${args.email}:\n`);
|
|
65
|
+
console.log('id'.padEnd(38) + ' | ' + 'productKey'.padEnd(32) + ' | ' + 'status'.padEnd(9) + ' | ' + 'source'.padEnd(12) + ' | purchasedAt | refundedAt');
|
|
66
|
+
console.log('-'.repeat(140));
|
|
67
|
+
for (const r of rows) {
|
|
68
|
+
console.log(
|
|
69
|
+
r.id.padEnd(38) + ' | ' +
|
|
70
|
+
r.productKey.padEnd(32) + ' | ' +
|
|
71
|
+
r.status.padEnd(9) + ' | ' +
|
|
72
|
+
r.source.padEnd(12) + ' | ' +
|
|
73
|
+
r.purchasedAt.padEnd(24) + ' | ' +
|
|
74
|
+
(r.refundedAt ?? ''),
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { callBilling, validateEnv } from '../billing-http';
|
|
2
|
+
import { confirmIfProd } from '../confirm-prompt';
|
|
3
|
+
import { getInfisicalConfig, getInfisicalToken, resolveUserId } from '../db-utils';
|
|
4
|
+
|
|
5
|
+
interface RevokeArgs {
|
|
6
|
+
email: string;
|
|
7
|
+
productKey: string;
|
|
8
|
+
reason: string;
|
|
9
|
+
yes: boolean;
|
|
10
|
+
env: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
interface EntitlementRow {
|
|
14
|
+
id: string;
|
|
15
|
+
productKey: string;
|
|
16
|
+
status: string;
|
|
17
|
+
source: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function parseArgs(argv: string[]): RevokeArgs {
|
|
21
|
+
if (argv.length === 0 || argv[0] === '-h' || argv[0] === '--help') {
|
|
22
|
+
console.log(`Usage: optima-entitlement revoke --email <user> --product-key <slug> --reason "..." [options]
|
|
23
|
+
|
|
24
|
+
Required:
|
|
25
|
+
--email <user-email> Resolved to userId via user-auth DB
|
|
26
|
+
--product-key <productKey>
|
|
27
|
+
--reason "..." Required by billing (400 otherwise); stored on entitlement.refundReason
|
|
28
|
+
|
|
29
|
+
Optional:
|
|
30
|
+
--yes Skip prod confirmation prompt (no-op on stage)
|
|
31
|
+
--env stage|prod (default: stage)
|
|
32
|
+
|
|
33
|
+
Refuses non-ADMIN_GRANT sources (PAYMENT, PARTNER) with source-specific
|
|
34
|
+
error pointing to the right reversal flow.`);
|
|
35
|
+
process.exit(0);
|
|
36
|
+
}
|
|
37
|
+
const out: Partial<RevokeArgs> = { env: 'stage', yes: false };
|
|
38
|
+
for (let i = 0; i < argv.length; i++) {
|
|
39
|
+
const a = argv[i];
|
|
40
|
+
const next = argv[i + 1];
|
|
41
|
+
switch (a) {
|
|
42
|
+
case '--email': out.email = next; i++; break;
|
|
43
|
+
case '--product-key': out.productKey = next; i++; break;
|
|
44
|
+
case '--reason': out.reason = next; i++; break;
|
|
45
|
+
case '--yes': out.yes = true; break;
|
|
46
|
+
case '--env': out.env = next; i++; break;
|
|
47
|
+
default: throw new Error(`Unknown arg: ${a}`);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
if (!out.email) throw new Error('--email required');
|
|
51
|
+
if (!out.productKey) throw new Error('--product-key required');
|
|
52
|
+
if (!out.reason) throw new Error('--reason required (billing returns 400 otherwise)');
|
|
53
|
+
return out as RevokeArgs;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const PAYMENT_REFUSAL = `refusing to revoke a PAYMENT-source entitlement via CLI; this would leave the customer charged but unentitled. Use the Stripe refund flow which calls Stripe refund API + records refundedAmountCents + emits webhook. Manual psql is the escape hatch if absolutely necessary.`;
|
|
57
|
+
|
|
58
|
+
const PARTNER_REFUSAL = `refusing to revoke a PARTNER-source entitlement via CLI; PARTNER grants are issued out-of-band and must be reversed via the partner contract / process that issued them. Manual psql is the escape hatch if absolutely necessary.`;
|
|
59
|
+
|
|
60
|
+
export async function runRevoke(argv: string[]): Promise<void> {
|
|
61
|
+
const args = parseArgs(argv);
|
|
62
|
+
validateEnv(args.env);
|
|
63
|
+
|
|
64
|
+
const cfg = getInfisicalConfig();
|
|
65
|
+
const token = getInfisicalToken(cfg);
|
|
66
|
+
const userId = await resolveUserId(args.email, args.env, cfg, token);
|
|
67
|
+
|
|
68
|
+
// Step 1: Fetch user's entitlements
|
|
69
|
+
const listRes = await callBilling<{ entitlements: EntitlementRow[] }>(
|
|
70
|
+
args.env,
|
|
71
|
+
'GET',
|
|
72
|
+
`/api/billing/admin/entitlements?userId=${encodeURIComponent(userId)}`,
|
|
73
|
+
);
|
|
74
|
+
const all = listRes.body.entitlements ?? [];
|
|
75
|
+
|
|
76
|
+
// Step 2: Filter for ACTIVE + matching productKey
|
|
77
|
+
const matches = all.filter((e) => e.status === 'ACTIVE' && e.productKey === args.productKey);
|
|
78
|
+
|
|
79
|
+
// Step 3: Validate count (partial unique index enforces ≤1 ACTIVE)
|
|
80
|
+
if (matches.length === 0) {
|
|
81
|
+
throw new Error(`no active entitlement for (user=${args.email}, product=${args.productKey}) on ${args.env}`);
|
|
82
|
+
}
|
|
83
|
+
if (matches.length > 1) {
|
|
84
|
+
throw new Error(`unexpected: ${matches.length} ACTIVE entitlements for (user, product) — partial unique constraint should prevent this. Inspect with: optima-entitlement list --email ${args.email}`);
|
|
85
|
+
}
|
|
86
|
+
const target = matches[0];
|
|
87
|
+
|
|
88
|
+
// Step 4: Validate source
|
|
89
|
+
if (target.source === 'PAYMENT') throw new Error(PAYMENT_REFUSAL);
|
|
90
|
+
if (target.source === 'PARTNER') throw new Error(PARTNER_REFUSAL);
|
|
91
|
+
if (target.source !== 'ADMIN_GRANT') throw new Error(`unknown entitlement source: ${target.source}`);
|
|
92
|
+
|
|
93
|
+
await confirmIfProd(
|
|
94
|
+
args.env,
|
|
95
|
+
`Action: REVOKE entitlement ${target.id} (productKey=${target.productKey}) for user ${args.email} (userId=${userId}) on ${args.env.toUpperCase()}\nReason: ${args.reason}`,
|
|
96
|
+
args.yes,
|
|
97
|
+
);
|
|
98
|
+
|
|
99
|
+
// Step 5: Refund
|
|
100
|
+
// refundAmountCents=0 is always correct for ADMIN_GRANT (priceCents=0,
|
|
101
|
+
// no upstream charge). Pass explicitly so billing's auto-compute
|
|
102
|
+
// (which requires refundWindowDays on the Product) doesn't 400 with
|
|
103
|
+
// MANUAL_REFUND_AMOUNT_REQUIRED for products that lack a refund policy.
|
|
104
|
+
// PAYMENT/PARTNER sources are already refused in step 4 above, so
|
|
105
|
+
// this branch only ever runs for ADMIN_GRANT (priceCents=0) — Stripe
|
|
106
|
+
// refund path in billing (admin-products.ts:296-307) is gated on
|
|
107
|
+
// source=PAYMENT and won't trigger here.
|
|
108
|
+
console.log(`\n♻️ Revoking entitlement ${target.id} for ${args.email}...`);
|
|
109
|
+
const res = await callBilling(args.env, 'POST', '/api/billing/admin/refund-entitlement', {
|
|
110
|
+
entitlementId: target.id,
|
|
111
|
+
refundReason: args.reason,
|
|
112
|
+
refundAmountCents: 0,
|
|
113
|
+
});
|
|
114
|
+
console.log(`✓ Revoked entitlement (HTTP ${res.status}):`);
|
|
115
|
+
console.log(JSON.stringify(res.body, null, 2));
|
|
116
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { runGrant } from './entitlement/grant';
|
|
4
|
+
import { runList } from './entitlement/list';
|
|
5
|
+
import { runRevoke } from './entitlement/revoke';
|
|
6
|
+
|
|
7
|
+
function printHelp() {
|
|
8
|
+
console.log(`Usage: optima-entitlement <subcommand> [options]
|
|
9
|
+
|
|
10
|
+
Subcommands:
|
|
11
|
+
grant Admin-grant a product entitlement to a user
|
|
12
|
+
revoke Revoke an admin-granted entitlement (refuses PAYMENT / PARTNER sources)
|
|
13
|
+
list List a user's entitlements, newest first
|
|
14
|
+
|
|
15
|
+
Run 'optima-entitlement <subcommand> --help' for subcommand-specific options.`);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
async function main() {
|
|
19
|
+
const [, , subcommand, ...rest] = process.argv;
|
|
20
|
+
if (!subcommand || subcommand === '-h' || subcommand === '--help') { printHelp(); process.exit(0); }
|
|
21
|
+
switch (subcommand) {
|
|
22
|
+
case 'list': await runList(rest); break;
|
|
23
|
+
case 'grant': await runGrant(rest); break;
|
|
24
|
+
case 'revoke': await runRevoke(rest); break;
|
|
25
|
+
default:
|
|
26
|
+
console.error(`Unknown subcommand: ${subcommand}`);
|
|
27
|
+
printHelp();
|
|
28
|
+
process.exit(1);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
main().catch((err) => { console.error(err.message); process.exit(1); });
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { execSync } from 'child_process';
|
|
2
|
+
import { getInfisicalConfig, getInfisicalToken, InfisicalConfig } from './db-utils';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Fetch a single secret value from Infisical given env + path + name.
|
|
6
|
+
*
|
|
7
|
+
* env mapping: 'stage' → Infisical env slug 'staging'; 'prod' → 'prod'
|
|
8
|
+
* (matches dev-skills convention documented at
|
|
9
|
+
* ~/.claude/projects/-mnt-d-work-projects-optima/memory/optima_infisical_env_naming.md).
|
|
10
|
+
*
|
|
11
|
+
* Returns the raw secretValue string. Throws if the secret is missing.
|
|
12
|
+
*/
|
|
13
|
+
export function fetchInfisicalSecret(
|
|
14
|
+
env: string,
|
|
15
|
+
secretPath: string,
|
|
16
|
+
secretName: string,
|
|
17
|
+
config?: InfisicalConfig,
|
|
18
|
+
token?: string,
|
|
19
|
+
): string {
|
|
20
|
+
const cfg = config ?? getInfisicalConfig();
|
|
21
|
+
const tok = token ?? getInfisicalToken(cfg);
|
|
22
|
+
const envSlug = env === 'stage' ? 'staging' : env;
|
|
23
|
+
const encodedPath = encodeURIComponent(secretPath);
|
|
24
|
+
const encodedName = encodeURIComponent(secretName);
|
|
25
|
+
|
|
26
|
+
const response = execSync(
|
|
27
|
+
`curl -s "${cfg.url}/api/v3/secrets/raw/${encodedName}?workspaceId=${cfg.projectId}&environment=${envSlug}&secretPath=${encodedPath}" -H "Authorization: Bearer ${tok}"`,
|
|
28
|
+
{ encoding: 'utf-8' },
|
|
29
|
+
);
|
|
30
|
+
|
|
31
|
+
let parsed: { secret?: { secretValue?: string }; message?: string };
|
|
32
|
+
try {
|
|
33
|
+
parsed = JSON.parse(response);
|
|
34
|
+
} catch {
|
|
35
|
+
throw new Error(`Infisical raw secret fetch returned non-JSON for ${secretPath}/${secretName} (${envSlug}): ${response.slice(0, 200)}`);
|
|
36
|
+
}
|
|
37
|
+
if (!parsed.secret?.secretValue) {
|
|
38
|
+
throw new Error(`Infisical secret not found: env=${envSlug} path=${secretPath} name=${secretName} (response: ${response.slice(0, 200)})`);
|
|
39
|
+
}
|
|
40
|
+
return parsed.secret.secretValue;
|
|
41
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { callSkills, validateEnv } from '../billing-http';
|
|
2
|
+
import { confirmIfProd } from '../confirm-prompt';
|
|
3
|
+
|
|
4
|
+
interface SetDefaultArgs {
|
|
5
|
+
slug: string;
|
|
6
|
+
default: boolean;
|
|
7
|
+
yes: boolean;
|
|
8
|
+
env: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function parseArgs(argv: string[]): SetDefaultArgs {
|
|
12
|
+
if (argv.length === 0 || argv[0] === '-h' || argv[0] === '--help') {
|
|
13
|
+
console.log(`Usage: optima-plugin set-default --slug <slug> --default true|false [options]
|
|
14
|
+
|
|
15
|
+
Required:
|
|
16
|
+
--slug <slug>
|
|
17
|
+
--default true|false Sets Plugin.defaultForUser
|
|
18
|
+
|
|
19
|
+
Optional:
|
|
20
|
+
--yes Skip prod confirmation prompt (no-op on stage)
|
|
21
|
+
--env stage|prod (default: stage)
|
|
22
|
+
|
|
23
|
+
Note: no skill-sync broadcast — changes what NEW user syncs receive; does not
|
|
24
|
+
retroactively add/remove the plugin for existing users until their next sync.`);
|
|
25
|
+
process.exit(0);
|
|
26
|
+
}
|
|
27
|
+
const out: Partial<SetDefaultArgs> = { env: 'stage', yes: false };
|
|
28
|
+
for (let i = 0; i < argv.length; i++) {
|
|
29
|
+
const a = argv[i];
|
|
30
|
+
const next = argv[i + 1];
|
|
31
|
+
switch (a) {
|
|
32
|
+
case '--slug': out.slug = next; i++; break;
|
|
33
|
+
case '--default':
|
|
34
|
+
if (next !== 'true' && next !== 'false') throw new Error('--default must be true or false');
|
|
35
|
+
out.default = next === 'true'; i++; break;
|
|
36
|
+
case '--yes': out.yes = true; break;
|
|
37
|
+
case '--env': out.env = next; i++; break;
|
|
38
|
+
default: throw new Error(`Unknown arg: ${a}`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
if (!out.slug) throw new Error('--slug required');
|
|
42
|
+
if (out.default === undefined) throw new Error('--default required (true|false)');
|
|
43
|
+
return out as SetDefaultArgs;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export async function runSetDefault(argv: string[]): Promise<void> {
|
|
47
|
+
const args = parseArgs(argv);
|
|
48
|
+
validateEnv(args.env);
|
|
49
|
+
|
|
50
|
+
await confirmIfProd(
|
|
51
|
+
args.env,
|
|
52
|
+
`Action: set defaultForUser=${args.default} on plugin '${args.slug}' (${args.env.toUpperCase()})`,
|
|
53
|
+
args.yes,
|
|
54
|
+
);
|
|
55
|
+
|
|
56
|
+
console.log(`\n🔧 Setting defaultForUser=${args.default} on ${args.slug} (${args.env.toUpperCase()})...`);
|
|
57
|
+
const res = await callSkills(
|
|
58
|
+
args.env,
|
|
59
|
+
'PATCH',
|
|
60
|
+
`/api/admin/plugins/${encodeURIComponent(args.slug)}`,
|
|
61
|
+
{ defaultForUser: args.default },
|
|
62
|
+
);
|
|
63
|
+
console.log(`✓ Updated plugin (HTTP ${res.status}):`);
|
|
64
|
+
console.log(JSON.stringify(res.body, null, 2));
|
|
65
|
+
}
|