-
Notifications
You must be signed in to change notification settings - Fork 0
feat(cli): add buy command #59
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
fa6ab3e
626c5d9
718df90
66bba25
002d41d
cbae349
6979ec7
54c928e
3c3f741
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| 'use strict' | ||
|
|
||
| const { randomUUID } = require('crypto') | ||
| const { writeConfig, configPathDisplay } = require('./config') | ||
| const { authorize, fetchJson } = require('./dashboard') | ||
| const select = require('./select') | ||
| const openUrl = require('./open') | ||
| const { gray } = require('./style') | ||
|
|
||
| const TIMEOUT_MS = 15 * 60 * 1000 | ||
| const POLL_MS = 2000 | ||
|
|
||
| const request = async (path, options) => { | ||
| const { res, body } = await fetchJson(path, options) | ||
| if (!res.ok) { | ||
| throw new Error(body.error || `Dashboard request failed (${res.status})`) | ||
| } | ||
| return body | ||
| } | ||
|
|
||
| const money = (amount, currency) => | ||
| new Intl.NumberFormat(undefined, { | ||
| style: 'currency', | ||
| currency, | ||
| maximumFractionDigits: amount % 100 === 0 ? 0 : 2 | ||
| }).format(amount / 100) | ||
|
|
||
| const asChoice = plan => ({ | ||
| name: `${plan.limit.toLocaleString()} req`, | ||
| hint: `${money(plan.price, plan.currency)}/mo`, | ||
| value: plan.id | ||
| }) | ||
|
|
||
| const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)) | ||
|
|
||
| const pickPlan = async (plans, planId) => { | ||
| if (planId) { | ||
| if (!plans.some(plan => plan.id === planId)) { | ||
| throw new Error(`Unknown plan \`${planId}\``) | ||
| } | ||
| return planId | ||
| } | ||
| const { value } = await select({ | ||
| message: 'Which plan?', | ||
| choices: plans.map(asChoice) | ||
| }) | ||
| return value | ||
| } | ||
|
|
||
| const waitForPayment = async sessionId => { | ||
| const started = Date.now() | ||
| const path = `/api/v1/checkout/sessions/${encodeURIComponent(sessionId)}` | ||
| for (;;) { | ||
| const body = await request(path) | ||
| if (body.state === 'ready') return body | ||
| if (body.state === 'expired') throw new Error('Checkout expired') | ||
| if (Date.now() - started > TIMEOUT_MS) { | ||
| throw new Error('Timed out waiting for payment') | ||
| } | ||
| await sleep(POLL_MS) | ||
| } | ||
| } | ||
|
|
||
| const buy = async ({ plan: planId } = {}) => { | ||
| const { plans } = await request('/api/v1/plans') | ||
| if (!plans?.length) throw new Error('No plans available') | ||
|
|
||
| planId = await pickPlan(plans, planId) | ||
| const { token, sessionId, checkoutUrl } = await authorize({ plan: planId }) | ||
|
|
||
| let session | ||
| if (sessionId != null && checkoutUrl != null) { | ||
| session = { sessionId, checkoutUrl } | ||
| } else { | ||
| session = await request('/api/v1/checkout/sessions', { | ||
| method: 'POST', | ||
| headers: { | ||
| 'content-type': 'application/json', | ||
| 'idempotency-key': randomUUID(), | ||
| authorization: `Bearer ${token}` | ||
| }, | ||
| body: JSON.stringify({ planId, label: 'default' }) | ||
| }) | ||
| process.stderr.write(`Opening ${session.checkoutUrl}\n\n`) | ||
| if (process.stderr.isTTY) openUrl(session.checkoutUrl) | ||
| } | ||
|
|
||
| process.stderr.write('Waiting for payment…\n') | ||
| const { apiKey } = await waitForPayment(session.sessionId) | ||
| if (typeof apiKey !== 'string' || apiKey === '') { | ||
| process.stderr.write( | ||
| `\n${gray('Paid.')} Run \`microlink login\` to save your API key.\n` | ||
| ) | ||
| return | ||
| } | ||
| writeConfig({ apiKey }) | ||
| process.stdout.write(`${apiKey}\n`) | ||
| process.stderr.write( | ||
| `\n${gray('Saved')} ${gray(`to ${configPathDisplay()}`)}\n` | ||
| ) | ||
| } | ||
|
|
||
| module.exports = buy |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| 'use strict' | ||
|
|
||
| const debug = require('debug-logfmt')('microlink') | ||
| const { randomBytes } = require('crypto') | ||
| const http = require('http') | ||
| const openUrl = require('./open') | ||
|
|
||
| const TIMEOUT_MS = 5 * 60 * 1000 | ||
| const CLOSE_MS = 2000 | ||
|
|
||
| const dashboardUrl = () => | ||
| process.env.MICROLINK_DASHBOARD_URL || 'https://dashboard.microlink.io' | ||
|
|
||
| const debugResponse = (method, path, status, body) => { | ||
| const fields = { method, path, status } | ||
| for (const [key, value] of Object.entries(body || {})) { | ||
| fields[key] = | ||
| value != null && typeof value === 'object' ? JSON.stringify(value) : value | ||
| } | ||
| debug(fields) | ||
| } | ||
|
|
||
| const fetchJson = async (path, options = {}) => { | ||
| const method = options.method || 'GET' | ||
| const res = await fetch(new URL(path, dashboardUrl()), options) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔒 Security & Privacy | 🛡️ Analyzed with Security Review | 🟠 Major | ⚡ Quick win 🧩 Analysis chain🏁 Script executed: sed -n '1,125p' packages/core/bin/dashboard.js
sed -n '1,130p' packages/core/bin/buy.js
sed -n '1,90p' packages/core/bin/login.js
rg -n 'MICROLINK_DASHBOARD_URL|fetchJson\(' packages/core packages/mcp README.md --glob '!**/node_modules/**'Repository: microlinkhq/microlink Length of output: 8055 🏁 Script executed: sed -n '420,485p' packages/core/test/cli.mjs
sed -n '1,120p' packages/mcp/src/dashboard-client.js
rg -n -C 3 'MICROLINK_DASHBOARD_URL|dashboard\.microlink\.io' README.md packages/core packages/mcp --glob '!**/node_modules/**'Repository: microlinkhq/microlink Length of output: 8088 Security Misconfiguration Reachability: Internal Reject non-loopback HTTP dashboard URLs before sending bearer tokens.
🤖 Prompt for AI Agents |
||
| const body = await res.json().catch(() => ({})) | ||
| debugResponse(method, path, res.status, body) | ||
| return { res, body } | ||
| } | ||
|
|
||
| const end = (res, status) => { | ||
| res.writeHead(status) | ||
| res.end() | ||
| } | ||
|
|
||
| const listen = state => | ||
| new Promise((resolve, reject) => { | ||
| let settle | ||
| const handshake = new Promise((resolve, reject) => { | ||
| settle = { resolve, reject } | ||
| }) | ||
|
|
||
| const cors = res => { | ||
| res.setHeader('Access-Control-Allow-Origin', '*') | ||
| res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS') | ||
| res.setHeader('Access-Control-Allow-Headers', 'content-type') | ||
| res.setHeader('Access-Control-Allow-Private-Network', 'true') | ||
| } | ||
|
|
||
| const server = http.createServer((req, res) => { | ||
| cors(res) | ||
| if (req.method === 'OPTIONS') return end(res, 204) | ||
| if (req.method !== 'POST') return end(res, 405) | ||
| const chunks = [] | ||
| req.on('data', chunk => chunks.push(chunk)) | ||
| req.on('end', () => { | ||
| try { | ||
| const body = JSON.parse(Buffer.concat(chunks).toString()) | ||
| if (body.state !== state || typeof body.token !== 'string') { | ||
| return end(res, 400) | ||
| } | ||
| end(res, 204) | ||
| clearTimeout(timer) | ||
| settle.resolve(body) | ||
| } catch { | ||
| end(res, 400) | ||
| } | ||
| }) | ||
| }) | ||
|
|
||
| const close = () => { | ||
| clearTimeout(timer) | ||
| server.close() | ||
| } | ||
|
|
||
| const timer = setTimeout(() => { | ||
| close() | ||
| settle.reject(new Error('Timed out waiting for dashboard authorization')) | ||
| }, TIMEOUT_MS) | ||
|
|
||
| server.listen(0, '127.0.0.1', () => { | ||
| resolve({ port: server.address().port, handshake, close }) | ||
| }) | ||
| server.on('error', reject) | ||
| }) | ||
|
|
||
| const authorize = async (query = {}) => { | ||
| if (process.env.MICROLINK_CONNECT_TOKEN) { | ||
| return { token: process.env.MICROLINK_CONNECT_TOKEN } | ||
| } | ||
|
|
||
| const state = randomBytes(16).toString('hex') | ||
| const { port, handshake, close } = await listen(state) | ||
| const url = new URL('/connect', dashboardUrl()) | ||
| url.searchParams.set('port', String(port)) | ||
| url.searchParams.set('state', state) | ||
| for (const [key, value] of Object.entries(query)) { | ||
| if (value != null && value !== '') url.searchParams.set(key, String(value)) | ||
| } | ||
| process.stderr.write(`Opening ${url}\n\n`) | ||
| openUrl(url.toString()) | ||
| try { | ||
| return await handshake | ||
| } finally { | ||
| setTimeout(close, CLOSE_MS).unref() | ||
| } | ||
| } | ||
|
|
||
| module.exports = { dashboardUrl, authorize, fetchJson } | ||
Uh oh!
There was an error while loading. Please reload this page.