create-disposabl-app 0.3.2 → 0.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +31 -6
- package/dist/templates/default/apps/web/src/routeTree.gen.ts +49 -5
- package/dist/templates/default/apps/web/src/router/_authenticated/dashboard.api-keys.tsx +154 -0
- package/dist/templates/default/apps/web/src/router/_authenticated/dashboard.tsx +23 -5
- package/dist/templates/default/bun.lock +237 -39
- package/dist/templates/default/disposabl.json +3 -1
- package/dist/templates/default/package.json +4 -2
- package/dist/templates/default/packages/backend/generate.ts +123 -0
- package/dist/templates/default/packages/backend/generated/openapi.json +190 -0
- package/dist/templates/default/packages/backend/generated/platforms.ts +3 -0
- package/dist/templates/default/packages/backend/package.json +3 -1
- package/dist/templates/default/packages/cli/README.md +17 -0
- package/dist/templates/default/packages/cli/auth.ts +301 -0
- package/dist/templates/default/packages/cli/build.ts +9 -0
- package/dist/templates/default/packages/cli/index.ts +146 -0
- package/dist/templates/default/packages/cli/package.json +35 -0
- package/dist/templates/default/packages/cli/tsconfig.json +15 -0
- package/dist/templates/default/packages/disposabl-kit/platforms.ts +4 -4
- package/dist/templates/default/packages/disposabl-kit/server/http.ts +44 -8
- package/dist/templates/default/packages/disposabl-kit/server/lib/platform-spec.ts +94 -5
- package/dist/templates/default/packages/sdk/README.md +20 -0
- package/dist/templates/default/packages/sdk/openapi-ts.config.ts +10 -0
- package/dist/templates/default/packages/sdk/package.json +31 -0
- package/dist/templates/default/packages/sdk/src/config.ts +11 -0
- package/dist/templates/default/packages/sdk/src/generated/client/client.gen.ts +300 -0
- package/dist/templates/default/packages/sdk/src/generated/client/index.ts +27 -0
- package/dist/templates/default/packages/sdk/src/generated/client/types.gen.ts +238 -0
- package/dist/templates/default/packages/sdk/src/generated/client/utils.gen.ts +337 -0
- package/dist/templates/default/packages/sdk/src/generated/client.gen.ts +28 -0
- package/dist/templates/default/packages/sdk/src/generated/core/auth.gen.ts +49 -0
- package/dist/templates/default/packages/sdk/src/generated/core/bodySerializer.gen.ts +96 -0
- package/dist/templates/default/packages/sdk/src/generated/core/params.gen.ts +188 -0
- package/dist/templates/default/packages/sdk/src/generated/core/pathSerializer.gen.ts +186 -0
- package/dist/templates/default/packages/sdk/src/generated/core/queryKeySerializer.gen.ts +134 -0
- package/dist/templates/default/packages/sdk/src/generated/core/serverSentEvents.gen.ts +265 -0
- package/dist/templates/default/packages/sdk/src/generated/core/types.gen.ts +126 -0
- package/dist/templates/default/packages/sdk/src/generated/core/utils.gen.ts +146 -0
- package/dist/templates/default/packages/sdk/src/generated/index.ts +18 -0
- package/dist/templates/default/packages/sdk/src/generated/sdk.gen.ts +82 -0
- package/dist/templates/default/packages/sdk/src/generated/types.gen.ts +134 -0
- package/dist/templates/default/packages/sdk/src/index.ts +3 -0
- package/dist/templates/default/packages/sdk/tsconfig.build.json +10 -0
- package/dist/templates/default/packages/sdk/tsconfig.json +12 -0
- package/dist/templates/default/turbo.json +9 -0
- package/package.json +1 -1
|
@@ -2,12 +2,14 @@
|
|
|
2
2
|
"name": "disposabl-dev",
|
|
3
3
|
"private": true,
|
|
4
4
|
"scripts": {
|
|
5
|
-
"check": "turbo run typecheck lint && bun fmt --check && bun test --pass-with-no-tests",
|
|
5
|
+
"check": "bun run generate && turbo run typecheck lint && bun fmt --check && bun test --pass-with-no-tests",
|
|
6
6
|
"build": "turbo build",
|
|
7
7
|
"dev": "turbo dev",
|
|
8
8
|
"lint": "turbo lint",
|
|
9
9
|
"format": "turbo format",
|
|
10
|
-
"typecheck": "turbo typecheck"
|
|
10
|
+
"typecheck": "turbo typecheck",
|
|
11
|
+
"generate": "bun run --cwd packages/backend generate",
|
|
12
|
+
"prebuild": "bun run generate"
|
|
11
13
|
},
|
|
12
14
|
"devDependencies": {
|
|
13
15
|
"prettier": "^3.9.10",
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { watch } from "node:fs";
|
|
2
|
+
import { readdir, readFile, mkdir, writeFile } from "node:fs/promises";
|
|
3
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { spawnSync } from "node:child_process";
|
|
6
|
+
import {
|
|
7
|
+
createOpenApi,
|
|
8
|
+
createPlatforms,
|
|
9
|
+
} from "../disposabl-kit/server/lib/platform-spec";
|
|
10
|
+
|
|
11
|
+
import config from "../../disposabl.json";
|
|
12
|
+
|
|
13
|
+
const root = fileURLToPath(new URL(".", import.meta.url));
|
|
14
|
+
const convex = join(root, "convex");
|
|
15
|
+
const output = join(root, "generated");
|
|
16
|
+
const canonical = (value: unknown): string =>
|
|
17
|
+
JSON.stringify(value, (_, item) =>
|
|
18
|
+
item && typeof item === "object" && !Array.isArray(item)
|
|
19
|
+
? Object.fromEntries(
|
|
20
|
+
Object.entries(item).sort(([a], [b]) => a.localeCompare(b)),
|
|
21
|
+
)
|
|
22
|
+
: item,
|
|
23
|
+
);
|
|
24
|
+
|
|
25
|
+
async function writeChanged(path: string, text: string) {
|
|
26
|
+
if ((await readFile(path, "utf8").catch(() => "")) !== text)
|
|
27
|
+
await writeFile(path, text);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Discover opt-in modules, validate the contract, then update both transports together. */
|
|
31
|
+
export async function generate(acceptBreaking = false) {
|
|
32
|
+
const files = await readdir(convex, { recursive: true });
|
|
33
|
+
const modules: Record<string, Record<string, unknown>> = {};
|
|
34
|
+
for (const file of files.sort()) {
|
|
35
|
+
if (
|
|
36
|
+
file.startsWith("_generated/") ||
|
|
37
|
+
!file.endsWith(".ts") ||
|
|
38
|
+
file.endsWith(".d.ts")
|
|
39
|
+
)
|
|
40
|
+
continue;
|
|
41
|
+
const source = await readFile(join(convex, file), "utf8");
|
|
42
|
+
if (!/\bplatforms\s*:\s*true\b/.test(source)) continue;
|
|
43
|
+
if (/^[\s;]*["']use node["']/.test(source))
|
|
44
|
+
throw new Error(
|
|
45
|
+
`${file}: platform validators must be in a default-runtime module; delegate Node work through an internal action.`,
|
|
46
|
+
);
|
|
47
|
+
modules[file.slice(0, -3)] = await import(
|
|
48
|
+
pathToFileURL(join(convex, file)).href
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
const next = createOpenApi(createPlatforms(modules).spec);
|
|
52
|
+
const previous = await readFile(join(output, "openapi.json"), "utf8")
|
|
53
|
+
.then(JSON.parse)
|
|
54
|
+
.catch((error) => {
|
|
55
|
+
if (error.code !== "ENOENT") throw error;
|
|
56
|
+
return null;
|
|
57
|
+
});
|
|
58
|
+
const changes = previous
|
|
59
|
+
? Object.keys(previous.paths).filter(
|
|
60
|
+
(path) =>
|
|
61
|
+
canonical(previous.paths[path]) !== canonical(next.paths[path]),
|
|
62
|
+
)
|
|
63
|
+
: [];
|
|
64
|
+
if (changes.length && !acceptBreaking)
|
|
65
|
+
throw new Error(
|
|
66
|
+
`Contract changed or removed: ${changes.join(", ")}. Review the changes, then run bun run generate --accept-breaking to accept a major version.`,
|
|
67
|
+
);
|
|
68
|
+
if (previous) {
|
|
69
|
+
const [major, minor, patch] = previous.info.version.split(".").map(Number);
|
|
70
|
+
next.info.version = changes.length
|
|
71
|
+
? `${major + 1}.0.0`
|
|
72
|
+
: canonical(previous.paths) !== canonical(next.paths)
|
|
73
|
+
? `${major}.${minor + 1}.0`
|
|
74
|
+
: `${major}.${minor}.${patch}`;
|
|
75
|
+
}
|
|
76
|
+
const paths = Object.keys(modules);
|
|
77
|
+
const registry =
|
|
78
|
+
"// Generated by bun run generate. Do not edit.\n" +
|
|
79
|
+
paths
|
|
80
|
+
.map(
|
|
81
|
+
(path, index) =>
|
|
82
|
+
`import * as m${index} from ${JSON.stringify(`../convex/${path}`)};`,
|
|
83
|
+
)
|
|
84
|
+
.join("\n") +
|
|
85
|
+
`\nexport default {${paths.map((path, index) => `${JSON.stringify(path)}: m${index}`).join(",")}};\n`;
|
|
86
|
+
await mkdir(output, { recursive: true });
|
|
87
|
+
await writeChanged(
|
|
88
|
+
join(output, "openapi.json"),
|
|
89
|
+
JSON.stringify(next, null, 2) + "\n",
|
|
90
|
+
);
|
|
91
|
+
await writeChanged(join(output, "platforms.ts"), registry);
|
|
92
|
+
const formatted = spawnSync(process.execPath, ["fmt", output], {
|
|
93
|
+
stdio: "pipe",
|
|
94
|
+
});
|
|
95
|
+
if (formatted.status !== 0)
|
|
96
|
+
throw new Error("Could not format generated contract");
|
|
97
|
+
if (config.platforms.includes("typescript-sdk")) {
|
|
98
|
+
const sdk = spawnSync(process.execPath, ["run", "generate"], {
|
|
99
|
+
cwd: join(root, "../sdk"),
|
|
100
|
+
stdio: "inherit",
|
|
101
|
+
});
|
|
102
|
+
if (sdk.status !== 0) throw new Error("SDK generation failed");
|
|
103
|
+
}
|
|
104
|
+
console.log(
|
|
105
|
+
`Generated ${Object.keys(next.paths).length} operations, contract ${next.info.version}.`,
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
if (import.meta.main) {
|
|
110
|
+
if (process.argv.includes("--watch")) {
|
|
111
|
+
const run = () =>
|
|
112
|
+
spawnSync(process.execPath, [fileURLToPath(import.meta.url)], {
|
|
113
|
+
stdio: "inherit",
|
|
114
|
+
});
|
|
115
|
+
run();
|
|
116
|
+
let timer: ReturnType<typeof setTimeout>;
|
|
117
|
+
watch(convex, { recursive: true }, (_, file) => {
|
|
118
|
+
if (!file?.endsWith(".ts")) return;
|
|
119
|
+
clearTimeout(timer);
|
|
120
|
+
timer = setTimeout(run, 200);
|
|
121
|
+
});
|
|
122
|
+
} else await generate(process.argv.includes("--accept-breaking"));
|
|
123
|
+
}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
{
|
|
2
|
+
"openapi": "3.1.0",
|
|
3
|
+
"info": {
|
|
4
|
+
"title": "Application API",
|
|
5
|
+
"version": "0.1.0"
|
|
6
|
+
},
|
|
7
|
+
"security": [
|
|
8
|
+
{
|
|
9
|
+
"bearerAuth": []
|
|
10
|
+
}
|
|
11
|
+
],
|
|
12
|
+
"components": {
|
|
13
|
+
"securitySchemes": {
|
|
14
|
+
"bearerAuth": {
|
|
15
|
+
"type": "http",
|
|
16
|
+
"scheme": "bearer"
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
"paths": {
|
|
21
|
+
"/api/todos/create": {
|
|
22
|
+
"post": {
|
|
23
|
+
"operationId": "todosCreate",
|
|
24
|
+
"x-convex-function": "todos/internal:create",
|
|
25
|
+
"requestBody": {
|
|
26
|
+
"required": true,
|
|
27
|
+
"content": {
|
|
28
|
+
"application/json": {
|
|
29
|
+
"schema": {
|
|
30
|
+
"type": "object",
|
|
31
|
+
"properties": {
|
|
32
|
+
"title": {
|
|
33
|
+
"type": "string"
|
|
34
|
+
}
|
|
35
|
+
},
|
|
36
|
+
"required": ["title"],
|
|
37
|
+
"additionalProperties": false
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
"responses": {
|
|
43
|
+
"200": {
|
|
44
|
+
"description": "Success",
|
|
45
|
+
"content": {
|
|
46
|
+
"application/json": {
|
|
47
|
+
"schema": {
|
|
48
|
+
"type": "string",
|
|
49
|
+
"description": "ID of a document in \"todos\""
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
"400": {
|
|
55
|
+
"description": "Invalid arguments"
|
|
56
|
+
},
|
|
57
|
+
"401": {
|
|
58
|
+
"description": "Authentication required"
|
|
59
|
+
},
|
|
60
|
+
"403": {
|
|
61
|
+
"description": "Insufficient scope"
|
|
62
|
+
},
|
|
63
|
+
"500": {
|
|
64
|
+
"description": "Internal error"
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
},
|
|
69
|
+
"/api/todos/get": {
|
|
70
|
+
"get": {
|
|
71
|
+
"operationId": "todosGet",
|
|
72
|
+
"x-convex-function": "todos/internal:get",
|
|
73
|
+
"parameters": [
|
|
74
|
+
{
|
|
75
|
+
"name": "id",
|
|
76
|
+
"in": "query",
|
|
77
|
+
"required": true,
|
|
78
|
+
"content": {
|
|
79
|
+
"application/json": {
|
|
80
|
+
"schema": {
|
|
81
|
+
"type": "string",
|
|
82
|
+
"description": "ID of a document in \"todos\""
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
],
|
|
88
|
+
"responses": {
|
|
89
|
+
"200": {
|
|
90
|
+
"description": "Success",
|
|
91
|
+
"content": {
|
|
92
|
+
"application/json": {
|
|
93
|
+
"schema": {
|
|
94
|
+
"anyOf": [
|
|
95
|
+
{
|
|
96
|
+
"type": "object",
|
|
97
|
+
"properties": {
|
|
98
|
+
"userId": {
|
|
99
|
+
"type": "string"
|
|
100
|
+
},
|
|
101
|
+
"title": {
|
|
102
|
+
"type": "string"
|
|
103
|
+
},
|
|
104
|
+
"_id": {
|
|
105
|
+
"type": "string",
|
|
106
|
+
"description": "ID of a document in \"todos\""
|
|
107
|
+
},
|
|
108
|
+
"_creationTime": {
|
|
109
|
+
"type": "number"
|
|
110
|
+
}
|
|
111
|
+
},
|
|
112
|
+
"required": ["userId", "title", "_id", "_creationTime"],
|
|
113
|
+
"additionalProperties": false
|
|
114
|
+
},
|
|
115
|
+
{
|
|
116
|
+
"type": "null"
|
|
117
|
+
}
|
|
118
|
+
]
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
},
|
|
123
|
+
"400": {
|
|
124
|
+
"description": "Invalid arguments"
|
|
125
|
+
},
|
|
126
|
+
"401": {
|
|
127
|
+
"description": "Authentication required"
|
|
128
|
+
},
|
|
129
|
+
"403": {
|
|
130
|
+
"description": "Insufficient scope"
|
|
131
|
+
},
|
|
132
|
+
"500": {
|
|
133
|
+
"description": "Internal error"
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
},
|
|
138
|
+
"/api/todos/list": {
|
|
139
|
+
"get": {
|
|
140
|
+
"operationId": "todosList",
|
|
141
|
+
"x-convex-function": "todos/internal:list",
|
|
142
|
+
"parameters": [],
|
|
143
|
+
"responses": {
|
|
144
|
+
"200": {
|
|
145
|
+
"description": "Success",
|
|
146
|
+
"content": {
|
|
147
|
+
"application/json": {
|
|
148
|
+
"schema": {
|
|
149
|
+
"type": "array",
|
|
150
|
+
"items": {
|
|
151
|
+
"type": "object",
|
|
152
|
+
"properties": {
|
|
153
|
+
"userId": {
|
|
154
|
+
"type": "string"
|
|
155
|
+
},
|
|
156
|
+
"title": {
|
|
157
|
+
"type": "string"
|
|
158
|
+
},
|
|
159
|
+
"_id": {
|
|
160
|
+
"type": "string",
|
|
161
|
+
"description": "ID of a document in \"todos\""
|
|
162
|
+
},
|
|
163
|
+
"_creationTime": {
|
|
164
|
+
"type": "number"
|
|
165
|
+
}
|
|
166
|
+
},
|
|
167
|
+
"required": ["userId", "title", "_id", "_creationTime"],
|
|
168
|
+
"additionalProperties": false
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
},
|
|
174
|
+
"400": {
|
|
175
|
+
"description": "Invalid arguments"
|
|
176
|
+
},
|
|
177
|
+
"401": {
|
|
178
|
+
"description": "Authentication required"
|
|
179
|
+
},
|
|
180
|
+
"403": {
|
|
181
|
+
"description": "Insufficient scope"
|
|
182
|
+
},
|
|
183
|
+
"500": {
|
|
184
|
+
"description": "Internal error"
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
@@ -3,7 +3,9 @@
|
|
|
3
3
|
"private": true,
|
|
4
4
|
"version": "0.0.0",
|
|
5
5
|
"scripts": {
|
|
6
|
-
"
|
|
6
|
+
"generate": "bun generate.ts",
|
|
7
|
+
"generate:watch": "bun generate.ts --watch",
|
|
8
|
+
"predev": "bun run generate && bun x --no-install --package @convex-dev/auth auth --keys-only",
|
|
7
9
|
"dev": "convex dev",
|
|
8
10
|
"logs": "convex logs",
|
|
9
11
|
"typecheck": "tsc -p convex",
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Disposabl CLI
|
|
2
|
+
|
|
3
|
+
The CLI reads your app's `/openapi.json` and calls its API directly. It does not depend on the SDK.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
export DISPOSABL_API_URL=https://your-deployment.convex.site
|
|
7
|
+
npx @disposabl/cli login
|
|
8
|
+
npx @disposabl/cli todos create --title 'Ship the app'
|
|
9
|
+
npx @disposabl/cli todos list
|
|
10
|
+
npx @disposabl/cli logout
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
`--url` overrides the environment. `login --no-browser` prints the authorization URL for manual opening. OAuth uses the app's existing MCP authorization server, PKCE S256, a random loopback callback port and state, rotating refresh tokens, and server-side revocation. Login requires the API platform; MCP tool exposure is optional.
|
|
14
|
+
|
|
15
|
+
Credentials are stored per API origin under `~/.config/disposabl` (directory mode 0700, files 0600). `DISPOSABL_CONFIG_DIR` overrides that directory. Credentials are not encrypted at rest; keep the account and disk protected. A lock serializes refreshes across processes. `DISPOSABL_API_KEY` supplies a dashboard-created key for automation and bypasses OAuth. Logout revokes stored OAuth credentials; revoke API keys from the dashboard.
|
|
16
|
+
|
|
17
|
+
Strings are plain option values. Other argument types use JSON, for example `--limit 10` or `--filters '{"done":false}'`. Use `todos --help` for commands exposed by your app.
|
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
import { lock } from "proper-lockfile";
|
|
2
|
+
import {
|
|
3
|
+
auth,
|
|
4
|
+
type OAuthClientProvider,
|
|
5
|
+
} from "@modelcontextprotocol/sdk/client/auth.js";
|
|
6
|
+
import type {
|
|
7
|
+
OAuthClientInformationMixed,
|
|
8
|
+
OAuthTokens,
|
|
9
|
+
} from "@modelcontextprotocol/sdk/shared/auth.js";
|
|
10
|
+
import { createServer } from "node:http";
|
|
11
|
+
import { randomBytes, createHash } from "node:crypto";
|
|
12
|
+
import {
|
|
13
|
+
mkdir,
|
|
14
|
+
readFile,
|
|
15
|
+
writeFile,
|
|
16
|
+
rename,
|
|
17
|
+
rm,
|
|
18
|
+
chmod,
|
|
19
|
+
} from "node:fs/promises";
|
|
20
|
+
import { homedir } from "node:os";
|
|
21
|
+
import { join } from "node:path";
|
|
22
|
+
import { spawn } from "node:child_process";
|
|
23
|
+
|
|
24
|
+
type Session = {
|
|
25
|
+
client?: OAuthClientInformationMixed;
|
|
26
|
+
tokens?: OAuthTokens;
|
|
27
|
+
expiresAt?: number;
|
|
28
|
+
redirectUrl?: string;
|
|
29
|
+
};
|
|
30
|
+
const directory = () =>
|
|
31
|
+
process.env.DISPOSABL_CONFIG_DIR || join(homedir(), ".config", "disposabl");
|
|
32
|
+
const sessionPath = (url: string) =>
|
|
33
|
+
join(directory(), `${createHash("sha256").update(url).digest("hex")}.json`);
|
|
34
|
+
export function apiUrl(value: string) {
|
|
35
|
+
const url = new URL(value);
|
|
36
|
+
if (
|
|
37
|
+
url.protocol !== "https:" &&
|
|
38
|
+
!(
|
|
39
|
+
url.protocol === "http:" &&
|
|
40
|
+
["127.0.0.1", "localhost", "[::1]"].includes(url.hostname)
|
|
41
|
+
)
|
|
42
|
+
)
|
|
43
|
+
throw new Error("Use HTTPS, or HTTP on loopback for local development.");
|
|
44
|
+
if (
|
|
45
|
+
url.username ||
|
|
46
|
+
url.password ||
|
|
47
|
+
url.search ||
|
|
48
|
+
url.hash ||
|
|
49
|
+
url.pathname !== "/"
|
|
50
|
+
)
|
|
51
|
+
throw new Error("Use the API origin without a path or credentials.");
|
|
52
|
+
return url.origin;
|
|
53
|
+
}
|
|
54
|
+
const fetchFor = (origin: string): typeof fetch =>
|
|
55
|
+
Object.assign(
|
|
56
|
+
async (
|
|
57
|
+
input: Parameters<typeof fetch>[0],
|
|
58
|
+
init?: Parameters<typeof fetch>[1],
|
|
59
|
+
) => {
|
|
60
|
+
const url = new URL(input instanceof Request ? input.url : input);
|
|
61
|
+
if (url.origin !== origin)
|
|
62
|
+
throw new Error(
|
|
63
|
+
"OAuth endpoint must belong to the configured API origin.",
|
|
64
|
+
);
|
|
65
|
+
return fetch(input, {
|
|
66
|
+
...init,
|
|
67
|
+
redirect: "error",
|
|
68
|
+
signal: init?.signal ?? AbortSignal.timeout(30_000),
|
|
69
|
+
});
|
|
70
|
+
},
|
|
71
|
+
{ preconnect: fetch.preconnect },
|
|
72
|
+
);
|
|
73
|
+
async function load(url: string): Promise<Session> {
|
|
74
|
+
try {
|
|
75
|
+
return JSON.parse(await readFile(sessionPath(url), "utf8"));
|
|
76
|
+
} catch (error) {
|
|
77
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return {};
|
|
78
|
+
throw error;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
async function save(url: string, session: Session) {
|
|
82
|
+
await mkdir(directory(), { recursive: true, mode: 0o700 });
|
|
83
|
+
await chmod(directory(), 0o700);
|
|
84
|
+
const temporary = `${sessionPath(url)}.${randomBytes(8).toString("hex")}`;
|
|
85
|
+
try {
|
|
86
|
+
await writeFile(temporary, JSON.stringify(session), {
|
|
87
|
+
mode: 0o600,
|
|
88
|
+
flag: "wx",
|
|
89
|
+
});
|
|
90
|
+
await rename(temporary, sessionPath(url));
|
|
91
|
+
} finally {
|
|
92
|
+
await rm(temporary, { force: true });
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
function provider(
|
|
96
|
+
url: string,
|
|
97
|
+
session: Session,
|
|
98
|
+
redirect: (url: URL) => void,
|
|
99
|
+
state?: string,
|
|
100
|
+
): OAuthClientProvider {
|
|
101
|
+
let verifier = "";
|
|
102
|
+
return {
|
|
103
|
+
redirectUrl: session.redirectUrl,
|
|
104
|
+
clientMetadata: {
|
|
105
|
+
client_name: "Disposabl CLI",
|
|
106
|
+
redirect_uris: session.redirectUrl ? [session.redirectUrl] : [],
|
|
107
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
108
|
+
response_types: ["code"],
|
|
109
|
+
token_endpoint_auth_method: "none",
|
|
110
|
+
},
|
|
111
|
+
state: () => state ?? "",
|
|
112
|
+
clientInformation: () => session.client,
|
|
113
|
+
saveClientInformation: (client) => {
|
|
114
|
+
session.client = client;
|
|
115
|
+
},
|
|
116
|
+
tokens: () => session.tokens,
|
|
117
|
+
saveTokens: async (tokens) => {
|
|
118
|
+
session.tokens = tokens;
|
|
119
|
+
session.expiresAt = tokens.expires_in
|
|
120
|
+
? Date.now() + tokens.expires_in * 1000
|
|
121
|
+
: 0;
|
|
122
|
+
await save(url, session);
|
|
123
|
+
},
|
|
124
|
+
saveCodeVerifier: (value) => {
|
|
125
|
+
verifier = value;
|
|
126
|
+
},
|
|
127
|
+
codeVerifier: () => verifier,
|
|
128
|
+
redirectToAuthorization: redirect,
|
|
129
|
+
invalidateCredentials: async (scope) => {
|
|
130
|
+
if (scope === "all" || scope === "tokens") {
|
|
131
|
+
delete session.tokens;
|
|
132
|
+
delete session.expiresAt;
|
|
133
|
+
}
|
|
134
|
+
if (scope === "all" || scope === "client") delete session.client;
|
|
135
|
+
if (scope === "all" || scope === "verifier") verifier = "";
|
|
136
|
+
await save(url, session);
|
|
137
|
+
},
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
async function unlockedLogin(url: string, openBrowser = true) {
|
|
141
|
+
const state = randomBytes(32).toString("base64url");
|
|
142
|
+
const server = createServer();
|
|
143
|
+
await new Promise<void>((resolve, reject) => {
|
|
144
|
+
server.once("error", reject);
|
|
145
|
+
server.listen(0, "127.0.0.1", resolve);
|
|
146
|
+
});
|
|
147
|
+
const address = server.address();
|
|
148
|
+
if (!address || typeof address === "string")
|
|
149
|
+
throw new Error("Could not bind the login callback.");
|
|
150
|
+
const session: Session = {
|
|
151
|
+
redirectUrl: `http://127.0.0.1:${address.port}/callback`,
|
|
152
|
+
};
|
|
153
|
+
const oauth = provider(
|
|
154
|
+
url,
|
|
155
|
+
session,
|
|
156
|
+
(authorizationUrl) => {
|
|
157
|
+
if (authorizationUrl.origin !== url)
|
|
158
|
+
throw new Error("Unexpected authorization server.");
|
|
159
|
+
console.error(`Open this URL to sign in:\n${authorizationUrl.href}`);
|
|
160
|
+
if (openBrowser) {
|
|
161
|
+
const command =
|
|
162
|
+
process.platform === "darwin"
|
|
163
|
+
? "open"
|
|
164
|
+
: process.platform === "win32"
|
|
165
|
+
? "rundll32"
|
|
166
|
+
: "xdg-open";
|
|
167
|
+
const args =
|
|
168
|
+
process.platform === "win32"
|
|
169
|
+
? ["url.dll,FileProtocolHandler", authorizationUrl.href]
|
|
170
|
+
: [authorizationUrl.href];
|
|
171
|
+
const child = spawn(command, args, { stdio: "ignore" });
|
|
172
|
+
child.on("error", () =>
|
|
173
|
+
console.error("Open the sign-in URL manually."),
|
|
174
|
+
);
|
|
175
|
+
child.unref();
|
|
176
|
+
}
|
|
177
|
+
},
|
|
178
|
+
state,
|
|
179
|
+
);
|
|
180
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
181
|
+
try {
|
|
182
|
+
const callback = new Promise<void>((resolve, reject) => {
|
|
183
|
+
timer = setTimeout(
|
|
184
|
+
() => reject(new Error("Login timed out. Start login again.")),
|
|
185
|
+
300_000,
|
|
186
|
+
);
|
|
187
|
+
server.on("request", async (request, response) => {
|
|
188
|
+
const callbackUrl = new URL(request.url ?? "/", session.redirectUrl);
|
|
189
|
+
const invalid =
|
|
190
|
+
request.method !== "GET" ||
|
|
191
|
+
request.headers.host !== `127.0.0.1:${address.port}` ||
|
|
192
|
+
callbackUrl.pathname !== "/callback" ||
|
|
193
|
+
callbackUrl.searchParams.getAll("state").length !== 1 ||
|
|
194
|
+
callbackUrl.searchParams.get("state") !== state;
|
|
195
|
+
if (invalid) {
|
|
196
|
+
response.writeHead(400).end("Invalid login callback.");
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
try {
|
|
200
|
+
if (callbackUrl.searchParams.get("iss")?.replace(/\/$/, "") !== url)
|
|
201
|
+
throw new Error("Unexpected OAuth issuer.");
|
|
202
|
+
const code = callbackUrl.searchParams.get("code");
|
|
203
|
+
if (
|
|
204
|
+
!code ||
|
|
205
|
+
callbackUrl.searchParams.getAll("code").length !== 1 ||
|
|
206
|
+
callbackUrl.searchParams.has("error")
|
|
207
|
+
)
|
|
208
|
+
throw new Error("Login was not approved.");
|
|
209
|
+
const result = await auth(oauth, {
|
|
210
|
+
serverUrl: `${url}/mcp`,
|
|
211
|
+
authorizationCode: code,
|
|
212
|
+
fetchFn: fetchFor(url),
|
|
213
|
+
});
|
|
214
|
+
if (result !== "AUTHORIZED")
|
|
215
|
+
throw new Error("Login did not complete.");
|
|
216
|
+
response
|
|
217
|
+
.writeHead(200, {
|
|
218
|
+
"Content-Type": "text/plain",
|
|
219
|
+
"Cache-Control": "no-store",
|
|
220
|
+
})
|
|
221
|
+
.end("Signed in. You can close this tab.");
|
|
222
|
+
resolve();
|
|
223
|
+
} catch (error) {
|
|
224
|
+
response.writeHead(400).end("Login failed. Return to your terminal.");
|
|
225
|
+
reject(error);
|
|
226
|
+
}
|
|
227
|
+
});
|
|
228
|
+
});
|
|
229
|
+
// Attach a rejection handler before discovery can fail or the timer fires.
|
|
230
|
+
void callback.catch(() => {});
|
|
231
|
+
await auth(oauth, { serverUrl: `${url}/mcp`, fetchFn: fetchFor(url) });
|
|
232
|
+
await callback;
|
|
233
|
+
} finally {
|
|
234
|
+
clearTimeout(timer);
|
|
235
|
+
server.closeAllConnections();
|
|
236
|
+
server.close();
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
async function unlockedAccessToken(url: string, forceRefresh = false) {
|
|
240
|
+
if (process.env.DISPOSABL_API_KEY) return process.env.DISPOSABL_API_KEY;
|
|
241
|
+
const session = await load(url);
|
|
242
|
+
if (!session.tokens)
|
|
243
|
+
throw new Error("Run login first, or set DISPOSABL_API_KEY.");
|
|
244
|
+
if (
|
|
245
|
+
forceRefresh ||
|
|
246
|
+
!session.expiresAt ||
|
|
247
|
+
Date.now() >= session.expiresAt - 30_000
|
|
248
|
+
) {
|
|
249
|
+
const oauth = provider(url, session, () => {
|
|
250
|
+
throw new Error("Session expired. Run login again.");
|
|
251
|
+
});
|
|
252
|
+
await auth(oauth, { serverUrl: `${url}/mcp`, fetchFn: fetchFor(url) });
|
|
253
|
+
}
|
|
254
|
+
if (!session.tokens) throw new Error("Session expired. Run login again.");
|
|
255
|
+
return session.tokens.access_token;
|
|
256
|
+
}
|
|
257
|
+
async function unlockedLogout(url: string) {
|
|
258
|
+
const session = await load(url);
|
|
259
|
+
if (session.tokens) {
|
|
260
|
+
for (const token of [
|
|
261
|
+
session.tokens.refresh_token,
|
|
262
|
+
session.tokens.access_token,
|
|
263
|
+
].filter(Boolean)) {
|
|
264
|
+
const response = await fetchFor(url)(`${url}/mcp/oauth/revoke`, {
|
|
265
|
+
method: "POST",
|
|
266
|
+
body: new URLSearchParams({
|
|
267
|
+
token: token!,
|
|
268
|
+
client_id: session.client?.client_id ?? "",
|
|
269
|
+
}),
|
|
270
|
+
});
|
|
271
|
+
if (!response.ok)
|
|
272
|
+
throw new Error(
|
|
273
|
+
"Revocation failed; credentials retained so logout can be retried.",
|
|
274
|
+
);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
await rm(sessionPath(url), { force: true });
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
async function withCredentials<T>(
|
|
281
|
+
url: string,
|
|
282
|
+
operation: () => Promise<T>,
|
|
283
|
+
): Promise<T> {
|
|
284
|
+
await mkdir(directory(), { recursive: true, mode: 0o700 });
|
|
285
|
+
const release = await lock(sessionPath(url), {
|
|
286
|
+
realpath: false,
|
|
287
|
+
stale: 10000,
|
|
288
|
+
retries: { retries: 8, minTimeout: 100, maxTimeout: 1000 },
|
|
289
|
+
});
|
|
290
|
+
try {
|
|
291
|
+
return await operation();
|
|
292
|
+
} finally {
|
|
293
|
+
await release();
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
export const login = (url: string, browser = true) =>
|
|
297
|
+
withCredentials(url, () => unlockedLogin(url, browser));
|
|
298
|
+
export const accessToken = (url: string, refresh = false) =>
|
|
299
|
+
withCredentials(url, () => unlockedAccessToken(url, refresh));
|
|
300
|
+
export const logout = (url: string) =>
|
|
301
|
+
withCredentials(url, () => unlockedLogout(url));
|