From e7b2c871abb6303b94872e9e1a66dd8f8c4d9d76 Mon Sep 17 00:00:00 2001 From: Anthony Ettinger Date: Mon, 30 Nov 2026 14:40:41 +0000 Subject: [PATCH 1/4] cloud: hosted sk33p API + remote MCP with free tier and Pro via CoinPay sk33p.pwa.pit.world. Bun + Hono in front of the release binary: every call runs a fresh 'sk33p mcp' under prlimit in a scratch dir. - /api/v1/{eval,read,write,sheets,convert} (JSON base64 files, or raw upload for convert), /api/v1/{keys,me,upgrade}, remote MCP at /mcp. - Plans per UTC day: no key 10 calls, free key 100 (2 MB), Pro 10,000 (25 MB) at $9 per 30 days; over the limit is a 402 with the next step. - Pro = CoinPay hosted checkout (any coin or PayPal); signed webhook at /hooks/coinpay settles once and extends Pro. - Pages: home with live formula demo + pricing, /docs (+ /docs.md), /key, /upgrade, llms.txt, webring descriptor, webmcp embed, footers. - Docker: ubuntu 24.04 (release glibc), non-root, read-only, HEALTHCHECK. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 4 + cloud/.dockerignore | 5 + cloud/Dockerfile | 25 +++ cloud/bun.lock | 209 +++++++++++++++++++ cloud/compose.yml | 22 ++ cloud/package.json | 15 ++ cloud/src/app.ts | 445 +++++++++++++++++++++++++++++++++++++++++ cloud/src/engine.ts | 100 +++++++++ cloud/src/main.ts | 24 +++ cloud/src/page.ts | 303 ++++++++++++++++++++++++++++ cloud/src/store.ts | 101 ++++++++++ cloud/test/app.test.ts | 167 ++++++++++++++++ 12 files changed, 1420 insertions(+) create mode 100644 cloud/.dockerignore create mode 100644 cloud/Dockerfile create mode 100644 cloud/bun.lock create mode 100644 cloud/compose.yml create mode 100644 cloud/package.json create mode 100644 cloud/src/app.ts create mode 100644 cloud/src/engine.ts create mode 100644 cloud/src/main.ts create mode 100644 cloud/src/page.ts create mode 100644 cloud/src/store.ts create mode 100644 cloud/test/app.test.ts diff --git a/.gitignore b/.gitignore index 2f7896d..6b829d9 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,5 @@ target/ +cloud/node_modules/ +cloud/app.env +cloud/*.db +cloud/*.db-* diff --git a/cloud/.dockerignore b/cloud/.dockerignore new file mode 100644 index 0000000..4b84477 --- /dev/null +++ b/cloud/.dockerignore @@ -0,0 +1,5 @@ +node_modules +test +app.env +*.db +*.db-* diff --git a/cloud/Dockerfile b/cloud/Dockerfile new file mode 100644 index 0000000..96577e3 --- /dev/null +++ b/cloud/Dockerfile @@ -0,0 +1,25 @@ +# sk33p cloud: Bun + Hono in front of the sk33p release binary. +# ubuntu:24.04 because the release binary is built on ubuntu-latest (glibc 2.39). +FROM oven/bun:1.4.4 AS bun + +FROM ubuntu:24.04 +ARG SK33P_VERSION=latest +RUN apt-get update \ + && apt-get install -y --no-install-recommends ca-certificates curl util-linux zlib1g libstdc++6 \ + && rm -rf /var/lib/apt/lists/* +COPY --from=bun /usr/local/bin/bun /usr/local/bin/bun +RUN set -eu; \ + if [ "$SK33P_VERSION" = latest ]; then url=https://github.com/profullstack/sk33p/releases/latest/download/sk33p-linux-x86_64.tar.gz; \ + else url=https://github.com/profullstack/sk33p/releases/download/$SK33P_VERSION/sk33p-linux-x86_64.tar.gz; fi; \ + curl -fsSL "$url" | tar -xz -C /usr/local/bin sk33p && chmod 755 /usr/local/bin/sk33p && /usr/local/bin/sk33p --version +WORKDIR /app +COPY package.json bun.lock ./ +RUN bun install --frozen-lockfile --production +COPY src ./src +# Checkouts can carry owner-only modes; the app runs as a non-root user. +RUN chmod -R a+rX /app && useradd --system --uid 10033 --home /data sk33p && mkdir -p /data && chown sk33p /data +USER sk33p +ENV PORT=8811 HOST=0.0.0.0 DATA_DIR=/data SK33P_BIN=/usr/local/bin/sk33p NODE_ENV=production +EXPOSE 8811 +HEALTHCHECK --interval=30s --timeout=5s --retries=3 CMD curl -fsS http://127.0.0.1:8811/healthz || exit 1 +CMD ["bun", "src/main.ts"] diff --git a/cloud/bun.lock b/cloud/bun.lock new file mode 100644 index 0000000..dbc6ff3 --- /dev/null +++ b/cloud/bun.lock @@ -0,0 +1,209 @@ +{ + "lockfileVersion": 2, + "configVersion": 1, + "workspaces": { + "": { + "name": "sk33p-cloud", + "dependencies": { + "@profullstack/coinpay-onboard": "^0.5.1", + "@profullstack/footer": "^0.7.2", + "hono": "^4.13.23", + }, + }, + }, + "packages": { + "@hono/node-server": ["@hono/node-server@2.1.11", "", { "peerDependencies": { "hono": "^4 || ^5.0.0-0" } }, "sha512-KzKz9vl4vvr1vgLHamj+g5uonbrj5NwAdO3yzOS6cd2HjALVeOgTgeZOyAzNxejbkfOOPIcvuf/Tg8l1pEFLog=="], + + "@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.32.2", "", { "dependencies": { "@hono/node-server": "^1.19.9 || ^2.0.5", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-SWsVtH/0vULSQStoZ6xxH2K09Li8fXYTMC64ZeogCdpZ3XSi1eCPOByV1OpuJxuI3OcmHhosDWYyii07tpPsLw=="], + + "@profullstack/coinpay-onboard": ["@profullstack/coinpay-onboard@0.5.1", "", { "dependencies": { "@modelcontextprotocol/sdk": "^1.32.2", "zod": "^4.6.7" }, "bin": { "coinpay-onboard": "bin/coinpay-onboard" } }, "sha512-vuM/1vYvkXP2E/tBcTBZ8JY4K49qtSPPY1N9XRQvIlcy0Sezr+spOf6vYBkRPhasKcFqda44MRLgxPseG9Kvdg=="], + + "@profullstack/footer": ["@profullstack/footer@0.7.2", "", { "peerDependencies": { "react": ">=18" }, "optionalPeers": ["react"], "bin": { "profullstack-footer": "bin/profullstack-footer.js" } }, "sha512-2Va4LEsVM7PJEGkiNaSn//Zbp3u/EP1jhJff0Q8WfhKZJieUxqXPZZGv0R3qQjy4qiFMNYQATuNXM4ZXNXsVpA=="], + + "accepts": ["accepts@2.0.0", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="], + + "ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="], + + "ajv-formats": ["ajv-formats@3.0.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="], + + "body-parser": ["body-parser@2.4.0", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^2.1.0", "debug": "^4.4.3", "http-errors": "^2.0.1", "iconv-lite": "^0.7.3", "on-finished": "^2.4.1", "qs": "^6.16.1", "raw-body": "^3.0.2", "type-is": "^2.1.0" } }, "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ=="], + + "bytes": ["bytes@3.1.2", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="], + + "call-bind-apply-helpers": ["call-bind-apply-helpers@1.0.2", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="], + + "call-bound": ["call-bound@1.0.4", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "get-intrinsic": "^1.3.0" } }, "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg=="], + + "content-disposition": ["content-disposition@2.0.1", "", {}, "sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog=="], + + "content-type": ["content-type@1.0.5", "", {}, "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA=="], + + "cookie": ["cookie@0.7.2", "", {}, "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w=="], + + "cookie-signature": ["cookie-signature@1.2.2", "", {}, "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg=="], + + "cors": ["cors@2.8.6", "", { "dependencies": { "object-assign": "^4", "vary": "^1" } }, "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw=="], + + "cross-spawn": ["cross-spawn@7.1.2", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-8BPK2r+sKWC8sDinRwLwrFMq2lXTBBwzYYEB9LiCznfMurOi4FOvQflq3XOLGG+HPdMSVpe+k/s96+AtDEOgPg=="], + + "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" }, "peerDependencies": { "supports-color": "*" }, "optionalPeers": ["supports-color"] }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], + + "depd": ["depd@2.0.0", "", {}, "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="], + + "dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="], + + "ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="], + + "encodeurl": ["encodeurl@2.0.3", "", {}, "sha512-mIteYONiEfc4xWf2F1WXovh1c8npzS00vNeiUPdwFF+QlVJni+gNvpQltLMQhob8rew/bWWc/bGTuUr0EUGt0w=="], + + "es-define-property": ["es-define-property@1.0.1", "", {}, "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="], + + "es-errors": ["es-errors@1.3.0", "", {}, "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="], + + "es-object-atoms": ["es-object-atoms@1.1.2", "", { "dependencies": { "es-errors": "^1.3.0" } }, "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw=="], + + "escape-html": ["escape-html@1.0.3", "", {}, "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow=="], + + "etag": ["etag@1.8.1", "", {}, "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg=="], + + "eventsource": ["eventsource@3.0.7", "", { "dependencies": { "eventsource-parser": "^3.0.1" } }, "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA=="], + + "eventsource-parser": ["eventsource-parser@3.1.1", "", {}, "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ=="], + + "express": ["express@5.3.0", "", { "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.3.0", "content-disposition": "^2.0.1", "content-type": "^2.0.0", "cookie": "^0.7.1", "cookie-signature": "^1.2.1", "debug": "^4.4.0", "depd": "^2.0.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "finalhandler": "^2.1.0", "fresh": "^2.0.0", "http-errors": "^2.0.0", "merge-descriptors": "^2.0.0", "mime-types": "^3.0.0", "on-finished": "^2.4.1", "once": "^1.4.0", "parseurl": "^1.3.3", "proxy-addr": "^2.0.8", "qs": "^6.16.0", "range-parser": "^1.2.1", "router": "^2.2.0", "send": "^1.1.0", "serve-static": "^2.2.0", "statuses": "^2.0.1", "type-is": "^2.1.0", "vary": "^1.1.2" } }, "sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g=="], + + "express-rate-limit": ["express-rate-limit@8.7.5", "", { "dependencies": { "debug": "^4.4.3", "ip-address": "^10.2.0" }, "peerDependencies": { "express": ">= 4.11" } }, "sha512-wi+v38cx2EqD0JnhE/e74o5tFqKWUOAPFJIgyEiqJ8v2MNpoOAA3kI2hXYOI+YM+HE5yqbdAlVxm2GqOIeYOgA=="], + + "fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="], + + "fast-uri": ["fast-uri@3.1.9", "", {}, "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ=="], + + "finalhandler": ["finalhandler@2.1.1", "", { "dependencies": { "debug": "^4.4.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "on-finished": "^2.4.1", "parseurl": "^1.3.3", "statuses": "^2.0.1" } }, "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA=="], + + "forwarded": ["forwarded@0.2.0", "", {}, "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow=="], + + "fresh": ["fresh@2.0.0", "", {}, "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A=="], + + "function-bind": ["function-bind@1.1.2", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="], + + "get-intrinsic": ["get-intrinsic@1.3.0", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="], + + "get-proto": ["get-proto@1.0.1", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="], + + "gopd": ["gopd@1.2.0", "", {}, "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="], + + "has-symbols": ["has-symbols@1.1.0", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="], + + "hasown": ["hasown@2.0.4", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A=="], + + "hono": ["hono@4.13.23", "", {}, "sha512-OS90dj7dcsftEEWCOef8jRbnHE5lbrOq0hNRqjSyPsOnaGZvvfof1KS05hQNb4kUOCfDq1mG3PmHoX37DMnHQg=="], + + "http-errors": ["http-errors@2.0.1", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="], + + "iconv-lite": ["iconv-lite@0.7.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ=="], + + "inherits": ["inherits@2.0.4", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="], + + "ip-address": ["ip-address@10.7.7", "", {}, "sha512-He15rAs4jip5AEAz7XM9L+S6Y8LBMIDj6YewbYuJfmDnOCKWb+3TLOGnHFBTAIW7wpm5ohtZ+Xyo5PEaG+O2vQ=="], + + "ipaddr.js": ["ipaddr.js@1.9.1", "", {}, "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="], + + "is-promise": ["is-promise@4.0.0", "", {}, "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ=="], + + "isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="], + + "jose": ["jose@6.2.18", "", {}, "sha512-doV4thUwgkrycJH4yLeqwTGIIZphHl+pk7CPReuMIhYhncmgzdko85MaCG4YQFTxqMFr1/oEH32tZuKKovcDEg=="], + + "json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="], + + "json-schema-typed": ["json-schema-typed@8.0.2", "", {}, "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA=="], + + "math-intrinsics": ["math-intrinsics@1.1.0", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="], + + "media-typer": ["media-typer@1.1.1", "", {}, "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ=="], + + "merge-descriptors": ["merge-descriptors@2.0.0", "", {}, "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g=="], + + "mime-db": ["mime-db@1.54.0", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="], + + "mime-types": ["mime-types@3.0.2", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="], + + "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], + + "negotiator": ["negotiator@1.1.0", "", { "dependencies": { "content-type": "^2.1.0" } }, "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg=="], + + "object-assign": ["object-assign@4.1.1", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="], + + "object-inspect": ["object-inspect@1.14.0", "", {}, "sha512-IVgHNlp/jwQX271+Xzoq9LZNTWXxZK+cEOrGBOBxXNbn7fapnZ+Ts6TVMgNOuAezwG2wdtnMX97tTPK6VEnuOQ=="], + + "on-finished": ["on-finished@2.4.2", "", { "dependencies": { "ee-first": "1.1.1" } }, "sha512-ATWUv387i+nLD49EiDoOft5scf32Vsdz3ktrQJG9bi7jRFmaXTssvyvj1EmeKVVgvesbqUtvQQvaS2TpTukAZQ=="], + + "once": ["once@1.4.0", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="], + + "parseurl": ["parseurl@1.3.3", "", {}, "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="], + + "path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="], + + "path-to-regexp": ["path-to-regexp@8.4.2", "", {}, "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA=="], + + "pkce-challenge": ["pkce-challenge@5.0.2", "", {}, "sha512-vCc54+qyIfKC5e2UN28AZKElwqjLINgiIV3RKI8pDu93TjaAJoB3QrgMzEBouy8yOKsXVXdAinO1QArJf9x5WA=="], + + "proxy-addr": ["proxy-addr@2.0.8", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ=="], + + "qs": ["qs@6.17.1", "", { "dependencies": { "es-define-property": "^1.0.1", "side-channel": "^1.1.1" } }, "sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA=="], + + "range-parser": ["range-parser@1.3.0", "", {}, "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw=="], + + "raw-body": ["raw-body@3.0.2", "", { "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", "iconv-lite": "~0.7.0", "unpipe": "~1.0.0" } }, "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA=="], + + "require-from-string": ["require-from-string@2.0.2", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="], + + "router": ["router@2.3.0", "", { "dependencies": { "debug": "^4.4.0", "depd": "^2.0.0", "is-promise": "^4.0.0", "parseurl": "^1.3.3", "path-to-regexp": "^8.0.0" } }, "sha512-bpowRfGjEPe8t9R6fJIzhwmyCGAXwKvxBUsgJm+bJukwdcWmUXbMo7p22w7aYmQBPQTUMNqMV39YX0kMou3z8w=="], + + "safer-buffer": ["safer-buffer@2.1.2", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="], + + "send": ["send@1.2.1", "", { "dependencies": { "debug": "^4.4.3", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "fresh": "^2.0.0", "http-errors": "^2.0.1", "mime-types": "^3.0.2", "ms": "^2.1.3", "on-finished": "^2.4.1", "range-parser": "^1.2.1", "statuses": "^2.0.2" } }, "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ=="], + + "serve-static": ["serve-static@2.2.1", "", { "dependencies": { "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "parseurl": "^1.3.3", "send": "^1.2.0" } }, "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw=="], + + "setprototypeof": ["setprototypeof@1.2.0", "", {}, "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="], + + "shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="], + + "shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="], + + "side-channel": ["side-channel@1.1.1", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.4", "side-channel-list": "^1.0.1", "side-channel-map": "^1.0.1", "side-channel-weakmap": "^1.0.2" } }, "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ=="], + + "side-channel-list": ["side-channel-list@1.0.1", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.4" } }, "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w=="], + + "side-channel-map": ["side-channel-map@1.0.1", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3" } }, "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA=="], + + "side-channel-weakmap": ["side-channel-weakmap@1.0.2", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3", "side-channel-map": "^1.0.1" } }, "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A=="], + + "statuses": ["statuses@2.0.2", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="], + + "toidentifier": ["toidentifier@1.0.1", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="], + + "type-is": ["type-is@2.1.0", "", { "dependencies": { "content-type": "^2.0.0", "media-typer": "^1.1.0", "mime-types": "^3.0.0" } }, "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA=="], + + "unpipe": ["unpipe@1.0.0", "", {}, "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ=="], + + "vary": ["vary@1.1.2", "", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="], + + "which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="], + + "wrappy": ["wrappy@1.0.2", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="], + + "zod": ["zod@4.6.7", "", {}, "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg=="], + + "zod-to-json-schema": ["zod-to-json-schema@3.25.2", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="], + + "body-parser/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], + + "express/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], + + "negotiator/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], + + "type-is/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], + } +} diff --git a/cloud/compose.yml b/cloud/compose.yml new file mode 100644 index 0000000..a3114c1 --- /dev/null +++ b/cloud/compose.yml @@ -0,0 +1,22 @@ +# docker compose -f cloud/compose.yml --env-file cloud/app.env up -d --build +services: + web: + build: . + image: sk33p-cloud:latest + restart: unless-stopped + env_file: app.env + environment: + ORIGIN: https://sk33p.pwa.pit.world + ports: + - "127.0.0.1:8811:8811" + volumes: + - data:/data + read_only: true + tmpfs: + - /tmp:size=512m + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + mem_limit: 3g + pids_limit: 256 +volumes: + data: diff --git a/cloud/package.json b/cloud/package.json new file mode 100644 index 0000000..0e44050 --- /dev/null +++ b/cloud/package.json @@ -0,0 +1,15 @@ +{ + "name": "sk33p-cloud", + "private": true, + "type": "module", + "description": "sk33p.pwa.pit.world: hosted sk33p API and remote MCP (free tier + Pro via CoinPay)", + "scripts": { + "start": "bun src/main.ts", + "test": "bun test" + }, + "dependencies": { + "@profullstack/coinpay-onboard": "^0.5.1", + "@profullstack/footer": "^0.7.2", + "hono": "^4.13.23" + } +} diff --git a/cloud/src/app.ts b/cloud/src/app.ts new file mode 100644 index 0000000..598fbcb --- /dev/null +++ b/cloud/src/app.ts @@ -0,0 +1,445 @@ +/** + * sk33p cloud: the sk33p engine as an HTTP API and a remote MCP server. + * + * Plans (per day, UTC): + * anon no key, by IP — try it on the homepage + * free free key by email + * pro paid via CoinPay, N days per payment + * Going over answers 402 with the upgrade offer, never a bare 429. + */ +import { Hono, type Context } from 'hono' +import { randomBytes } from 'node:crypto' +import { CoinPay, CoinPayError, readWebhook, verifyWebhook } from '@profullstack/coinpay-onboard' +import { descriptorResponse } from '@profullstack/footer' +import { runTool, safeName, withExt, ToolError, FORMATS, type FileIn } from './engine.ts' +import { Store, type Key, type Plan } from './store.ts' +import { docsMarkdown, docsPage, homePage, keyPage, llmsTxt, messagePage, upgradePage } from './page.ts' + +export type Limits = { calls: number; maxBytes: number } +export type Config = { + origin: string + bin: string + limits: Record + proUsd: number + proDays: number + /** Process limits via prlimit (off only in tests on hosts without it). */ + sandbox: boolean + coinpay: { baseUrl: string; apiKey: string; businessId: string; webhookSecret: string; fetch?: typeof fetch } | null + /** Key mints per IP per day. */ + mintsPerIp: number +} + +export const DEFAULT_LIMITS: Record = { + anon: { calls: 10, maxBytes: 512 * 1024 }, + free: { calls: 100, maxBytes: 2 * 1024 * 1024 }, + pro: { calls: 10_000, maxBytes: 25 * 1024 * 1024 }, +} + +type Caller = { plan: Plan; key: Key | null; subject: string; limits: Limits } +type Env = { Variables: { ip: string } } + +const EMAIL = /^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]{2,}$/ + +export function validEmail(v: unknown): string | null { + const s = typeof v === 'string' ? v.trim().toLowerCase() : '' + return s.length <= 200 && EMAIL.test(s) ? s : null +} + +/** The tools, shared by the API and MCP. Each returns JSON plus maybe a file. */ +export const TOOLS = [ + { + name: 'eval', + description: 'Evaluate spreadsheet formulas with SkeeptoEngine (344 Excel-compatible functions: XLOOKUP, LET, FILTER, PMT, IRR, TEXTJOIN...). One result per formula. No ^ operator: use POWER().', + inputSchema: { type: 'object', properties: { formulas: { type: 'array', items: { type: 'string' }, description: 'e.g. ["=PMT(5%/12,360,-300000)", "=SUM(1,2,3)"]' } }, required: ['formulas'] }, + }, + { + name: 'read_range', + description: 'Read computed values (and optionally formulas) from a workbook you send (.xlsx, .sker, .csv, .tsv).', + inputSchema: { + type: 'object', + properties: { file: { $ref: '#/$defs/file' }, range: { type: 'string', description: 'A1 or A1:D20; omit for the used range' }, sheet: { type: 'string' }, formulas: { type: 'boolean' } }, + required: ['file'], + $defs: { file: fileSchema() }, + }, + }, + { + name: 'write_cells', + description: 'Set cells (values or =formulas) in a workbook you send, or in a new one, and get the recomputed values and the saved file back (base64).', + inputSchema: { + type: 'object', + properties: { + file: { $ref: '#/$defs/file' }, + name: { type: 'string', description: 'name for a new workbook, e.g. budget.xlsx (when no file is sent)' }, + cells: { type: 'object', additionalProperties: { type: 'string' }, description: '{"A1": "10", "B1": "=A1*2"}' }, + sheet: { type: 'string' }, + format: { type: 'string', enum: [...FORMATS], description: 'save as this format' }, + }, + required: ['cells'], + $defs: { file: fileSchema() }, + }, + }, + { + name: 'list_sheets', + description: 'List the sheets in a workbook you send, with their used size.', + inputSchema: { type: 'object', properties: { file: { $ref: '#/$defs/file' } }, required: ['file'], $defs: { file: fileSchema() } }, + }, + { + name: 'convert', + description: 'Convert a workbook between .xlsx, .sker, .csv and .tsv; the converted file comes back base64.', + inputSchema: { + type: 'object', + properties: { file: { $ref: '#/$defs/file' }, to: { type: 'string', enum: [...FORMATS] }, sheet: { type: 'string' } }, + required: ['file', 'to'], + $defs: { file: fileSchema() }, + }, + }, +] as const + +function fileSchema() { + return { type: 'object', properties: { name: { type: 'string', description: 'e.g. budget.xlsx' }, data: { type: 'string', description: 'file contents, base64' } }, required: ['name', 'data'] } +} + +const ACCOUNT_TOOLS = [ + { name: 'usage', description: 'Your plan, calls used today and limits.', inputSchema: { type: 'object', properties: {} } }, + { name: 'upgrade', description: 'Start a CoinPay checkout for Pro (any coin or PayPal). Returns a checkout_url for the human to open. Needs an API key.', inputSchema: { type: 'object', properties: {} } }, +] + +function fileArg(v: unknown, label = 'file'): FileIn { + const f = v as { name?: unknown; data?: unknown } | undefined + if (!f || typeof f !== 'object' || typeof f.data !== 'string') throw new ToolError(`${label} must be {"name": "x.xlsx", "data": ""}`) + return { name: safeName(f.name), data: f.data } +} + +/** Run one engine tool with cloud-shaped arguments. */ +export async function callTool(name: string, a: Record, cfg: Config, limits: Limits): Promise> { + const run = { bin: cfg.bin, maxBytes: limits.maxBytes, limits: cfg.sandbox } + const sheet = typeof a.sheet === 'string' && a.sheet ? { sheet: a.sheet.slice(0, 100) } : {} + switch (name) { + case 'eval': { + const fs = Array.isArray(a.formulas) ? a.formulas : typeof a.formula === 'string' ? [a.formula] : null + if (!fs?.length) throw new ToolError('send formulas: ["=SUM(1,2,3)"]') + if (fs.length > 200) throw new ToolError('at most 200 formulas per call') + if (fs.some((f: unknown) => typeof f !== 'string' || f.length > 4000)) throw new ToolError('each formula must be a string under 4000 characters') + const r = await runTool('eval', { formulas: fs }, [], null, run) + return { results: r.result } + } + case 'read_range': { + const f = fileArg(a.file) + const r = await runTool('read_range', { path: f.name, ...(typeof a.range === 'string' ? { range: a.range } : {}), ...sheet, formulas: Boolean(a.formulas) }, [f], null, run) + return { result: r.result } + } + case 'list_sheets': { + const f = fileArg(a.file) + const r = await runTool('list_sheets', { path: f.name }, [f], null, run) + return { sheets: r.result } + } + case 'write_cells': { + if (!a.cells || typeof a.cells !== 'object' || Array.isArray(a.cells)) throw new ToolError('send cells: {"A1": "10", "B1": "=A1*2"}') + const entries = Object.entries(a.cells) + if (!entries.length || entries.length > 5000) throw new ToolError('send between 1 and 5000 cells') + const cells = Object.fromEntries(entries.map(([k, v]) => [k, String(v)])) + const files = a.file ? [fileArg(a.file)] : [] + const name = files[0]?.name ?? safeName(a.name) + const out = typeof a.format === 'string' ? withExt(name, a.format) : name + const r = await runTool('write_cells', { path: name, cells, ...sheet, ...(out !== name ? { out } : {}) }, files, out, run) + return { result: r.result, file: r.file } + } + case 'convert': { + const f = fileArg(a.file) + const to = String(a.to ?? '').toLowerCase().replace(/^\./, '') + let out = withExt(f.name, to) + if (out === f.name) out = out.replace(/(\.[^.]+)$/, '-converted$1') + const r = await runTool('convert', { input: f.name, output: out, ...sheet }, [f], out, run) + if (!r.file) throw new ToolError('the engine wrote no file', 422) + return { file: r.file } + } + } + throw new ToolError(`unknown tool ${name}`, 404) +} + +export function createApp(store: Store, cfg: Config) { + const app = new Hono() + + const keyFrom = (c: Context): string | null => { + const auth = c.req.header('authorization') ?? '' + const m = /^Bearer\s+(\S+)$/i.exec(auth) + return m?.[1] ?? c.req.header('x-api-key') ?? c.req.query('key') ?? null + } + + /** Who is calling: a key's plan, or anonymous by IP. A bad key is an error, not anonymous. */ + const caller = (c: Context): Caller => { + const secret = keyFrom(c) + if (secret) { + const key = store.keyBySecret(secret) + if (!key) throw new ToolError('unknown API key', 401) + const plan: Plan = key.proUntil > Date.now() ? 'pro' : 'free' + return { plan, key, subject: `k:${key.id}`, limits: cfg.limits[plan] } + } + return { plan: 'anon', key: null, subject: `ip:${c.get('ip')}`, limits: cfg.limits.anon } + } + + const offer = (who: Caller) => ({ + plan: who.plan, + limit: who.limits.calls, + used: store.used(who.subject), + resets: 'midnight UTC', + next: + who.plan === 'anon' + ? { step: 'Get a free key (100 calls/day)', web: `${cfg.origin}/key`, api: `POST ${cfg.origin}/api/v1/keys {"email": "you@example.com"}` } + : { step: `Pro: ${cfg.limits.pro.calls} calls/day for $${cfg.proUsd} per ${cfg.proDays} days`, web: `${cfg.origin}/upgrade`, api: `POST ${cfg.origin}/api/v1/upgrade (with your key)`, price_usd: cfg.proUsd, days: cfg.proDays }, + }) + + const usage = (who: Caller) => ({ + plan: who.plan, + email: who.key?.email ?? null, + pro_until: who.key && who.key.proUntil > Date.now() ? new Date(who.key.proUntil).toISOString() : null, + calls_today: store.used(who.subject), + calls_per_day: who.limits.calls, + max_file_bytes: who.limits.maxBytes, + }) + + const fail = (c: Context, e: unknown) => { + if (e instanceof ToolError) return c.json({ error: e.message }, e.status as 400) + console.error(e) + return c.json({ error: 'something went wrong' }, 500) + } + + // Client address: the dev2 edge (Caddy) sets X-Forwarded-For; the first hop is the client. + app.use('*', async (c, next) => { + const xff = (c.req.header('x-forwarded-for') ?? '').split(',')[0]?.trim() + c.set('ip', xff || c.req.header('x-real-ip') || 'local') + await next() + }) + + app.get('/healthz', (c) => c.json({ ok: true })) + + // ---- pages + app.get('/', (c) => c.html(homePage(cfg))) + app.get('/docs', (c) => c.html(docsPage(cfg))) + app.get('/docs.md', (c) => c.text(docsMarkdown(cfg), 200, { 'content-type': 'text/markdown; charset=utf-8' })) + app.get('/llms.txt', (c) => c.text(llmsTxt(cfg))) + app.get('/pricing', (c) => c.redirect('/#pricing')) + app.get('/key', (c) => c.html(keyPage(cfg, {}))) + app.post('/key', async (c) => { + const form = await c.req.parseBody() + const r = mint(c, form.email) + if ('error' in r) return c.html(keyPage(cfg, { error: r.error, email: String(form.email ?? '') }), 400) + return c.html(keyPage(cfg, { key: r.key })) + }) + app.get('/upgrade', (c) => c.html(upgradePage(cfg, { paid: c.req.query('paid') === '1' }))) + app.post('/upgrade', async (c) => { + const form = await c.req.parseBody() + const key = store.keyBySecret(String(form.key ?? '').trim()) + if (!key) return c.html(upgradePage(cfg, { error: 'That key is not one of ours. Get a free key first, then upgrade it.' }), 400) + try { + const s = await checkout(key) + return c.redirect(s.checkout_url, 303) + } catch (e) { + return c.html(upgradePage(cfg, { error: e instanceof ToolError ? e.message : 'CoinPay did not answer; try again in a minute.' }), 502) + } + }) + app.get('/robots.txt', (c) => c.text(`User-agent: *\nAllow: /\nSitemap: ${cfg.origin}/sitemap.xml\n`)) + app.get('/sitemap.xml', (c) => + c.body(`\n${['/', '/docs', '/key', '/upgrade'].map((p) => `${cfg.origin}${p}`).join('')}`, 200, { 'content-type': 'application/xml' }), + ) + app.get('/.well-known/openwebring.json', () => descriptorResponse({ site: `${cfg.origin}/`, name: 'sk33p' })) + + // ---- keys + billing + const mint = (c: Context, emailIn: unknown): { key: string } | { error: string } => { + const email = validEmail(emailIn) + if (!email) return { error: 'Enter a real email: it is where CoinPay sends receipts if you upgrade.' } + if (!store.take(`mint:${c.get('ip')}`, cfg.mintsPerIp)) return { error: 'Too many keys from your address today. Try tomorrow.' } + return { key: store.mintKey(email).key } + } + + const checkout = async (key: Key) => { + const cp = cfg.coinpay + if (!cp) throw new ToolError('Payments are not set up on this server yet.', 503) + const client = new CoinPay({ token: cp.apiKey, base: cp.baseUrl, fetch: cp.fetch ?? fetch }) + const ref = `pp_${randomBytes(9).toString('base64url')}` + let session + try { + session = await client.createCheckoutSession({ + amount: cfg.proUsd, + currency: 'USD', + description: `sk33p Pro: ${cfg.limits.pro.calls} API/MCP calls a day for ${cfg.proDays} days`, + customerEmail: key.email, + accountId: key.id, + property: new URL(cfg.origin).hostname, + metadata: { key_id: key.id, product: 'pro', days: cfg.proDays, payment_ref: ref }, + successUrl: `${cfg.origin}/upgrade?paid=1`, + cancelUrl: `${cfg.origin}/upgrade`, + expiresInMinutes: 60, + }) + } catch (e) { + throw new ToolError(`CoinPay said ${e instanceof CoinPayError ? e.status : 'error'}: ${(e as Error).message.slice(0, 200)}`, 502) + } + if (!session?.id || !session.url) throw new ToolError('CoinPay returned no checkout session', 502) + // Written before the buyer leaves: the webhook can beat the redirect. + store.addPayment({ ref, keyId: key.id, sessionId: session.id, email: key.email, usd: cfg.proUsd, days: cfg.proDays }) + return { checkout_url: session.url, checkout_session_id: session.id, methods: session.methods ?? [], price_usd: cfg.proUsd, days: cfg.proDays } + } + + app.post('/api/v1/keys', async (c) => { + const body = await c.req.json().catch(() => ({})) + const r = mint(c, (body as any).email) + if ('error' in r) return c.json({ error: r.error }, 400) + return c.json({ key: r.key, plan: 'free', calls_per_day: cfg.limits.free.calls, note: 'Shown once: keep it. Send it as Authorization: Bearer .' }, 201) + }) + + app.get('/api/v1/me', (c) => { + try { + return c.json(usage(caller(c))) + } catch (e) { + return fail(c, e) + } + }) + + app.post('/api/v1/upgrade', async (c) => { + try { + const who = caller(c) + if (!who.key) throw new ToolError('send your API key (Authorization: Bearer sk33p_...); get one free at /key', 401) + return c.json(await checkout(who.key)) + } catch (e) { + return fail(c, e) + } + }) + + app.post('/hooks/coinpay', async (c) => { + const raw = await c.req.text() + const cp = cfg.coinpay + const header = c.req.header('x-coinpay-signature') + if (!cp?.webhookSecret || !header || !verifyWebhook(raw, header, cp.webhookSecret, Date.now())) return c.json({ error: 'bad signature' }, 401) + let payload: unknown + try { + payload = JSON.parse(raw) + } catch { + return c.json({ error: 'bad json' }, 400) + } + const ev = readWebhook(payload) + const row = store.payment({ sessionId: ev.checkoutSessionId }) ?? store.payment({ ref: typeof ev.metadata?.payment_ref === 'string' ? ev.metadata.payment_ref : null }) + if (!row) return c.json({ ok: true }) + if (ev.paid) { + if (store.settle(row.ref, ev.paymentId || null)) store.extendPro(row.keyId, row.days) + return c.json({ ok: true, settled: true }) + } + const status = ev.status || ev.type.replace(/^payment\./, '') + if (status) store.setStatus(row.ref, status) + return c.json({ ok: true }) + }) + + // ---- engine API + const metered = async (c: Context, tool: string, args: Record) => { + const who = caller(c) + if (!store.take(who.subject, who.limits.calls)) return c.json({ error: `daily limit reached (${who.limits.calls} calls on ${who.plan})`, ...offer(who) }, 402) + const out = await callTool(tool, args, cfg, who.limits) + c.header('x-sk33p-plan', who.plan) + c.header('x-sk33p-remaining', String(Math.max(0, who.limits.calls - store.used(who.subject)))) + return c.json(out) + } + + const routes: Record = { eval: 'eval', read: 'read_range', write: 'write_cells', sheets: 'list_sheets', convert: 'convert' } + for (const [path, tool] of Object.entries(routes)) { + app.post(`/api/v1/${path}`, async (c) => { + try { + const ct = c.req.header('content-type') ?? '' + // Raw upload: curl --data-binary @budget.xlsx '.../api/v1/convert?name=budget.xlsx&to=csv' + if (!ct.includes('json') && path !== 'eval') { + const buf = Buffer.from(await c.req.arrayBuffer()) + const q = c.req.query() + const args: Record = { ...q, file: { name: q.name ?? 'upload.xlsx', data: buf.toString('base64') } } + if (path === 'write') args.cells = JSON.parse(q.cells ?? '{}') + if (path === 'convert' || (path === 'write' && q.raw === '1')) { + const who = caller(c) + if (!store.take(who.subject, who.limits.calls)) return c.json({ error: `daily limit reached (${who.limits.calls} calls on ${who.plan})`, ...offer(who) }, 402) + const out: any = await callTool(tool, args, cfg, who.limits) + const f = out.file + return c.body(Buffer.from(f.data, 'base64'), 200, { 'content-type': 'application/octet-stream', 'content-disposition': `attachment; filename="${f.name}"`, 'x-sk33p-plan': who.plan }) + } + return await metered(c, tool, args) + } + const body = await c.req.json().catch(() => { + throw new ToolError('send a JSON body') + }) + return await metered(c, tool, body as Record) + } catch (e) { + return fail(c, e) + } + }) + } + + // ---- remote MCP (streamable HTTP, stateless JSON responses) + app.get('/mcp', (c) => c.json({ error: 'POST JSON-RPC here; see /docs#mcp' }, 405)) + app.post('/mcp', async (c) => { + let msg: any + try { + msg = await c.req.json() + } catch { + return c.json({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'parse error' } }) + } + if (Array.isArray(msg)) return c.json(await Promise.all(msg.map((m) => rpc(c, m)))) + if (msg?.id === undefined || msg?.id === null) return c.body(null, 202) + return c.json(await rpc(c, msg)) + }) + + const rpc = async (c: Context, m: any) => { + const ok = (result: unknown) => ({ jsonrpc: '2.0', id: m.id, result }) + const toolText = (v: unknown, isError = false) => ok({ content: [{ type: 'text', text: typeof v === 'string' ? v : JSON.stringify(v) }], ...(isError ? { isError: true } : { structuredContent: v }) }) + switch (m.method) { + case 'initialize': + return ok({ protocolVersion: m.params?.protocolVersion ?? '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'sk33p', version: '0.1.0' }, instructions: `Spreadsheet engine (344 Excel functions, .xlsx in and out). Files go in and out as base64. Free: ${cfg.limits.free.calls} calls/day with a key from ${cfg.origin}/key; Pro via the upgrade tool.` }) + case 'ping': + return ok({}) + case 'tools/list': + return ok({ tools: [...TOOLS, ...ACCOUNT_TOOLS] }) + case 'tools/call': { + const name = m.params?.name + const args = m.params?.arguments ?? {} + try { + const who = caller(c) + if (name === 'usage') return toolText(usage(who)) + if (name === 'upgrade') { + if (!who.key) return toolText(`Get a free key at ${cfg.origin}/key and connect with it first.`, true) + return toolText(await checkout(who.key)) + } + if (!TOOLS.some((t) => t.name === name)) return { jsonrpc: '2.0', id: m.id, error: { code: -32602, message: `unknown tool ${name}` } } + if (!store.take(who.subject, who.limits.calls)) return toolText({ error: `daily limit reached (${who.limits.calls} calls on ${who.plan})`, ...offer(who) }, true) + return toolText(await callTool(name, args, cfg, who.limits)) + } catch (e) { + return toolText(e instanceof ToolError ? e.message : 'something went wrong', true) + } + } + default: + return { jsonrpc: '2.0', id: m.id, error: { code: -32601, message: `method not found: ${m.method}` } } + } + } + + app.notFound((c) => (c.req.path.startsWith('/api/') ? c.json({ error: 'not found' }, 404) : c.html(messagePage(cfg, 'Not found', 'That page does not exist.'), 404))) + app.onError((e, c) => { + console.error(e) + return c.req.path.startsWith('/api/') ? c.json({ error: 'something went wrong' }, 500) : c.html(messagePage(cfg, 'Something went wrong', 'Try again in a moment.'), 500) + }) + return app +} + +export function configFromEnv(env: Record = process.env): Config { + const n = (k: string, d: number) => (env[k] && Number.isFinite(Number(env[k])) ? Number(env[k]) : d) + const coinpay = + env.COINPAY_API_KEY && env.COINPAY_BUSINESS_ID + ? { baseUrl: (env.COINPAY_API_URL ?? 'https://coinpayportal.com').replace(/\/+$/, '').replace(/\/api$/, ''), apiKey: env.COINPAY_API_KEY, businessId: env.COINPAY_BUSINESS_ID, webhookSecret: env.COINPAY_WEBHOOK_SECRET ?? '' } + : null + return { + origin: (env.ORIGIN ?? 'https://sk33p.pwa.pit.world').replace(/\/+$/, ''), + bin: env.SK33P_BIN ?? 'sk33p', + limits: { + anon: { calls: n('ANON_CALLS', DEFAULT_LIMITS.anon.calls), maxBytes: n('ANON_BYTES', DEFAULT_LIMITS.anon.maxBytes) }, + free: { calls: n('FREE_CALLS', DEFAULT_LIMITS.free.calls), maxBytes: n('FREE_BYTES', DEFAULT_LIMITS.free.maxBytes) }, + pro: { calls: n('PRO_CALLS', DEFAULT_LIMITS.pro.calls), maxBytes: n('PRO_BYTES', DEFAULT_LIMITS.pro.maxBytes) }, + }, + proUsd: n('PRO_USD', 9), + proDays: n('PRO_DAYS', 30), + sandbox: env.SANDBOX !== '0', + coinpay, + mintsPerIp: n('MINTS_PER_IP', 5), + } +} diff --git a/cloud/src/engine.ts b/cloud/src/engine.ts new file mode 100644 index 0000000..463daa7 --- /dev/null +++ b/cloud/src/engine.ts @@ -0,0 +1,100 @@ +/** + * Runs one sk33p MCP tool call in a fresh, resource-limited process. + * + * The engine keeps its state in singletons (one workbook per process), so every + * call gets its own `sk33p mcp` in its own scratch directory: input files are + * written there, the tool runs with paths relative to it, any output file is + * read back, and the directory is removed. prlimit caps address space, CPU + * seconds and file size so a hostile workbook cannot take the box down. + */ +import { mkdtemp, readFile, rm, writeFile, stat } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +export type FileIn = { name: string; data: string } +export type FileOut = { name: string; data: string; bytes: number } + +export class ToolError extends Error { + constructor(message: string, readonly status = 400) { + super(message) + } +} + +export const FORMATS = ['xlsx', 'sker', 'csv', 'tsv'] as const +export type Format = (typeof FORMATS)[number] + +/** A file name safe to use inside the scratch dir: plain basename, known extension. */ +export function safeName(name: unknown, fallback = 'workbook.xlsx'): string { + const raw = typeof name === 'string' && name.trim() ? name.trim() : fallback + const base = raw.split(/[\\/]/).pop() ?? '' + const clean = base.replace(/[^A-Za-z0-9._-]/g, '_').replace(/^\.+/, '').slice(0, 80) + const ext = clean.split('.').pop()?.toLowerCase() ?? '' + if (!clean || !(FORMATS as readonly string[]).includes(ext)) throw new ToolError(`file name must end in .${FORMATS.join(', .')}`) + return clean +} + +export function withExt(name: string, to: string): string { + if (!(FORMATS as readonly string[]).includes(to)) throw new ToolError(`format must be one of ${FORMATS.join(', ')}`) + return name.replace(/\.[^.]+$/, '') + '.' + to +} + +export type RunOptions = { + bin: string + timeoutMs?: number + /** Largest file accepted in or produced, bytes. */ + maxBytes: number + /** Use prlimit (Linux). Tests on other hosts can turn it off. */ + limits?: boolean +} + +export type RunResult = { result: unknown; file?: FileOut } + +/** + * Call `tool` with `args`. `files` are written into the scratch dir first; + * `outputName` (if set) is read back after the call. + */ +export async function runTool(tool: string, args: Record, files: FileIn[], outputName: string | null, o: RunOptions): Promise { + const dir = await mkdtemp(join(tmpdir(), 'sk33p-')) + try { + for (const f of files) { + const buf = Buffer.from(f.data, 'base64') + if (buf.length > o.maxBytes) throw new ToolError(`${f.name} is ${buf.length} bytes; your plan allows ${o.maxBytes}`, 413) + await writeFile(join(dir, f.name), buf) + } + const line = JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: tool, arguments: args } }) + '\n' + const cmd = o.limits === false ? [o.bin, 'mcp'] : ['prlimit', '--as=1610612736', '--cpu=20', `--fsize=${Math.max(o.maxBytes * 4, 8 << 20)}`, '--nproc=64', '--', o.bin, 'mcp'] + const proc = Bun.spawn(cmd, { cwd: dir, stdin: 'pipe', stdout: 'pipe', stderr: 'pipe', env: { PATH: '/usr/bin:/bin', HOME: dir, LANG: 'C.UTF-8' } }) + proc.stdin.write(line) + proc.stdin.end() + const timer = setTimeout(() => proc.kill(9), o.timeoutMs ?? 20_000) + const [out, err, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]) + clearTimeout(timer) + const first = out.split('\n').find((l) => l.trim().startsWith('{')) + if (!first) throw new ToolError(code === 137 || code === 9 ? 'the engine ran out of time or memory on that input' : `the engine failed (${code}): ${err.slice(0, 300)}`, 422) + const msg = JSON.parse(first) + if (msg.error) throw new ToolError(String(msg.error.message ?? 'engine error'), 422) + const r = msg.result ?? {} + const text = r.content?.[0]?.text ?? '' + if (r.isError) throw new ToolError(String(text || 'engine error'), 422) + let result: unknown = r.structuredContent?.result ?? r.structuredContent + if (result === undefined) { + try { + result = JSON.parse(text) + } catch { + result = text + } + } + let file: FileOut | undefined + if (outputName) { + const p = join(dir, outputName) + const s = await stat(p).catch(() => null) + if (s) { + if (s.size > o.maxBytes) throw new ToolError(`the result is ${s.size} bytes; your plan allows ${o.maxBytes}`, 413) + file = { name: outputName, data: (await readFile(p)).toString('base64'), bytes: s.size } + } + } + return { result, file } + } finally { + await rm(dir, { recursive: true, force: true }) + } +} diff --git a/cloud/src/main.ts b/cloud/src/main.ts new file mode 100644 index 0000000..6cc3f40 --- /dev/null +++ b/cloud/src/main.ts @@ -0,0 +1,24 @@ +import { footerHtml } from '@profullstack/footer' +import { createApp, configFromEnv } from './app.ts' +import { setFooters } from './page.ts' +import { Store } from './store.ts' + +const cfg = configFromEnv() +const store = new Store(process.env.DB_PATH ?? `${process.env.DATA_DIR ?? '.'}/sk33p-cloud.db`) +const app = createApp(store, cfg) + +// Footers: site footer, Profullstack webring row, pit.world footer last. Refreshed hourly; pages never wait. +const host = new URL(cfg.origin).hostname +const refresh = async () => { + const ring = await footerHtml({ site: `${cfg.origin}/`, links: [{ label: 'Docs', href: '/docs' }, { label: 'Pricing', href: '/#pricing' }, { label: 'GitHub', href: 'https://github.com/profullstack/sk33p' }], since: 2026 }).catch(() => '') + const pit = await fetch(`https://pit.world/snippets/footer.html?site=${encodeURIComponent(host)}`, { signal: AbortSignal.timeout(3000) }) + .then((r) => (r.ok ? r.text() : '')) + .catch(() => '') + setFooters({ ring, pit }) +} +refresh() +setInterval(refresh, 60 * 60_000).unref?.() + +const port = Number(process.env.PORT ?? 8811) +Bun.serve({ port, hostname: process.env.HOST ?? '0.0.0.0', fetch: app.fetch, idleTimeout: 60 }) +console.log(`sk33p cloud on :${port} (${cfg.origin}), payments ${cfg.coinpay ? 'on' : 'OFF'}, sandbox ${cfg.sandbox ? 'prlimit' : 'off'}`) diff --git a/cloud/src/page.ts b/cloud/src/page.ts new file mode 100644 index 0000000..61b3d1f --- /dev/null +++ b/cloud/src/page.ts @@ -0,0 +1,303 @@ +/** Server-rendered pages. One stylesheet, no build step, no client framework. */ +import type { Config } from './app.ts' + +const INSTALL = 'curl -fsSL https://raw.githubusercontent.com/profullstack/sk33p/main/install.sh | sh' +const REPO = 'https://github.com/profullstack/sk33p' + +// Footers are fetched in the background by main.ts and set here; pages never wait on them. +let ringFooter = '' +let pitFooter = '' +export function setFooters(f: { ring?: string; pit?: string }) { + if (typeof f.ring === 'string' && f.ring) ringFooter = f.ring + if (typeof f.pit === 'string' && f.pit.includes('data-pit-footer') && f.pit.length < 64_000) pitFooter = f.pit.trim() +} + +export const esc = (s: unknown) => String(s ?? '').replace(/[&<>"']/g, (ch) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[ch]!) + +const CSS = ` +:root{--bg:#0b0f0c;--panel:#111814;--line:#1f2a23;--fg:#d8e6dc;--dim:#8aa293;--accent:#5cff8d;--accent-ink:#04210f;--warn:#ffcf5c;--err:#ff6b6b;--radius:10px;color-scheme:dark} +@media (prefers-color-scheme: light){:root:not([data-theme="dark"]){--bg:#f6faf7;--panel:#fff;--line:#d9e5dd;--fg:#122018;--dim:#4d6457;--accent:#0f8a3c;--accent-ink:#fff;--warn:#9a6a00;--err:#b42318;color-scheme:light}} +*{box-sizing:border-box}html,body{margin:0} +body{background:var(--bg);color:var(--fg);font:16px/1.6 system-ui,-apple-system,Segoe UI,Roboto,sans-serif} +a{color:var(--accent)}code,pre,kbd,.mono{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace} +.wrap{max-width:1040px;margin:0 auto;padding:0 16px} +header.top{display:flex;align-items:center;gap:16px;padding:18px 0;flex-wrap:wrap} +header.top .brand{font:700 22px ui-monospace,Menlo,monospace;color:var(--fg);text-decoration:none;letter-spacing:.5px} +header.top .brand b{color:var(--accent)} +header.top nav{display:flex;gap:16px;margin-left:auto;flex-wrap:wrap} +header.top nav a{color:var(--dim);text-decoration:none}header.top nav a:hover{color:var(--fg)} +.hero{padding:40px 0 24px} +.hero h1{font-size:clamp(30px,5vw,50px);line-height:1.1;margin:0 0 14px;letter-spacing:-.5px} +.hero h1 em{font-style:normal;color:var(--accent)} +.hero p.lede{font-size:clamp(17px,2.2vw,20px);color:var(--dim);max-width:720px;margin:0 0 22px} +.cmd{display:flex;align-items:center;gap:8px;background:var(--panel);border:1px solid var(--line);border-radius:var(--radius);padding:10px 12px;max-width:100%;overflow-x:auto} +.cmd code{white-space:nowrap;font-size:14px}.cmd .p{color:var(--accent)} +button,.btn{font:600 15px system-ui,sans-serif;border-radius:8px;border:1px solid var(--accent);background:var(--accent);color:var(--accent-ink);padding:10px 16px;cursor:pointer;text-decoration:none;display:inline-block} +.btn.ghost{background:transparent;color:var(--accent)} +.copy{padding:4px 10px;font-size:13px;margin-left:auto;flex:none} +.ctas{display:flex;gap:12px;flex-wrap:wrap;margin-top:18px} +pre.term{background:#050806;color:#c9f5d6;border:1px solid var(--line);border-radius:var(--radius);padding:16px;overflow-x:auto;font-size:13.5px;line-height:1.45;margin:28px 0} +section{padding:34px 0;border-top:1px solid var(--line)} +section h2{font-size:26px;margin:0 0 6px}section .sub{color:var(--dim);margin:0 0 20px} +.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,260px),1fr));gap:16px} +.card{background:var(--panel);border:1px solid var(--line);border-radius:var(--radius);padding:18px} +.card h3{margin:0 0 8px;font-size:18px}.card p{margin:0;color:var(--dim)} +.demo textarea{width:100%;min-height:120px;background:var(--panel);color:var(--fg);border:1px solid var(--line);border-radius:8px;padding:12px;font:14px ui-monospace,Menlo,monospace;resize:vertical} +.demo .row{display:flex;gap:12px;align-items:center;margin-top:10px;flex-wrap:wrap} +.demo table{width:100%;border-collapse:collapse;margin-top:14px;font:14px ui-monospace,Menlo,monospace} +.demo td{border-top:1px solid var(--line);padding:6px 8px;vertical-align:top;word-break:break-word}.demo td.v{color:var(--accent);text-align:right} +.note{color:var(--dim);font-size:14px}.err{color:var(--err)} +.price{display:flex;flex-direction:column;gap:10px} +.price .amt{font:700 32px system-ui,sans-serif}.price .amt small{font-size:15px;color:var(--dim);font-weight:500} +.price ul{margin:0;padding-left:18px;color:var(--dim)}.price .btn{margin-top:auto;text-align:center} +.price.hot{border-color:var(--accent)} +pre.code{background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:14px;overflow-x:auto;font-size:13.5px} +details{border-top:1px solid var(--line);padding:12px 0}summary{cursor:pointer;font-weight:600} +form.stack{display:flex;flex-direction:column;gap:12px;max-width:520px} +input[type=email],input[type=text]{background:var(--panel);color:var(--fg);border:1px solid var(--line);border-radius:8px;padding:11px 12px;font:15px system-ui,sans-serif;width:100%} +.keybox{background:var(--panel);border:1px solid var(--accent);border-radius:8px;padding:14px;font:15px ui-monospace,Menlo,monospace;word-break:break-all} +.doc h2{margin-top:34px}.doc h3{margin-top:24px}.doc table{border-collapse:collapse;width:100%;display:block;overflow-x:auto}.doc td,.doc th{border:1px solid var(--line);padding:6px 10px;text-align:left} +.site-foot{border-top:1px solid var(--line);margin-top:40px;padding:24px 0;color:var(--dim);font-size:14px} +` + +function layout(cfg: Config, o: { title: string; description: string; path: string; body: string }) { + const url = cfg.origin + o.path + return ` +${esc(o.title)} + + + + + + + +
sk33p
+${o.body} + +
+${ringFooter} +${pitFooter} +` +} + +const TERM = `
 sk33p  budget.xlsx [+]    Summary   Jan   Feb
+ C4      │ =SUM(C2:C3)*1.2
+     │      A       │      B       │      C
+   1 │ item         │ qty          │        price
+   2 │ widget       │            4 │        12.50
+   3 │ gadget       │            2 │        40.00
+   4 │ total        │              │       156.00
+ READY                                   ? help  ^S save  ^Q quit
` + +const cmdBox = (text: string, prompt = '$') => `
${prompt}${esc(text)}
` + +const COPY_JS = `` + +export function homePage(cfg: Config): string { + const L = cfg.limits + const curl = `curl -s ${cfg.origin}/api/v1/eval -H 'content-type: application/json' \\\n -d '{"formulas":["=PMT(5%/12,360,-300000)","=XLOOKUP(2,{1,2,3},{\\"a\\",\\"b\\",\\"c\\"})"]}'` + const body = ` +
+

A spreadsheet for the terminal.
And an Excel engine for your agents.

+

sk33p opens, edits and saves real .xlsx files in your terminal, with 344 Excel-compatible functions: XLOOKUP, LET, FILTER, PMT, IRR and the rest. The app is free and open source. The hosted API and remote MCP give scripts and AI agents the same engine with nothing to install.

+ ${cmdBox(INSTALL)} + + ${TERM} +
+ +

Try it now

One formula per line. This runs on the hosted engine (${L.anon.calls} free tries a day without a key).

+
+
No ^ operator in this engine: use POWER().
+ +
+ +

One engine, four ways in

The same calculation core everywhere: people in a terminal, agents over a socket.

+
+

TUI

A full-screen grid: arrows or hjkl, = to type a formula, undo and redo, sheet tabs, :w file.xlsx to save as. Opens .xlsx, .csv, .tsv.

+

CLI

sk33p eval, get, set, cat --csv, convert. Pipe workbooks through shell scripts and CI.

+

API

Evaluate formulas, read ranges, write cells and convert files over HTTPS. Send a workbook, get JSON or the saved file back.

+

MCP

sk33p mcp locally on stdio, or the hosted server at ${esc(cfg.origin)}/mcp for Claude, Cursor and any MCP client.

+
+ +

API in one line

No key needed to try. Add Authorization: Bearer sk33p_... for your plan's limits.

+
${esc(curl)}
+
${esc(`# xlsx in, csv out\ncurl -s --data-binary @budget.xlsx '${cfg.origin}/api/v1/convert?name=budget.xlsx&to=csv' \\\n  -H "authorization: Bearer $SK33P_KEY" -o budget.csv`)}
+
${esc(JSON.stringify({ mcpServers: { sk33p: { type: 'http', url: `${cfg.origin}/mcp`, headers: { Authorization: 'Bearer sk33p_...' } } } }, null, 2))}
+

Every endpoint and MCP tool

+ +

Pricing

The terminal app is free forever. The hosted API and MCP have a free tier; Pro is for real workloads.

+
+

Terminal

$0 forever, MIT
  • TUI, CLI and local MCP
  • Runs on your machine, no limits
  • Linux x86_64 / arm64, macOS arm64
Install
+

Free API

$0 with an email
  • ${L.free.calls} API + MCP calls a day
  • Files up to ${Math.round(L.free.maxBytes / 1048576)} MB
  • All tools: eval, read, write, sheets, convert
Get a free key
+

Pro

$${cfg.proUsd} per ${cfg.proDays} days
  • ${L.pro.calls.toLocaleString('en-US')} calls a day
  • Files up to ${Math.round(L.pro.maxBytes / 1048576)} MB
  • Pay with any coin or PayPal via CoinPay
  • No subscription: buy more days when you want
Go Pro
+
+ +

Questions

+
What is the engine?

SkeeptoEngine, a C++20 calculation core by Stéphane Allez (MIT): 344 worksheet functions including dynamic arrays, XLOOKUP, LET, LAMBDA helpers and financial solvers. sk33p is an independent Rust frontend for it.

+
Do you keep my files?

No. Each call runs in a fresh, sandboxed process in a scratch directory that is deleted when the call ends. We store your key's hash, your email and a daily call count.

+
What happens when I hit the limit?

The API answers 402 with the next step (a free key, or Pro) instead of a bare error. Counts reset at midnight UTC.

+
Anything Excel does that sk33p does not?

No ^ operator (use POWER()), one workbook per process, no charts or macros. Number formats from .xlsx are applied.

+
+${COPY_JS}` + return layout(cfg, { title: 'sk33p: a terminal spreadsheet and Excel engine API', description: 'Open and edit .xlsx in your terminal with 344 Excel-compatible functions. Free TUI and CLI; hosted API and remote MCP for agents, free tier and Pro.', path: '/', body }) +} + +export function keyPage(cfg: Config, o: { key?: string; error?: string; email?: string }): string { + const body = o.key + ? `

Your free key

Shown once. Copy it somewhere safe: we only keep its hash.

+
${esc(o.key)}
+

Use it

${esc(`export SK33P_KEY=${o.key}\ncurl -s ${cfg.origin}/api/v1/me -H "authorization: Bearer $SK33P_KEY"`)}
+

${cfg.limits.free.calls} calls a day. Need more? Go Pro for $${cfg.proUsd} per ${cfg.proDays} days.

${COPY_JS}` + : `

Get a free API key

${cfg.limits.free.calls} API and MCP calls a day, files up to ${Math.round(cfg.limits.free.maxBytes / 1048576)} MB. Your email is where CoinPay sends receipts if you upgrade later.

+
+ +${o.error ? `

${esc(o.error)}

` : ''}
` + return layout(cfg, { title: 'Free API key · sk33p', description: 'A free sk33p API key: the Excel-compatible engine over HTTPS and MCP.', path: '/key', body }) +} + +export function upgradePage(cfg: Config, o: { error?: string; paid?: boolean }): string { + const body = o.paid + ? `

Thanks: Pro is on its way

CoinPay confirms the payment on chain, then your key turns Pro (usually a minute or two). Check with:

+
${esc(`curl -s ${cfg.origin}/api/v1/me -H "authorization: Bearer $SK33P_KEY"`)}
` + : `

sk33p Pro

$${cfg.proUsd} for ${cfg.proDays} days: ${cfg.limits.pro.calls.toLocaleString('en-US')} calls a day and files up to ${Math.round(cfg.limits.pro.maxBytes / 1048576)} MB. Pay with any coin or PayPal through CoinPay. No subscription; each payment adds ${cfg.proDays} days.

+
+${o.error ? `

${esc(o.error)}

` : ''}
+

No key yet? Get a free one first. Agents can call POST /api/v1/upgrade or the MCP upgrade tool and hand you the checkout link.

` + return layout(cfg, { title: 'sk33p Pro', description: `sk33p Pro: ${cfg.limits.pro.calls} Excel-engine API calls a day for $${cfg.proUsd}, paid in crypto or PayPal.`, path: '/upgrade', body }) +} + +export function messagePage(cfg: Config, title: string, message: string): string { + return layout(cfg, { title: `${title} · sk33p`, description: message, path: '/', body: `

${esc(title)}

${esc(message)}

Home
` }) +} + +export function docsMarkdown(cfg: Config): string { + const o = cfg.origin + const L = cfg.limits + return `# sk33p API and MCP + +The sk33p engine (SkeeptoEngine, 344 Excel-compatible functions, reads and writes .xlsx) over HTTPS and MCP. +Base URL: ${o} + +## Auth and limits + +Send your key as \`Authorization: Bearer sk33p_...\` (or \`X-API-Key\`, or \`?key=\` for MCP clients that cannot set headers). +Get a free key at ${o}/key or \`POST /api/v1/keys {"email": "you@example.com"}\`. + +| Plan | Calls a day | Largest file | Price | +| --- | --- | --- | --- | +| No key | ${L.anon.calls} | ${Math.round(L.anon.maxBytes / 1024)} KB | free | +| Free key | ${L.free.calls} | ${Math.round(L.free.maxBytes / 1048576)} MB | free | +| Pro | ${L.pro.calls} | ${Math.round(L.pro.maxBytes / 1048576)} MB | $${cfg.proUsd} per ${cfg.proDays} days | + +Days reset at midnight UTC. Over the limit the API answers **402** with \`next\`: how to get a key or go Pro. +Every engine response carries \`x-sk33p-plan\` and \`x-sk33p-remaining\`. + +Files travel as \`{"name": "budget.xlsx", "data": ""}\`. Formats: .xlsx, .sker, .csv, .tsv. +Each call runs in a fresh sandboxed process; nothing is kept. + +## Endpoints + +### POST /api/v1/eval +\`{"formulas": ["=PMT(5%/12,360,-300000)", "=SUM(1,2,3)"]}\` -> \`{"results": [{"formula": "...", "value": "1610.46486903642"}, ...]}\` +Up to 200 formulas. The engine has no ^ operator: use POWER(). + +### POST /api/v1/read +\`{"file": {...}, "range": "A1:D20", "sheet": "Jan", "formulas": true}\` -> computed values (and formulas). Omit range for the used range. + +### POST /api/v1/write +\`{"file": {...} | omit for a new workbook, "name": "new.xlsx", "cells": {"A1": "10", "B1": "=A1*2"}, "sheet": "Sheet1", "format": "xlsx"}\` +-> \`{"result": ..., "file": {"name", "data", "bytes"}}\` with the saved workbook. + +### POST /api/v1/sheets +\`{"file": {...}}\` -> sheet names and used sizes. + +### POST /api/v1/convert +\`{"file": {...}, "to": "csv"}\` -> \`{"file": {...}}\`. +Raw form: \`curl --data-binary @budget.xlsx '${o}/api/v1/convert?name=budget.xlsx&to=csv' -o budget.csv\` returns the file itself. + +### GET /api/v1/me +Your plan, calls today and limits. + +### POST /api/v1/keys +\`{"email": "you@example.com"}\` -> \`{"key": "sk33p_..."}\` (shown once). + +### POST /api/v1/upgrade +With your key: starts a CoinPay checkout for Pro and returns \`checkout_url\` (any coin or PayPal). Each payment adds ${cfg.proDays} days. + +## MCP + +Remote server (streamable HTTP): \`${o}/mcp\` + +\`\`\`json +{"mcpServers": {"sk33p": {"type": "http", "url": "${o}/mcp", "headers": {"Authorization": "Bearer sk33p_..."}}}} +\`\`\` + +Tools: eval, read_range, write_cells, list_sheets, convert (files as base64), usage, upgrade. + +Local, unlimited, no account: install the app and run \`sk33p mcp\` (stdio; the same tools on file paths). + +## The app + +\`${INSTALL}\` + +Source: ${REPO} (MIT) +` +} + +/** Tiny Markdown renderer for our own docs (headings, code, tables, paragraphs, inline code). */ +function md(src: string): string { + const inline = (s: string) => + esc(s) + .replace(/`([^`]+)`/g, '$1') + .replace(/\*\*([^*]+)\*\*/g, '$1') + .replace(/(https:\/\/[^\s<)]+)/g, '$1') + const out: string[] = [] + const lines = src.split('\n') + for (let i = 0; i < lines.length; i++) { + const l = lines[i]! + if (l.startsWith('```')) { + const buf: string[] = [] + while (++i < lines.length && !lines[i]!.startsWith('```')) buf.push(lines[i]!) + out.push(`
${esc(buf.join('\n'))}
`) + } else if (l.startsWith('|')) { + const rows: string[] = [] + for (; i < lines.length && lines[i]!.startsWith('|'); i++) if (!/^\|\s*-/.test(lines[i]!)) rows.push(lines[i]!) + i-- + out.push(`${rows.map((r, n) => `${r.split('|').slice(1, -1).map((c) => (n ? `` : ``)).join('')}`).join('')}
${inline(c.trim())}${inline(c.trim())}
`) + } else if (/^#{1,3} /.test(l)) { + const n = l.indexOf(' ') + const text = l.slice(n + 1) + const id = text.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') + out.push(`${inline(text)}`) + } else if (l.trim()) out.push(`

${inline(l)}

`) + } + return out.join('\n') +} + +export function docsPage(cfg: Config): string { + return layout(cfg, { title: 'Docs · sk33p API and MCP', description: 'sk33p API and MCP reference: eval, read, write, sheets, convert; limits, keys and Pro.', path: '/docs', body: `
${md(docsMarkdown(cfg))}

This page as Markdown: /docs.md

` }) +} + +export function llmsTxt(cfg: Config): string { + return `# sk33p + +> A terminal spreadsheet (TUI + CLI, MIT) and a hosted Excel-compatible formula engine (API + remote MCP) with 344 functions that reads and writes .xlsx. + +- [Docs (Markdown)](${cfg.origin}/docs.md): every endpoint, MCP tool, limit and price +- [Remote MCP](${cfg.origin}/mcp): streamable HTTP; tools eval, read_range, write_cells, list_sheets, convert, usage, upgrade +- [Free API key](${cfg.origin}/key) +- [Pro](${cfg.origin}/upgrade): $${cfg.proUsd} per ${cfg.proDays} days via CoinPay +- [Source](${REPO}) +` +} diff --git a/cloud/src/store.ts b/cloud/src/store.ts new file mode 100644 index 0000000..bf46458 --- /dev/null +++ b/cloud/src/store.ts @@ -0,0 +1,101 @@ +/** Keys, daily usage and CoinPay payments, in one SQLite file. */ +import { Database } from 'bun:sqlite' +import { createHash, randomBytes } from 'node:crypto' + +export type Plan = 'anon' | 'free' | 'pro' +export type Key = { id: string; email: string; proUntil: number; createdAt: number } +export type Payment = { ref: string; keyId: string; sessionId: string | null; days: number; status: string } + +export const hashKey = (k: string) => createHash('sha256').update(k).digest('hex') +export const day = (now = Date.now()) => new Date(now).toISOString().slice(0, 10) + +export class Store { + readonly db: Database + constructor(path = ':memory:') { + this.db = new Database(path, { create: true }) + this.db.exec('PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000;') + this.db.exec(` + CREATE TABLE IF NOT EXISTS keys (id TEXT PRIMARY KEY, hash TEXT UNIQUE NOT NULL, email TEXT NOT NULL, pro_until INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL); + CREATE INDEX IF NOT EXISTS keys_email ON keys(email); + CREATE TABLE IF NOT EXISTS usage (subject TEXT NOT NULL, day TEXT NOT NULL, n INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (subject, day)); + CREATE TABLE IF NOT EXISTS payments (ref TEXT PRIMARY KEY, key_id TEXT NOT NULL, session_id TEXT UNIQUE, email TEXT, usd REAL NOT NULL, days INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'pending', payment_id TEXT, created_at INTEGER NOT NULL, settled_at INTEGER); + `) + } + + /** A new key; the secret is returned once and only its hash is kept. */ + mintKey(email: string, now = Date.now()): { key: string; id: string } { + const key = `sk33p_${randomBytes(24).toString('base64url')}` + const id = `k_${randomBytes(8).toString('base64url')}` + this.db.query('INSERT INTO keys (id, hash, email, created_at) VALUES (?, ?, ?, ?)').run(id, hashKey(key), email, now) + return { key, id } + } + + keyBySecret(secret: string): Key | null { + const r: any = this.db.query('SELECT id, email, pro_until, created_at FROM keys WHERE hash = ?').get(hashKey(secret)) + return r ? { id: r.id, email: r.email, proUntil: r.pro_until, createdAt: r.created_at } : null + } + + keyById(id: string): Key | null { + const r: any = this.db.query('SELECT id, email, pro_until, created_at FROM keys WHERE id = ?').get(id) + return r ? { id: r.id, email: r.email, proUntil: r.pro_until, createdAt: r.created_at } : null + } + + /** Add `days` of Pro, starting from now or from the end of the current Pro period. */ + extendPro(id: string, days: number, now = Date.now()): number { + const k = this.keyById(id) + if (!k) return 0 + const until = Math.max(now, k.proUntil) + days * 86_400_000 + this.db.query('UPDATE keys SET pro_until = ? WHERE id = ?').run(until, id) + return until + } + + used(subject: string, now = Date.now()): number { + const r: any = this.db.query('SELECT n FROM usage WHERE subject = ? AND day = ?').get(subject, day(now)) + return r?.n ?? 0 + } + + /** Count one call if it fits under `limit`; false when the day's quota is spent. */ + take(subject: string, limit: number, now = Date.now()): boolean { + const d = day(now) + return this.db.transaction(() => { + const n = this.used(subject, now) + if (n >= limit) return false + this.db.query('INSERT INTO usage (subject, day, n) VALUES (?, ?, 1) ON CONFLICT(subject, day) DO UPDATE SET n = n + 1').run(subject, d) + return true + })() + } + + addPayment(p: { ref: string; keyId: string; sessionId: string; email: string; usd: number; days: number }, now = Date.now()): void { + this.db.query('INSERT INTO payments (ref, key_id, session_id, email, usd, days, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)').run(p.ref, p.keyId, p.sessionId, p.email, p.usd, p.days, now) + } + + payment(by: { sessionId?: string | null; ref?: string | null }): Payment | null { + const r: any = by.sessionId + ? this.db.query('SELECT * FROM payments WHERE session_id = ?').get(by.sessionId) + : by.ref + ? this.db.query('SELECT * FROM payments WHERE ref = ?').get(by.ref) + : null + return r ? { ref: r.ref, keyId: r.key_id, sessionId: r.session_id, days: r.days, status: r.status } : null + } + + /** Mark paid once; true only for the call that settled it. */ + settle(ref: string, paymentId: string | null, now = Date.now()): boolean { + const r = this.db.query("UPDATE payments SET status = 'paid', settled_at = ?, payment_id = COALESCE(?, payment_id) WHERE ref = ? AND status != 'paid'").run(now, paymentId, ref) + return r.changes === 1 + } + + setStatus(ref: string, status: string): void { + this.db.query("UPDATE payments SET status = ? WHERE ref = ? AND status != 'paid'").run(status, ref) + } + + stats(): { keys: number; pro: number; paid: number; callsToday: number } { + const now = Date.now() + const q = (sql: string, ...a: any[]) => (this.db.query(sql).get(...a) as any)?.n ?? 0 + return { + keys: q('SELECT COUNT(*) n FROM keys'), + pro: q('SELECT COUNT(*) n FROM keys WHERE pro_until > ?', now), + paid: q("SELECT COUNT(*) n FROM payments WHERE status = 'paid'"), + callsToday: q("SELECT COALESCE(SUM(n),0) n FROM usage WHERE day = ? AND subject NOT LIKE 'mint:%'", day(now)), + } + } +} diff --git a/cloud/test/app.test.ts b/cloud/test/app.test.ts new file mode 100644 index 0000000..8e9b23a --- /dev/null +++ b/cloud/test/app.test.ts @@ -0,0 +1,167 @@ +import { describe, expect, test } from 'bun:test' +import { signWebhook } from '@profullstack/coinpay-onboard' +import { createApp, configFromEnv, type Config } from '../src/app.ts' +import { Store } from '../src/store.ts' + +// SK33P_BIN must point at a built sk33p (e.g. a release binary). +const BIN = process.env.SK33P_BIN ?? 'sk33p' +const SECRET = 'whsec_test' + +function setup(over: Partial = {}) { + const sessions: any[] = [] + const fakeFetch = (async (url: string, init: any) => { + const body = JSON.parse(init.body) + sessions.push({ url, body }) + return new Response(JSON.stringify({ session: { id: `cs_${sessions.length}`, url: `https://coinpayportal.com/checkout/cs_${sessions.length}`, methods: ['BTC', 'paypal'] } }), { status: 201, headers: { 'content-type': 'application/json' } }) + }) as unknown as typeof fetch + const cfg: Config = { + ...configFromEnv({ SK33P_BIN: BIN, SANDBOX: process.env.SANDBOX ?? '1', ORIGIN: 'https://sk33p.test' }), + coinpay: { baseUrl: 'https://coinpayportal.com', apiKey: 'cp_test', businessId: 'biz', webhookSecret: SECRET, fetch: fakeFetch }, + ...over, + } + const store = new Store() + const app = createApp(store, cfg) + const req = (path: string, init: RequestInit & { ip?: string; key?: string } = {}) => { + const headers = new Headers(init.headers) + headers.set('x-forwarded-for', init.ip ?? '203.0.113.7') + if (init.key) headers.set('authorization', `Bearer ${init.key}`) + return app.request(path, { ...init, headers }) + } + const json = (path: string, body: unknown, o: { ip?: string; key?: string } = {}) => req(path, { method: 'POST', body: JSON.stringify(body), headers: { 'content-type': 'application/json' }, ...o }) + return { app, store, cfg, req, json, sessions } +} + +describe('engine API', () => { + test('eval works without a key and reports remaining calls', async () => { + const { json } = setup() + const r = await json('/api/v1/eval', { formulas: ['=SUM(1,2,3)', '=PMT(5%/12,360,-300000)', 'POWER(2,10)'] }) + expect(r.status).toBe(200) + expect(r.headers.get('x-sk33p-plan')).toBe('anon') + const j: any = await r.json() + expect(j.results.map((x: any) => x.value)).toEqual(['6', '1610.46486903642', '1024']) + expect(r.headers.get('x-sk33p-remaining')).toBe('9') + }) + + test('anonymous quota answers 402 with the next step', async () => { + const { json, cfg } = setup() + for (let i = 0; i < cfg.limits.anon.calls; i++) expect((await json('/api/v1/eval', { formulas: ['=1'] })).status).toBe(200) + const r = await json('/api/v1/eval', { formulas: ['=1'] }) + expect(r.status).toBe(402) + const j: any = await r.json() + expect(j.next.web).toBe('https://sk33p.test/key') + // Another address still has its own quota. + expect((await json('/api/v1/eval', { formulas: ['=1'] }, { ip: '198.51.100.9' })).status).toBe(200) + }) + + test('write a new xlsx, read it back, list sheets, convert to csv (JSON and raw)', async () => { + const { json, req } = setup() + const { key } = (await (await json('/api/v1/keys', { email: 'a@example.com' })).json()) as any + const w: any = await (await json('/api/v1/write', { name: 'budget.xlsx', cells: { A1: 'qty', B1: 'price', A2: '4', B2: '12.5', C2: '=A2*B2' } }, { key })).json() + expect(w.file.name).toBe('budget.xlsx') + expect(w.file.bytes).toBeGreaterThan(100) + const file = { name: 'budget.xlsx', data: w.file.data } + const rd: any = await (await json('/api/v1/read', { file, range: 'A1:C2' }, { key })).json() + expect(JSON.stringify(rd.result)).toContain('50') + const sh: any = await (await json('/api/v1/sheets', { file }, { key })).json() + expect(JSON.stringify(sh.sheets).length).toBeGreaterThan(2) + const cv: any = await (await json('/api/v1/convert', { file, to: 'csv' }, { key })).json() + expect(cv.file.name).toBe('budget.csv') + expect(Buffer.from(cv.file.data, 'base64').toString()).toContain('qty') + const raw = await req('/api/v1/convert?name=budget.xlsx&to=csv', { method: 'POST', body: Buffer.from(w.file.data, 'base64'), headers: { 'content-type': 'application/octet-stream' }, key }) + expect(raw.status).toBe(200) + expect(raw.headers.get('content-disposition')).toContain('budget.csv') + expect(await raw.text()).toContain('50') + }) + + test('rejects path tricks and unknown keys', async () => { + const { json } = setup() + const bad = await json('/api/v1/read', { file: { name: '../../etc/passwd', data: 'eA==' } }) + expect(bad.status).toBe(400) + const unk = await json('/api/v1/eval', { formulas: ['=1'] }, { key: 'sk33p_nope' }) + expect(unk.status).toBe(401) + }) +}) + +describe('keys and Pro', () => { + test('mint a key, upgrade through CoinPay, webhook turns it Pro', async () => { + const { json, req, sessions, store } = setup() + const mint = await json('/api/v1/keys', { email: 'Buyer@Example.com' }) + expect(mint.status).toBe(201) + const { key } = (await mint.json()) as any + expect(key).toStartWith('sk33p_') + let me: any = await (await req('/api/v1/me', { key })).json() + expect(me.plan).toBe('free') + expect(me.email).toBe('buyer@example.com') + + const up: any = await (await json('/api/v1/upgrade', {}, { key })).json() + expect(up.checkout_url).toContain('coinpayportal.com/checkout/cs_1') + expect(sessions[0].body.amount).toBe(9) + expect(sessions[0].body.customer_email).toBe('buyer@example.com') + + const event = JSON.stringify({ id: 'evt_1', type: 'payment.confirmed', data: { payment_id: 'pay_1', status: 'confirmed', checkout_session_id: up.checkout_session_id, metadata: {} } }) + const forged = await req('/hooks/coinpay', { method: 'POST', body: event, headers: { 'x-coinpay-signature': signWebhook(event, 'wrong') } }) + expect(forged.status).toBe(401) + const ok = await req('/hooks/coinpay', { method: 'POST', body: event, headers: { 'x-coinpay-signature': signWebhook(event, SECRET) } }) + expect(ok.status).toBe(200) + // A replay settles nothing twice. + await req('/hooks/coinpay', { method: 'POST', body: event, headers: { 'x-coinpay-signature': signWebhook(event, SECRET) } }) + me = await (await req('/api/v1/me', { key })).json() + expect(me.plan).toBe('pro') + const days = (Date.parse(me.pro_until) - Date.now()) / 86_400_000 + expect(days).toBeGreaterThan(29.9) + expect(days).toBeLessThan(30.1) + expect(store.stats().paid).toBe(1) + }) + + test('mint limit per address and email validation', async () => { + const { json, cfg } = setup() + expect((await json('/api/v1/keys', { email: 'nope' })).status).toBe(400) + for (let i = 0; i < cfg.mintsPerIp; i++) expect((await json('/api/v1/keys', { email: `u${i}@example.com` })).status).toBe(201) + expect((await json('/api/v1/keys', { email: 'more@example.com' })).status).toBe(400) + }) + + test('web forms: /key shows the key once, /upgrade redirects to CoinPay', async () => { + const { req } = setup() + const page = await req('/key', { method: 'POST', body: new URLSearchParams({ email: 'web@example.com' }), headers: { 'content-type': 'application/x-www-form-urlencoded' } }) + const html = await page.text() + const key = /sk33p_[A-Za-z0-9_-]{32}/.exec(html)?.[0] + expect(key).toBeTruthy() + const up = await req('/upgrade', { method: 'POST', body: new URLSearchParams({ key: key! }), headers: { 'content-type': 'application/x-www-form-urlencoded' } }) + expect(up.status).toBe(303) + expect(up.headers.get('location')).toContain('coinpayportal.com/checkout/') + }) +}) + +describe('MCP', () => { + test('initialize, tools/list, tools/call, usage', async () => { + const { json } = setup() + const rpc = async (method: string, params: unknown = {}, key?: string) => (await (await json('/mcp', { jsonrpc: '2.0', id: 1, method, params }, { key })).json()) as any + expect((await rpc('initialize', { protocolVersion: '2025-06-18' })).result.serverInfo.name).toBe('sk33p') + const names = (await rpc('tools/list')).result.tools.map((t: any) => t.name) + expect(names).toEqual(['eval', 'read_range', 'write_cells', 'list_sheets', 'convert', 'usage', 'upgrade']) + const call = await rpc('tools/call', { name: 'eval', arguments: { formulas: ['=TEXTJOIN("-",TRUE,"a","b")'] } }) + expect(call.result.structuredContent.results[0].value).toBe('a-b') + const usage = await rpc('tools/call', { name: 'usage', arguments: {} }) + expect(usage.result.structuredContent.calls_today).toBe(1) + const up = await rpc('tools/call', { name: 'upgrade', arguments: {} }) + expect(up.result.isError).toBe(true) + const note = await json('/mcp', { jsonrpc: '2.0', method: 'notifications/initialized' }) + expect(note.status).toBe(202) + }) +}) + +describe('pages', () => { + test('home, docs, llms.txt, ring descriptor, healthz', async () => { + const { req } = setup() + const home = await (await req('/')).text() + expect(home).toContain('Pricing') + expect(home).toContain('$9') + expect(home).toContain('data-webmcp') + expect(await (await req('/docs')).text()).toContain('/api/v1/convert') + expect(await (await req('/docs.md')).text()).toContain('## MCP') + expect(await (await req('/llms.txt')).text()).toContain('# sk33p') + expect((await req('/.well-known/openwebring.json')).status).toBe(200) + expect(await (await req('/healthz')).json()).toEqual({ ok: true }) + expect((await req('/nope')).status).toBe(404) + }) +}) From 8e328cbf881e3558aeff69239f4e471fb683ff29 Mon Sep 17 00:00:00 2001 From: Anthony Ettinger Date: Mon, 30 Nov 2026 14:43:15 +0000 Subject: [PATCH 2/4] README: hosted API and MCP at sk33p.pwa.pit.world Co-Authored-By: Claude Opus 5.5 --- README.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/README.md b/README.md index a9242ea..62ba3ed 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,18 @@ TUI keys: arrows or hjkl move, type or `=` to enter, Enter/F2 edit, Tab commit right, Del clear, Ctrl+Z / Ctrl+Y undo and redo, `[` `]` switch sheet, `<` `>` column width, `g` go to, `:w file.xlsx` save as, `:q` quit, `?` all keys. +## Hosted API and MCP + +The same engine over HTTPS and remote MCP at **https://sk33p.pwa.pit.world**: evaluate +formulas, read ranges, write cells and convert workbooks with nothing installed. +Free tier (a key by email, 100 calls a day); Pro is $9 per 30 days via CoinPay. +Docs: https://sk33p.pwa.pit.world/docs. Source in `cloud/`. + +```sh +curl -s https://sk33p.pwa.pit.world/api/v1/eval -H 'content-type: application/json' \ + -d '{"formulas":["=PMT(5%/12,360,-300000)"]}' +``` + ## Engine notes - The formula parser has no `^` operator: write `POWER(A1,2)`. From 8069a392f4b4eb3a8ddd32ccb65bb0340d0aa958 Mon Sep 17 00:00:00 2001 From: Anthony Ettinger Date: Mon, 30 Nov 2026 16:21:30 +0000 Subject: [PATCH 3/4] ci: stop caching target/ (restored engine stamps without their CMake cache) Error: could not load cache on every platform when the cache hit: target/ carries ExternalProject stamps but each sub-build's CMakeCache lives in the engine submodule tree. Cache only the cargo registry and git checkouts. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1993d78..b628949 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -44,11 +44,13 @@ jobs: - uses: dtolnay/rust-toolchain@stable - uses: actions/cache@v4 with: + # Not target/: it holds the engine's ExternalProject stamps, but each + # sub-build's CMakeCache lives in the engine submodule tree, so a + # restored target/ fails with "Error: could not load cache". path: | ~/.cargo/registry ~/.cargo/git - target - key: ${{ matrix.os }}-cargo-${{ hashFiles('Cargo.lock', 'engine', 'shim/**', 'patches/**', 'build.rs') }} + key: ${{ matrix.os }}-cargo-registry-${{ hashFiles('Cargo.lock') }} - name: build run: cargo build --release --all-targets -vv 2>&1 | grep -vE "^\s*$|warning:" | tail -200 env: From adb95ea153575d768d64423376e542b11d9a1725 Mon Sep 17 00:00:00 2001 From: Anthony Ettinger Date: Mon, 30 Nov 2026 16:37:35 +0000 Subject: [PATCH 4/4] cloud: homepage demo uses FV, not IRR on an inline array The engine's IRR only takes a range, so the default demo showed '#ARG! IRR: values must be a range'. ROUND(FV(5%/12,120,-200),2) = 31056.46. Co-Authored-By: Claude Opus 5.5 --- cloud/src/page.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cloud/src/page.ts b/cloud/src/page.ts index 61b3d1f..50b9046 100644 --- a/cloud/src/page.ts +++ b/cloud/src/page.ts @@ -109,7 +109,7 @@ export function homePage(cfg: Config): string {
No ^ operator in this engine: use POWER().