passflow 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +67 -2
- package/dist/cli.mjs +1759 -0
- package/package.json +42 -3
- package/skills/REVISION +1 -0
- package/skills/index.json +405 -0
- package/skills/passflow-nextjs/SKILL.md +205 -0
- package/skills/passflow-nextjs/assets/.env.example +5 -0
- package/skills/passflow-nextjs/assets/app/account/page.tsx +29 -0
- package/skills/passflow-nextjs/assets/app/actions.example.ts +21 -0
- package/skills/passflow-nextjs/assets/app/api/me/route.ts +22 -0
- package/skills/passflow-nextjs/assets/components/auth-links.tsx +11 -0
- package/skills/passflow-nextjs/assets/lib/call-api.example.ts +15 -0
- package/skills/passflow-nextjs/assets/lib/passflow.ts +4 -0
- package/skills/passflow-nextjs/assets/proxy.ts +10 -0
- package/skills/passflow-nextjs/references/guardrails.md +87 -0
- package/skills/passflow-nextjs/scripts/index.json +405 -0
- package/skills/passflow-nextjs/scripts/lib.sh +1069 -0
- package/skills/passflow-nextjs/scripts/verify.sh +467 -0
- package/skills/passflow-node-api/SKILL.md +189 -0
- package/skills/passflow-node-api/assets/examples/explain-rejection.ts +22 -0
- package/skills/passflow-node-api/assets/examples/express-routes.ts +22 -0
- package/skills/passflow-node-api/assets/examples/fastify-routes.ts +28 -0
- package/skills/passflow-node-api/assets/examples/hono-routes.ts +19 -0
- package/skills/passflow-node-api/assets/src/express-cors.ts +11 -0
- package/skills/passflow-node-api/assets/src/express.ts +13 -0
- package/skills/passflow-node-api/assets/src/fastify-cors.ts +11 -0
- package/skills/passflow-node-api/assets/src/fastify.ts +14 -0
- package/skills/passflow-node-api/assets/src/fetch-handler.ts +13 -0
- package/skills/passflow-node-api/assets/src/hono-cors.ts +11 -0
- package/skills/passflow-node-api/assets/src/hono.ts +16 -0
- package/skills/passflow-node-api/assets/src/passflow.ts +21 -0
- package/skills/passflow-node-api/references/guardrails.md +66 -0
- package/skills/passflow-node-api/scripts/index.json +405 -0
- package/skills/passflow-node-api/scripts/lib.sh +1069 -0
- package/skills/passflow-node-api/scripts/verify.sh +283 -0
- package/skills/passflow-react-vite/SKILL.md +225 -0
- package/skills/passflow-react-vite/assets/server/express-cors.ts +9 -0
- package/skills/passflow-react-vite/assets/server/express.ts +14 -0
- package/skills/passflow-react-vite/assets/server/fastify-cors.ts +11 -0
- package/skills/passflow-react-vite/assets/server/fastify.ts +15 -0
- package/skills/passflow-react-vite/assets/server/hono-cors.ts +8 -0
- package/skills/passflow-react-vite/assets/server/hono.ts +17 -0
- package/skills/passflow-react-vite/assets/server/passflow.ts +30 -0
- package/skills/passflow-react-vite/assets/server/tsconfig.json +14 -0
- package/skills/passflow-react-vite/assets/src/passflow.tsx +28 -0
- package/skills/passflow-react-vite/assets/src/require-sign-in.tsx +35 -0
- package/skills/passflow-react-vite/assets/src/use-api.ts +23 -0
- package/skills/passflow-react-vite/references/guardrails.md +82 -0
- package/skills/passflow-react-vite/scripts/index.json +405 -0
- package/skills/passflow-react-vite/scripts/lib.sh +1069 -0
- package/skills/passflow-react-vite/scripts/verify.sh +678 -0
- package/skills/passflow-tanstack-start/SKILL.md +182 -0
- package/skills/passflow-tanstack-start/assets/.env.example +5 -0
- package/skills/passflow-tanstack-start/assets/src/components/auth-links.tsx +10 -0
- package/skills/passflow-tanstack-start/assets/src/lib/call-api.example.ts +14 -0
- package/skills/passflow-tanstack-start/assets/src/lib/passflow.ts +14 -0
- package/skills/passflow-tanstack-start/assets/src/lib/server-functions.example.ts +20 -0
- package/skills/passflow-tanstack-start/assets/src/routes/account.tsx +25 -0
- package/skills/passflow-tanstack-start/assets/src/routes/api/me.ts +25 -0
- package/skills/passflow-tanstack-start/assets/src/start.ts +14 -0
- package/skills/passflow-tanstack-start/references/guardrails.md +73 -0
- package/skills/passflow-tanstack-start/scripts/index.json +405 -0
- package/skills/passflow-tanstack-start/scripts/lib.sh +1069 -0
- package/skills/passflow-tanstack-start/scripts/verify.sh +470 -0
package/dist/cli.mjs
ADDED
|
@@ -0,0 +1,1759 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { parseArgs } from "node:util";
|
|
3
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
4
|
+
import { accessSync, closeSync, constants, cpSync, existsSync, fchmodSync, fstatSync, lstatSync, mkdtempSync, openSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
|
|
5
|
+
import { homedir, tmpdir } from "node:os";
|
|
6
|
+
import { basename, dirname, join, posix, relative, resolve, sep, win32 } from "node:path";
|
|
7
|
+
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
8
|
+
import { createInterface } from "node:readline/promises";
|
|
9
|
+
import { createServer } from "node:http";
|
|
10
|
+
import { fileURLToPath } from "node:url";
|
|
11
|
+
// package.json
|
|
12
|
+
var version = "0.2.0";
|
|
13
|
+
// src/errors.ts
|
|
14
|
+
/** The project, or the command line, is refused before anything is created: exit 2. */
|
|
15
|
+
var Refusal = class extends Error {
|
|
16
|
+
name = "Refusal";
|
|
17
|
+
};
|
|
18
|
+
/** Something failed on the way (sign-in, the network, the server): exit 1. */
|
|
19
|
+
var Failure = class extends Error {
|
|
20
|
+
name = "Failure";
|
|
21
|
+
};
|
|
22
|
+
/** Text from a server or a file, cut to one short line with no control characters, safe to show. */
|
|
23
|
+
function shortText(value, max = 200) {
|
|
24
|
+
if (typeof value !== "string") return "";
|
|
25
|
+
const line = value.replace(/[\u0000-\u001f\u007f]+/g, " ").trim();
|
|
26
|
+
return line.length > max ? `${line.slice(0, max)}…` : line;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* A name from a server (an organization, a project, an environment), safe to print on a terminal: ANSI escape
|
|
30
|
+
* sequences and every control character removed, one line, at most 80 characters.
|
|
31
|
+
*/
|
|
32
|
+
function displayName(value) {
|
|
33
|
+
if (typeof value !== "string") return "";
|
|
34
|
+
const line = shortText(value.replace(/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)?/g, "").replace(/(?:\u001b\[|\u009b)[0-?]*[ -/]*[@-~]/g, "").replace(/\u001b[@-_]?/g, "").replace(/[\u0080-\u009f]+/g, " "), Number.POSITIVE_INFINITY);
|
|
35
|
+
return line.length > 80 ? `${line.slice(0, 79)}…` : line;
|
|
36
|
+
}
|
|
37
|
+
/** True when `fetch` failed because the answer was a redirect and `redirect: 'error'` refused to follow it. */
|
|
38
|
+
function isRefusedRedirect(error) {
|
|
39
|
+
const cause = error?.cause;
|
|
40
|
+
return typeof cause?.message === "string" && /redirect/i.test(cause.message);
|
|
41
|
+
}
|
|
42
|
+
// src/executable.ts
|
|
43
|
+
const defaultPathExt = ".COM;.EXE;.BAT;.CMD";
|
|
44
|
+
function defaultIsExecutable(path) {
|
|
45
|
+
try {
|
|
46
|
+
if (!statSync(path).isFile()) return false;
|
|
47
|
+
if (process.platform !== "win32") accessSync(path, constants.X_OK);
|
|
48
|
+
return true;
|
|
49
|
+
} catch {
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/** A variable of `env`. On Windows names are case-insensitive: PATH is usually spelt `Path`. */
|
|
54
|
+
function variable(env, name, platform) {
|
|
55
|
+
if (platform !== "win32") return env[name];
|
|
56
|
+
const key = Object.keys(env).find((candidate) => candidate.toUpperCase() === name);
|
|
57
|
+
return key === void 0 ? void 0 : env[key];
|
|
58
|
+
}
|
|
59
|
+
/** The file names Windows tries for `name`, one per PATHEXT extension, in PATHEXT order. */
|
|
60
|
+
function windowsNames(name, env) {
|
|
61
|
+
return (variable(env, "PATHEXT", "win32") || defaultPathExt).split(";").map((extension) => extension.trim().toLowerCase()).filter((extension) => /^\.[a-z0-9]+$/.test(extension)).map((extension) => `${name}${extension}`);
|
|
62
|
+
}
|
|
63
|
+
/** Whether `dir` is `parent` or inside it. Both are resolved, and case-folded on Windows. */
|
|
64
|
+
function within(dir, parent, sep) {
|
|
65
|
+
return dir === parent || dir.startsWith(parent.endsWith(sep) ? parent : parent + sep);
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* The absolute path of `name` on PATH, or undefined. Only absolute PATH entries count, so `.`, an empty entry and
|
|
69
|
+
* any relative one are skipped, and so is every `node_modules/.bin` and every entry in or below an excluded directory
|
|
70
|
+
* (see {@link LookupOptions}). On Windows a bare name given to CreateProcess is looked up in the current directory first, which is why callers spawn the path this returns.
|
|
71
|
+
* There each PATHEXT extension is tried, so an npm `.cmd` shim is found; start one with {@link invocation}.
|
|
72
|
+
*/
|
|
73
|
+
function findExecutable(name, options) {
|
|
74
|
+
const platform = options.platform ?? process.platform;
|
|
75
|
+
const env = options.env ?? process.env;
|
|
76
|
+
const isExecutable = options.isExecutable ?? defaultIsExecutable;
|
|
77
|
+
const paths = platform === "win32" ? win32 : posix;
|
|
78
|
+
const fold = (path) => platform === "win32" ? path.toLowerCase() : path;
|
|
79
|
+
const home = fold(paths.resolve(options.home ?? homedir()));
|
|
80
|
+
const skipped = options.exclude.map((dir) => {
|
|
81
|
+
const excluded = fold(paths.resolve(dir));
|
|
82
|
+
if (excluded === home) return (entry) => entry === home;
|
|
83
|
+
return (entry) => within(entry, excluded, paths.sep);
|
|
84
|
+
});
|
|
85
|
+
const isModulesBin = (dir) => paths.basename(dir) === ".bin" && paths.basename(paths.dirname(dir)) === "node_modules";
|
|
86
|
+
const names = platform === "win32" ? windowsNames(name, env) : [name];
|
|
87
|
+
for (const raw of (variable(env, "PATH", platform) ?? "").split(paths.delimiter)) {
|
|
88
|
+
const entry = platform === "win32" ? raw.replace(/^"(.*)"$/, "$1") : raw;
|
|
89
|
+
if (entry === "" || !paths.isAbsolute(entry)) continue;
|
|
90
|
+
const dir = paths.resolve(entry);
|
|
91
|
+
const folded = fold(dir);
|
|
92
|
+
if (isModulesBin(folded) || skipped.some((skip) => skip(folded))) continue;
|
|
93
|
+
for (const candidate of names) {
|
|
94
|
+
const path = paths.join(dir, candidate);
|
|
95
|
+
if (isExecutable(path)) return path;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
/** True for a Windows batch file, which only cmd.exe can run: Node refuses to spawn one without a shell. */
|
|
100
|
+
function isBatchFile(path, platform = process.platform) {
|
|
101
|
+
return platform === "win32" && /\.(?:bat|cmd)$/i.test(path);
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Characters that stay literal inside double quotes on a cmd.exe line, both where cmd.exe parses it and where an npm
|
|
105
|
+
* shim passes it on with `%*`. Left out on purpose: `"` ends the quotes, `%` and `!` expand variables, a line break
|
|
106
|
+
* ends the command, and `^ & | < >` are kept out even though the quotes protect them. A value may not end in `\`
|
|
107
|
+
* either: the program would read `\"` as an escaped quote and run the closing quote into the value.
|
|
108
|
+
*/
|
|
109
|
+
const batchSafe = /^[\p{L}\p{N} _.,:;=+'@#~$()[\]{}\\/-]*$/u;
|
|
110
|
+
/**
|
|
111
|
+
* The command and arguments that run `path` with `args`. Anything but a Windows batch file runs directly. A batch
|
|
112
|
+
* file runs through `cmd.exe /d /s /c` with its path and each argument in double quotes; a path or argument holding
|
|
113
|
+
* a character that cmd.exe could read as syntax is refused, so no argument can become a command.
|
|
114
|
+
*/
|
|
115
|
+
function invocation(path, args, options = {}) {
|
|
116
|
+
if (!isBatchFile(path, options.platform ?? process.platform)) return {
|
|
117
|
+
command: path,
|
|
118
|
+
args,
|
|
119
|
+
windowsVerbatimArguments: false
|
|
120
|
+
};
|
|
121
|
+
for (const value of [path, ...args]) if (!batchSafe.test(value) || value.endsWith("\\")) throw new Failure(`cannot pass ${JSON.stringify(value)} safely to ${win32.basename(path)} through cmd.exe`);
|
|
122
|
+
const env = options.env ?? process.env;
|
|
123
|
+
const comspec = variable(env, "COMSPEC", "win32");
|
|
124
|
+
return {
|
|
125
|
+
command: comspec !== void 0 && win32.isAbsolute(comspec) && /(?:^|\\)cmd\.exe$/i.test(comspec) ? comspec : win32.join(variable(env, "SYSTEMROOT", "win32") || "C:\\Windows", "System32", "cmd.exe"),
|
|
126
|
+
args: [
|
|
127
|
+
"/d",
|
|
128
|
+
"/s",
|
|
129
|
+
"/c",
|
|
130
|
+
`"${[path, ...args].map((value) => `"${value}"`).join(" ")}"`
|
|
131
|
+
],
|
|
132
|
+
windowsVerbatimArguments: true
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
// src/handoff.ts
|
|
136
|
+
const agents = [
|
|
137
|
+
"claude",
|
|
138
|
+
"codex",
|
|
139
|
+
"cursor-agent"
|
|
140
|
+
];
|
|
141
|
+
/** Variables a credential can be read from. The agent's environment never has them. */
|
|
142
|
+
const credentialVariables = ["PASSFLOW_API_KEY", "PASSFLOW_MANAGEMENT_KEY"];
|
|
143
|
+
/** The one fixed instruction for the developer's agent. It names the skill and holds no value from the run. */
|
|
144
|
+
function agentPrompt(stack) {
|
|
145
|
+
return [
|
|
146
|
+
`Add Passflow sign-in to this project with the ${stack.skill} skill, installed in .claude/skills/${stack.skill}/`,
|
|
147
|
+
`and .agents/skills/${stack.skill}/. Follow its SKILL.md step by step and copy every Passflow call from its`,
|
|
148
|
+
"assets/ folder; never write one from memory.",
|
|
149
|
+
`The Passflow CLI already wrote ${stack.env_file} and .env.example: do not create, edit, print or read out any`,
|
|
150
|
+
".env* file. Do not change the scripts in package.json. Add no dependency except @passflow/* packages.",
|
|
151
|
+
"When you are done, run the skill's scripts/verify.sh static and report what you changed and anything the",
|
|
152
|
+
"developer still has to do."
|
|
153
|
+
].join("\n");
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* A copy of the environment without the credential variables. Windows reads variable names case-insensitively, so
|
|
157
|
+
* there `Passflow_Api_Key` is the same variable and is dropped too.
|
|
158
|
+
*/
|
|
159
|
+
function agentEnvironment(source = process.env, platform = process.platform) {
|
|
160
|
+
const fold = (name) => platform === "win32" ? name.toUpperCase() : name;
|
|
161
|
+
const dropped = new Set(credentialVariables.map(fold));
|
|
162
|
+
const env = {};
|
|
163
|
+
for (const name of Object.keys(source)) if (!dropped.has(fold(name))) env[name] = source[name];
|
|
164
|
+
return env;
|
|
165
|
+
}
|
|
166
|
+
/** The one argument a batch shim gets instead of the prompt: where the prompt is. */
|
|
167
|
+
function promptFileInstruction(file) {
|
|
168
|
+
return `Read the file ${file} and follow the instructions in it.`;
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* How to start the agent at `path` with the prompt. An executable gets the prompt as its argument. A Windows batch
|
|
172
|
+
* shim (an npm `claude.cmd`) only runs through cmd.exe, which would read the prompt's line breaks and symbols as
|
|
173
|
+
* syntax, so it gets the prompt in a file: `writePrompt` saves it and returns the file's path, and the agent's only
|
|
174
|
+
* argument names that file.
|
|
175
|
+
*/
|
|
176
|
+
function agentInvocation(path, prompt, options) {
|
|
177
|
+
return invocation(path, isBatchFile(path, options.platform) ? [promptFileInstruction(options.writePrompt(prompt))] : [prompt], options);
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Starts the agent in the project with the prompt, in a copy of this environment without the credentials. The agent
|
|
181
|
+
* is run by its absolute path from PATH, never from the project or the current directory.
|
|
182
|
+
*/
|
|
183
|
+
function runAgent(agent, prompt, cwd) {
|
|
184
|
+
const env = agentEnvironment();
|
|
185
|
+
const path = findExecutable(agent, {
|
|
186
|
+
exclude: [cwd, process.cwd()],
|
|
187
|
+
env
|
|
188
|
+
});
|
|
189
|
+
if (path === void 0) throw new Failure(`${agent} is not on your PATH`);
|
|
190
|
+
return runAgentAt(path, agent, prompt, cwd, env);
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Starts the agent at the absolute `path` in `cwd` with the prompt and waits for it. A batch shim gets the prompt in
|
|
194
|
+
* a temporary file, removed when the agent exits. `name` is the agent's name in error messages.
|
|
195
|
+
*/
|
|
196
|
+
function runAgentAt(path, name, prompt, cwd, env) {
|
|
197
|
+
let scratch;
|
|
198
|
+
const writePrompt = (text) => {
|
|
199
|
+
scratch = mkdtempSync(join(tmpdir(), "passflow-prompt-"));
|
|
200
|
+
const file = join(scratch, "prompt.md");
|
|
201
|
+
writeFileSync(file, text, { mode: 384 });
|
|
202
|
+
return file;
|
|
203
|
+
};
|
|
204
|
+
try {
|
|
205
|
+
const run = agentInvocation(path, prompt, {
|
|
206
|
+
env,
|
|
207
|
+
writePrompt
|
|
208
|
+
});
|
|
209
|
+
const result = spawnSync(run.command, run.args, {
|
|
210
|
+
cwd,
|
|
211
|
+
env,
|
|
212
|
+
stdio: "inherit",
|
|
213
|
+
windowsVerbatimArguments: run.windowsVerbatimArguments
|
|
214
|
+
});
|
|
215
|
+
if (result.error) {
|
|
216
|
+
const code = result.error.code;
|
|
217
|
+
throw new Failure(code === "ENOENT" ? `${name} is not on your PATH` : `could not start ${name}: ${result.error.message}`);
|
|
218
|
+
}
|
|
219
|
+
return result.status ?? 1;
|
|
220
|
+
} finally {
|
|
221
|
+
if (scratch !== void 0) rmSync(scratch, {
|
|
222
|
+
recursive: true,
|
|
223
|
+
force: true
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
// src/detect.ts
|
|
228
|
+
function readPackageJson(dir) {
|
|
229
|
+
const file = join(dir, "package.json");
|
|
230
|
+
if (!existsSync(file)) throw new Refusal(`no package.json in ${dir}. Run passflow integrate at the root of your app.`);
|
|
231
|
+
try {
|
|
232
|
+
const parsed = JSON.parse(readFileSync(file, "utf8"));
|
|
233
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("not an object");
|
|
234
|
+
return parsed;
|
|
235
|
+
} catch {
|
|
236
|
+
throw new Refusal(`${file} is not valid JSON.`);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
/** The range package.json gives a package: from dependencies, else devDependencies; '' when it lists none. */
|
|
240
|
+
function dependencyRange(pkg, name) {
|
|
241
|
+
for (const field of [pkg.dependencies, pkg.devDependencies]) {
|
|
242
|
+
const range = field?.[name];
|
|
243
|
+
if (typeof range === "string" && range !== "") return range;
|
|
244
|
+
}
|
|
245
|
+
return "";
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* The lowest version a simple range admits. Understood: 1.2.3, v1.2.3, =1.2.3, ^1.2.3, ~1.2.3, >=1.2.3, and 1,
|
|
249
|
+
* 1.2, 1.x, 1.2.x, 1.2.*. Anything else (a tag, workspace:, npm:, a URL, `a || b`, `a - b`, `<2`, `>1`,
|
|
250
|
+
* `>=1 <2`) cannot be compared and gives null.
|
|
251
|
+
*/
|
|
252
|
+
function versionFloor(spec) {
|
|
253
|
+
const match = /^(\^|~|>=|=)?\s*v?(\d+)(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$/.exec(spec.trim());
|
|
254
|
+
if (!match) return null;
|
|
255
|
+
const major = Number(match[2]);
|
|
256
|
+
let minor = match[3];
|
|
257
|
+
let patch = match[4];
|
|
258
|
+
if (minor === void 0 || /^[xX*]$/.test(minor)) {
|
|
259
|
+
minor = "0";
|
|
260
|
+
patch = "0";
|
|
261
|
+
}
|
|
262
|
+
if (patch === void 0 || /^[xX*]$/.test(patch)) patch = "0";
|
|
263
|
+
return [
|
|
264
|
+
major,
|
|
265
|
+
Number(minor),
|
|
266
|
+
Number(patch),
|
|
267
|
+
match[5] !== void 0
|
|
268
|
+
];
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* True when every version `spec` admits is at least `required` (">=X[.Y[.Z]]", as index.json writes it). It fails
|
|
272
|
+
* safe: a range that cannot be compared does not meet it, and a pre-release of exactly the required version is
|
|
273
|
+
* below it, as in npm's semver.
|
|
274
|
+
*/
|
|
275
|
+
function rangeMeets(spec, required) {
|
|
276
|
+
if (!required.startsWith(">=")) return false;
|
|
277
|
+
const have = versionFloor(spec);
|
|
278
|
+
const want = versionFloor(required);
|
|
279
|
+
if (!have || !want) return false;
|
|
280
|
+
for (let i = 0; i < 3; i++) if (have[i] !== want[i]) return have[i] > want[i];
|
|
281
|
+
return !have[3];
|
|
282
|
+
}
|
|
283
|
+
/** Selection by package names alone: every `all` package is a dependency, and one `any` package when listed. */
|
|
284
|
+
function selected(pkg, stack) {
|
|
285
|
+
const all = stack.detect.all ?? [];
|
|
286
|
+
const any = stack.detect.any ?? [];
|
|
287
|
+
if (all.length === 0 && any.length === 0) return false;
|
|
288
|
+
if (!all.every((entry) => dependencyRange(pkg, entry.package) !== "")) return false;
|
|
289
|
+
return any.length === 0 || any.some((entry) => dependencyRange(pkg, entry.package) !== "");
|
|
290
|
+
}
|
|
291
|
+
const versionMessages = {
|
|
292
|
+
nextjs: "Next.js 16 or newer",
|
|
293
|
+
"tanstack-start": "TanStack Start 1.169.5 or newer and TanStack Router 1.170.46 or newer"
|
|
294
|
+
};
|
|
295
|
+
function rangeFailure(pkg, stack) {
|
|
296
|
+
for (const entry of [...stack.detect.all ?? [], ...stack.detect.any ?? []]) {
|
|
297
|
+
if (!entry.range) continue;
|
|
298
|
+
const spec = dependencyRange(pkg, entry.package);
|
|
299
|
+
if (spec === "") continue;
|
|
300
|
+
if (!rangeMeets(spec, entry.range)) return {
|
|
301
|
+
entry,
|
|
302
|
+
spec
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
return null;
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* The stack of the project: the first stack in index.json selected by package names. Its version ranges must
|
|
309
|
+
* then hold; there is no fall-through to a later stack.
|
|
310
|
+
*/
|
|
311
|
+
function detectStack(pkg, index) {
|
|
312
|
+
const stack = index.stacks.find((candidate) => selected(pkg, candidate));
|
|
313
|
+
if (!stack) throw new Refusal(`no supported stack found in package.json. Passflow integrates these stacks: ${index.stacks.map((s) => s.id).join(", ")}.`);
|
|
314
|
+
const failure = rangeFailure(pkg, stack);
|
|
315
|
+
if (failure) {
|
|
316
|
+
const rule = failure.entry.range ?? "";
|
|
317
|
+
throw new Refusal(`this project needs ${versionMessages[stack.id] ?? "a newer version of its framework"}: package.json gives ${failure.entry.package} "${failure.spec}", which does not meet ${rule}. A tag, workspace:, a URL or a compound range cannot be checked; write a version range such as "^${rule.replace(/^>=/, "")}".`);
|
|
318
|
+
}
|
|
319
|
+
return stack;
|
|
320
|
+
}
|
|
321
|
+
const managerTools = {
|
|
322
|
+
"yarn-classic": "yarn",
|
|
323
|
+
"yarn-berry": "yarn",
|
|
324
|
+
npm: "npm",
|
|
325
|
+
pnpm: "pnpm"
|
|
326
|
+
};
|
|
327
|
+
function tool(manager) {
|
|
328
|
+
return managerTools[manager] ?? manager;
|
|
329
|
+
}
|
|
330
|
+
function refusedManager(manager) {
|
|
331
|
+
return new Refusal(`this project uses ${manager}. Passflow supports npm, pnpm and Yarn 1 (classic) only.`);
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* The project's package manager, by the rules every Passflow consumer shares:
|
|
335
|
+
* 1. a `packageManager` field naming yarn@2 or newer, or bun, is refused;
|
|
336
|
+
* 2. a root npm-shrinkwrap.json is refused;
|
|
337
|
+
* 3. of the lockfiles index.json lists, any that names a refused manager refuses; otherwise the first wins;
|
|
338
|
+
* 4. a yarn.lock with a `__metadata:` line is Yarn Berry, and refused;
|
|
339
|
+
* 5. no lockfile is refused;
|
|
340
|
+
* 6. a `packageManager` field naming a supported manager other than the lockfile's is refused.
|
|
341
|
+
*/
|
|
342
|
+
function detectPackageManager(dir, pkg, index) {
|
|
343
|
+
const field = typeof pkg.packageManager === "string" ? pkg.packageManager : "";
|
|
344
|
+
let declared = "";
|
|
345
|
+
if (/^yarn@1(?:$|[.+])/.test(field)) declared = "yarn-classic";
|
|
346
|
+
else if (field.startsWith("yarn@")) throw refusedManager("yarn-berry");
|
|
347
|
+
else if (field.startsWith("bun@")) throw refusedManager("bun");
|
|
348
|
+
else if (field.startsWith("npm@")) declared = "npm";
|
|
349
|
+
else if (field.startsWith("pnpm@")) declared = "pnpm";
|
|
350
|
+
if (existsSync(join(dir, "npm-shrinkwrap.json"))) throw new Refusal("this project has an npm-shrinkwrap.json. Passflow cannot change it; it updates package-lock.json, pnpm-lock.yaml or yarn.lock only. Remove the shrinkwrap or integrate by hand.");
|
|
351
|
+
const found = index.package_managers.detect.filter((entry) => existsSync(join(dir, entry.file)));
|
|
352
|
+
const refused = found.find((entry) => index.package_managers.refused.includes(entry.manager));
|
|
353
|
+
if (refused) throw refusedManager(refused.manager);
|
|
354
|
+
const yarnLock = join(dir, "yarn.lock");
|
|
355
|
+
if (existsSync(yarnLock) && /^__metadata:/m.test(readFileSync(yarnLock, "utf8"))) throw refusedManager("yarn-berry");
|
|
356
|
+
const first = found[0];
|
|
357
|
+
if (!first) throw new Refusal("no lockfile found. Passflow needs a committed lockfile: package-lock.json (npm), pnpm-lock.yaml (pnpm) or yarn.lock (Yarn 1, classic). Install once with your package manager, commit the lockfile, then run again.");
|
|
358
|
+
if (declared !== "" && declared !== first.manager) throw new Refusal(`package.json names ${tool(declared)} in packageManager, but the lockfile belongs to ${tool(first.manager)}. Make them agree (remove the stale lockfile or fix packageManager), then run again.`);
|
|
359
|
+
if (!index.package_managers.supported.includes(first.manager)) throw refusedManager(first.manager);
|
|
360
|
+
return first.manager;
|
|
361
|
+
}
|
|
362
|
+
// src/envfile.ts
|
|
363
|
+
/**
|
|
364
|
+
* Refuses a path that is a symlink or anything but a regular file. lstat does not follow a link, so a link to a
|
|
365
|
+
* tracked or outside file is refused before anything reads or writes through it.
|
|
366
|
+
*/
|
|
367
|
+
function assertPlainFile(path) {
|
|
368
|
+
let stat;
|
|
369
|
+
try {
|
|
370
|
+
stat = lstatSync(path);
|
|
371
|
+
} catch (error) {
|
|
372
|
+
if (error.code === "ENOENT") return false;
|
|
373
|
+
throw error;
|
|
374
|
+
}
|
|
375
|
+
if (stat.isSymbolicLink()) throw new Refusal(`${basename(path)} is a symlink. Passflow writes only a plain file there: replace the link with a file.`);
|
|
376
|
+
if (!stat.isFile()) throw new Refusal(`${basename(path)} is not a regular file.`);
|
|
377
|
+
return true;
|
|
378
|
+
}
|
|
379
|
+
function readEnvFile(path) {
|
|
380
|
+
if (!assertPlainFile(path)) return {
|
|
381
|
+
exists: false,
|
|
382
|
+
keys: /* @__PURE__ */ new Set(),
|
|
383
|
+
emptyKeys: /* @__PURE__ */ new Set(),
|
|
384
|
+
endsWithNewline: true
|
|
385
|
+
};
|
|
386
|
+
const text = readFileSync(path, "utf8");
|
|
387
|
+
const keys = /* @__PURE__ */ new Set();
|
|
388
|
+
const emptyKeys = /* @__PURE__ */ new Set();
|
|
389
|
+
for (const line of text.split(/\r?\n/)) {
|
|
390
|
+
const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/.exec(line);
|
|
391
|
+
if (!match?.[1]) continue;
|
|
392
|
+
keys.add(match[1]);
|
|
393
|
+
const value = (match[2] ?? "").trim().replace(/^(['"])(.*)\1$/, "$2");
|
|
394
|
+
if (value === "" || value.startsWith("#")) emptyKeys.add(match[1]);
|
|
395
|
+
else emptyKeys.delete(match[1]);
|
|
396
|
+
}
|
|
397
|
+
return {
|
|
398
|
+
exists: true,
|
|
399
|
+
keys,
|
|
400
|
+
emptyKeys,
|
|
401
|
+
endsWithNewline: text === "" || text.endsWith("\n")
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
/** git from PATH, never from the project or the current directory. */
|
|
405
|
+
function gitPath(dir) {
|
|
406
|
+
return findExecutable("git", { exclude: [dir, process.cwd()] });
|
|
407
|
+
}
|
|
408
|
+
/**
|
|
409
|
+
* True when the project is inside a git checkout: a `.git` in it or a directory above it, or git itself says so.
|
|
410
|
+
* False only when neither holds, so a checkout git cannot read (git missing, a dubious-ownership refusal) still
|
|
411
|
+
* counts as one.
|
|
412
|
+
*/
|
|
413
|
+
function isGitCheckout(dir) {
|
|
414
|
+
for (let current = resolve(dir);; current = dirname(current)) {
|
|
415
|
+
if (existsSync(join(current, ".git"))) return true;
|
|
416
|
+
if (dirname(current) === current) break;
|
|
417
|
+
}
|
|
418
|
+
const git = gitPath(dir);
|
|
419
|
+
if (git === void 0) return false;
|
|
420
|
+
const run = invocation(git, ["rev-parse", "--is-inside-work-tree"]);
|
|
421
|
+
const result = spawnSync(run.command, run.args, {
|
|
422
|
+
cwd: dir,
|
|
423
|
+
encoding: "utf8",
|
|
424
|
+
windowsVerbatimArguments: run.windowsVerbatimArguments
|
|
425
|
+
});
|
|
426
|
+
return result.status === 0 && result.stdout.trim() === "true";
|
|
427
|
+
}
|
|
428
|
+
/** Runs a git command that answers with exit 0 or 1; anything else (git missing or refusing) is a refusal. */
|
|
429
|
+
function gitYesNo(dir, args, what) {
|
|
430
|
+
const git = gitPath(dir);
|
|
431
|
+
const run = git === void 0 ? void 0 : invocation(git, args);
|
|
432
|
+
const result = run === void 0 ? void 0 : spawnSync(run.command, run.args, {
|
|
433
|
+
cwd: dir,
|
|
434
|
+
stdio: "ignore",
|
|
435
|
+
windowsVerbatimArguments: run.windowsVerbatimArguments
|
|
436
|
+
});
|
|
437
|
+
if (result?.status === 0) return true;
|
|
438
|
+
if (result?.status === 1) return false;
|
|
439
|
+
throw new Refusal(`this is a git checkout, but git could not check ${what} (${result === void 0 ? "git is not on your PATH" : result.error ? "git did not run" : `git exited ${String(result.status)}`}), so Passflow cannot tell whether its secrets would reach your history. Fix git here, then run passflow integrate again.`);
|
|
440
|
+
}
|
|
441
|
+
/** In a git checkout, whether git tracks the file; a git that cannot answer is a refusal. */
|
|
442
|
+
function isTrackedByGit(dir, file) {
|
|
443
|
+
return gitYesNo(dir, [
|
|
444
|
+
"ls-files",
|
|
445
|
+
"--error-unmatch",
|
|
446
|
+
"--",
|
|
447
|
+
file
|
|
448
|
+
], `whether it tracks ${file}`);
|
|
449
|
+
}
|
|
450
|
+
/** Converts one .gitignore glob, for a single path segment, to a regular expression. */
|
|
451
|
+
function globToRegExp(glob) {
|
|
452
|
+
let source = "";
|
|
453
|
+
for (const char of glob) if (char === "*") source += "[^/]*";
|
|
454
|
+
else if (char === "?") source += "[^/]";
|
|
455
|
+
else source += char.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
456
|
+
return new RegExp(`^${source}$`);
|
|
457
|
+
}
|
|
458
|
+
/**
|
|
459
|
+
* Whether .gitignore ignores a file at the project root. In a git checkout git answers, and a git that cannot is a
|
|
460
|
+
* refusal; elsewhere the root .gitignore is read with git's rules for a name pattern (globs, negation, the last
|
|
461
|
+
* match wins). Path patterns are not followed; a file they would cover gets its own line.
|
|
462
|
+
*/
|
|
463
|
+
function isIgnored(dir, file, inCheckout) {
|
|
464
|
+
if (inCheckout) return gitYesNo(dir, [
|
|
465
|
+
"check-ignore",
|
|
466
|
+
"--quiet",
|
|
467
|
+
"--no-index",
|
|
468
|
+
"--",
|
|
469
|
+
file
|
|
470
|
+
], `whether it ignores ${file}`);
|
|
471
|
+
const gitignore = join(dir, ".gitignore");
|
|
472
|
+
if (!assertPlainFile(gitignore)) return false;
|
|
473
|
+
let ignored = false;
|
|
474
|
+
for (const raw of readFileSync(gitignore, "utf8").split(/\r?\n/)) {
|
|
475
|
+
let pattern = raw.replace(/\s+$/, "");
|
|
476
|
+
if (pattern === "" || pattern.startsWith("#")) continue;
|
|
477
|
+
const negated = pattern.startsWith("!");
|
|
478
|
+
if (negated) pattern = pattern.slice(1);
|
|
479
|
+
if (pattern.endsWith("/")) continue;
|
|
480
|
+
if (pattern.startsWith("/")) pattern = pattern.slice(1);
|
|
481
|
+
pattern = pattern.replace(/^\*\*\//, "");
|
|
482
|
+
if (pattern.includes("/")) continue;
|
|
483
|
+
if (globToRegExp(pattern).test(file)) ignored = !negated;
|
|
484
|
+
}
|
|
485
|
+
return ignored;
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* Adds the file to the root .gitignore. A .gitignore that is a symlink or not a regular file is refused: git does
|
|
489
|
+
* not read a symlinked one, so the rule would have no effect. In a git checkout, git must then confirm that it
|
|
490
|
+
* ignores the file; otherwise it is a refusal, and no secret is written.
|
|
491
|
+
*/
|
|
492
|
+
function addToGitignore(dir, file, inCheckout) {
|
|
493
|
+
const gitignore = join(dir, ".gitignore");
|
|
494
|
+
const current = assertPlainFile(gitignore) ? readFileSync(gitignore, "utf8") : "";
|
|
495
|
+
const lead = current === "" || current.endsWith("\n") ? "" : "\n";
|
|
496
|
+
const fd = openSync(gitignore, constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | (constants.O_NOFOLLOW ?? 0), 420);
|
|
497
|
+
try {
|
|
498
|
+
writeSync(fd, `${lead}${file}\n`);
|
|
499
|
+
} finally {
|
|
500
|
+
closeSync(fd);
|
|
501
|
+
}
|
|
502
|
+
if (inCheckout && !isIgnored(dir, file, true)) throw new Refusal(`git does not ignore ${file} even with the line added to .gitignore, so no secret was written to it.`);
|
|
503
|
+
}
|
|
504
|
+
/** A value goes on one line, unquoted: anything that would break the line or need quoting is refused. */
|
|
505
|
+
function checkValue(name, value) {
|
|
506
|
+
if (/[\u0000-\u001f\u007f\s"'`#$\\]/.test(value)) throw new Refusal(`the value for ${name} holds a character an env file cannot carry unquoted.`);
|
|
507
|
+
}
|
|
508
|
+
/**
|
|
509
|
+
* Appends `NAME=value` lines for the names the file lacks, and never changes a line already there. The file is
|
|
510
|
+
* opened with O_NOFOLLOW, so a symlink put in its place after the check is not written through, and a new file
|
|
511
|
+
* gets mode 0600. With `ownerOnly`, a file that is written to is set to 0600 first, on the opened descriptor,
|
|
512
|
+
* so secrets never land in a file others can read.
|
|
513
|
+
*/
|
|
514
|
+
function appendEnv(path, entries, { ownerOnly = false } = {}) {
|
|
515
|
+
const state = readEnvFile(path);
|
|
516
|
+
const missing = entries.filter(([name]) => !state.keys.has(name));
|
|
517
|
+
if (missing.length === 0) return { names: [] };
|
|
518
|
+
for (const [name, value] of missing) checkValue(name, value);
|
|
519
|
+
const text = `${state.endsWithNewline ? "" : "\n"}${missing.map(([name, value]) => `${name}=${value}`).join("\n")}\n`;
|
|
520
|
+
const flags = constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | (constants.O_NOFOLLOW ?? 0);
|
|
521
|
+
let fd;
|
|
522
|
+
try {
|
|
523
|
+
fd = openSync(path, flags, 384);
|
|
524
|
+
} catch (error) {
|
|
525
|
+
if (error.code === "ELOOP") throw new Refusal(`${basename(path)} is a symlink. Passflow writes only a plain file there: replace the link with a file.`);
|
|
526
|
+
throw error;
|
|
527
|
+
}
|
|
528
|
+
let previousMode;
|
|
529
|
+
try {
|
|
530
|
+
const stat = fstatSync(fd);
|
|
531
|
+
if (!stat.isFile()) throw new Refusal(`${basename(path)} is not a regular file.`);
|
|
532
|
+
const mode = stat.mode & 511;
|
|
533
|
+
if (ownerOnly && process.platform !== "win32" && mode !== 384) {
|
|
534
|
+
try {
|
|
535
|
+
fchmodSync(fd, 384);
|
|
536
|
+
} catch {
|
|
537
|
+
throw new Refusal(`cannot make ${basename(path)} readable by its owner only (mode ${mode.toString(8)}), so no secret was written to it.`);
|
|
538
|
+
}
|
|
539
|
+
previousMode = mode;
|
|
540
|
+
}
|
|
541
|
+
writeSync(fd, text);
|
|
542
|
+
} finally {
|
|
543
|
+
closeSync(fd);
|
|
544
|
+
}
|
|
545
|
+
const names = missing.map(([name]) => name);
|
|
546
|
+
return previousMode === void 0 ? { names } : {
|
|
547
|
+
names,
|
|
548
|
+
previousMode
|
|
549
|
+
};
|
|
550
|
+
}
|
|
551
|
+
/**
|
|
552
|
+
* Refuses, before anything is created, an env file that is not a plain file, or that git tracks, or a checkout
|
|
553
|
+
* where git cannot say. Only a project outside git, or a file git confirms it does not track, goes ahead.
|
|
554
|
+
*/
|
|
555
|
+
function preflightEnvFile(dir, file, inCheckout) {
|
|
556
|
+
const state = readEnvFile(join(dir, file));
|
|
557
|
+
if (inCheckout && isTrackedByGit(dir, file)) throw new Refusal(`git tracks ${file}, so its secrets would reach your history. Run \`git rm --cached ${file}\`, commit, then run passflow integrate again.`);
|
|
558
|
+
return state;
|
|
559
|
+
}
|
|
560
|
+
// src/prompt.ts
|
|
561
|
+
/** Questions need a person at a terminal on both ends. */
|
|
562
|
+
function canAsk() {
|
|
563
|
+
return Boolean(process.stdin.isTTY && process.stdout.isTTY);
|
|
564
|
+
}
|
|
565
|
+
async function ask(question) {
|
|
566
|
+
const rl = createInterface({
|
|
567
|
+
input: process.stdin,
|
|
568
|
+
output: process.stdout
|
|
569
|
+
});
|
|
570
|
+
try {
|
|
571
|
+
return (await rl.question(question)).trim();
|
|
572
|
+
} finally {
|
|
573
|
+
rl.close();
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
/** Shows a numbered list and returns the chosen item. Enter takes the first. */
|
|
577
|
+
async function choose(title, items, label) {
|
|
578
|
+
const first = items[0];
|
|
579
|
+
if (first === void 0) throw new Failure(`nothing to choose for ${title}`);
|
|
580
|
+
if (items.length === 1) return first;
|
|
581
|
+
process.stdout.write(`${title}:\n`);
|
|
582
|
+
items.forEach((item, i) => {
|
|
583
|
+
process.stdout.write(` ${i + 1}) ${label(item)}\n`);
|
|
584
|
+
});
|
|
585
|
+
for (;;) {
|
|
586
|
+
const answer = await ask(`Choose 1-${items.length} [1]: `);
|
|
587
|
+
if (answer === "") return first;
|
|
588
|
+
const n = Number(answer);
|
|
589
|
+
const item = Number.isInteger(n) ? items[n - 1] : void 0;
|
|
590
|
+
if (item !== void 0) return item;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
// src/provision.ts
|
|
594
|
+
const loopbackHosts = /* @__PURE__ */ new Set([
|
|
595
|
+
"localhost",
|
|
596
|
+
"127.0.0.1",
|
|
597
|
+
"[::1]",
|
|
598
|
+
"::1"
|
|
599
|
+
]);
|
|
600
|
+
/**
|
|
601
|
+
* An app's base URL: what `checkUrl` accepts, and an origin only. The session SDK registers and sends its
|
|
602
|
+
* callback at the origin's `/auth/callback`, so a path here would register a callback the app never uses.
|
|
603
|
+
*/
|
|
604
|
+
function checkBaseUrl(flag, raw) {
|
|
605
|
+
const checked = checkUrl(flag, raw);
|
|
606
|
+
if (new URL(checked).pathname !== "/") throw new Refusal(`${flag} must be the app's origin, such as https://app.example.com, with no path.`);
|
|
607
|
+
return checked;
|
|
608
|
+
}
|
|
609
|
+
/**
|
|
610
|
+
* An absolute http(s) URL with no query, fragment or credentials, returned without a trailing slash. http is
|
|
611
|
+
* accepted on a loopback host only, where a local dev server runs.
|
|
612
|
+
*/
|
|
613
|
+
function checkUrl(flag, raw) {
|
|
614
|
+
let url;
|
|
615
|
+
try {
|
|
616
|
+
url = new URL(raw.trim());
|
|
617
|
+
} catch {
|
|
618
|
+
throw new Refusal(`${flag} must be an absolute http(s) URL.`);
|
|
619
|
+
}
|
|
620
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") throw new Refusal(`${flag} must be an http(s) URL.`);
|
|
621
|
+
if (url.protocol === "http:" && !loopbackHosts.has(url.hostname)) throw new Refusal(`${flag} needs https, or http on localhost, 127.0.0.1 or [::1].`);
|
|
622
|
+
if (url.username || url.password || url.search || url.hash || raw.includes("#") || raw.includes("?")) throw new Refusal(`${flag} may not carry a user name, a query or a fragment.`);
|
|
623
|
+
return url.toString().replace(/\/+$/, "");
|
|
624
|
+
}
|
|
625
|
+
/**
|
|
626
|
+
* A call that carries a credential. Redirects are refused, not followed: fetch keeps custom headers such as
|
|
627
|
+
* `X-Passflow-Key` on a redirect to another host, so a redirect could hand the credential to a different service.
|
|
628
|
+
*/
|
|
629
|
+
async function call(url, init, what) {
|
|
630
|
+
try {
|
|
631
|
+
return await fetch(url, {
|
|
632
|
+
...init,
|
|
633
|
+
redirect: "error",
|
|
634
|
+
signal: AbortSignal.timeout(3e4)
|
|
635
|
+
});
|
|
636
|
+
} catch (error) {
|
|
637
|
+
const origin = new URL(url).origin;
|
|
638
|
+
if (isRefusedRedirect(error)) throw new Failure(`${origin} answered with a redirect when asked to ${what}. The CLI follows no redirect on a call that carries a credential: pass the final URL of the server.`);
|
|
639
|
+
throw new Failure(`cannot reach ${origin} to ${what}: ${error.message}`);
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
/** The error text of a JSON error body, `{"error": "..."}` or `{"error": {"message": "..."}}`, never the body. */
|
|
643
|
+
async function errorText(response) {
|
|
644
|
+
const body = await response.json().catch(() => null);
|
|
645
|
+
const error = body?.error;
|
|
646
|
+
if (typeof error === "string") return shortText(error);
|
|
647
|
+
if (error && typeof error === "object") return shortText(error.message);
|
|
648
|
+
return shortText(body?.message);
|
|
649
|
+
}
|
|
650
|
+
function checkProvisioned(app, stack) {
|
|
651
|
+
try {
|
|
652
|
+
const issuer = new URL(app.issuer);
|
|
653
|
+
if (issuer.protocol !== "https:" && issuer.protocol !== "http:") throw new Error("scheme");
|
|
654
|
+
} catch {
|
|
655
|
+
throw new Failure("Passflow answered without a usable issuer URL");
|
|
656
|
+
}
|
|
657
|
+
if (!/^[A-Za-z0-9_-]+$/.test(app.clientId)) throw new Failure("Passflow answered without a usable client ID");
|
|
658
|
+
if (stack.app_type === "bff" && !app.clientSecret) throw new Failure("Passflow answered without the app secret");
|
|
659
|
+
return app;
|
|
660
|
+
}
|
|
661
|
+
function cloudUrl(api, ...segments) {
|
|
662
|
+
return `${api.baseUrl}/saas/${segments.map(encodeURIComponent).join("/")}`;
|
|
663
|
+
}
|
|
664
|
+
async function cloudGet(api, segments, what) {
|
|
665
|
+
const response = await call(cloudUrl(api, ...segments), { headers: {
|
|
666
|
+
authorization: `Bearer ${api.bearer}`,
|
|
667
|
+
accept: "application/json"
|
|
668
|
+
} }, what);
|
|
669
|
+
if (!response.ok) throw new Failure(`Passflow Cloud refused to ${what} (${response.status} ${await errorText(response)})`.trim());
|
|
670
|
+
return await response.json();
|
|
671
|
+
}
|
|
672
|
+
async function listProjects(api, org) {
|
|
673
|
+
return ((await cloudGet(api, [
|
|
674
|
+
"org",
|
|
675
|
+
org,
|
|
676
|
+
"project"
|
|
677
|
+
], "list projects")).projects ?? []).filter((p) => typeof p.key === "string" && p.key !== "").map((p) => ({
|
|
678
|
+
key: p.key,
|
|
679
|
+
name: typeof p.name === "string" && p.name !== "" ? p.name : p.key
|
|
680
|
+
}));
|
|
681
|
+
}
|
|
682
|
+
async function listEnvironments(api, org, project) {
|
|
683
|
+
return ((await cloudGet(api, [
|
|
684
|
+
"org",
|
|
685
|
+
org,
|
|
686
|
+
"project",
|
|
687
|
+
project,
|
|
688
|
+
"environment"
|
|
689
|
+
], "list environments")).environments ?? []).filter((e) => typeof e.slug === "string" && e.slug !== "").map((e) => ({
|
|
690
|
+
slug: e.slug,
|
|
691
|
+
name: typeof e.name === "string" && e.name !== "" ? e.name : e.slug,
|
|
692
|
+
isProduction: e.isProduction === true
|
|
693
|
+
}));
|
|
694
|
+
}
|
|
695
|
+
/** POST /saas/org/{org}/project/{key}/environment/{env}/apps with {stack, base_url}. */
|
|
696
|
+
async function provisionCloudApp(api, target, stack, baseUrl) {
|
|
697
|
+
const response = await call(cloudUrl(api, "org", target.org, "project", target.project, "environment", target.env, "apps"), {
|
|
698
|
+
method: "POST",
|
|
699
|
+
headers: {
|
|
700
|
+
authorization: `Bearer ${api.bearer}`,
|
|
701
|
+
"content-type": "application/json",
|
|
702
|
+
accept: "application/json"
|
|
703
|
+
},
|
|
704
|
+
body: JSON.stringify({
|
|
705
|
+
stack: stack.id,
|
|
706
|
+
base_url: baseUrl
|
|
707
|
+
})
|
|
708
|
+
}, "create the app");
|
|
709
|
+
if (response.status === 403) throw new Failure(`you have no write access to environment ${target.env} of project ${target.project}, so no app was created (${await errorText(response)})`);
|
|
710
|
+
if (response.status !== 201 && response.status !== 200) throw new Failure(`Passflow Cloud did not create the app (${response.status} ${await errorText(response)})`.trim());
|
|
711
|
+
const body = await response.json().catch(() => ({}));
|
|
712
|
+
return checkProvisioned({
|
|
713
|
+
issuer: typeof body.issuer === "string" ? body.issuer : "",
|
|
714
|
+
clientId: typeof body.client_id === "string" ? body.client_id : "",
|
|
715
|
+
...typeof body.client_secret === "string" && body.client_secret !== "" ? { clientSecret: body.client_secret } : {}
|
|
716
|
+
}, stack);
|
|
717
|
+
}
|
|
718
|
+
const stackLabels = {
|
|
719
|
+
nextjs: "Next.js",
|
|
720
|
+
"tanstack-start": "TanStack Start",
|
|
721
|
+
"react-vite": "React (Vite)"
|
|
722
|
+
};
|
|
723
|
+
/** The same settings Passflow Cloud gives a stack's app. */
|
|
724
|
+
function appSettings(stack, baseUrl) {
|
|
725
|
+
const base = new URL(baseUrl);
|
|
726
|
+
const settings = {
|
|
727
|
+
name: `${stackLabels[stack.id] ?? stack.id} at ${base.host}`,
|
|
728
|
+
description: `Created by passflow integrate for ${baseUrl}`,
|
|
729
|
+
active: true,
|
|
730
|
+
type: stack.app_type,
|
|
731
|
+
offline: true,
|
|
732
|
+
pkce_enabled: true,
|
|
733
|
+
redirect_urls: [`${baseUrl}/auth/callback`, `${baseUrl}/`],
|
|
734
|
+
origins: [base.origin],
|
|
735
|
+
default_scopes: [
|
|
736
|
+
"openid",
|
|
737
|
+
"email",
|
|
738
|
+
"offline",
|
|
739
|
+
"id"
|
|
740
|
+
]
|
|
741
|
+
};
|
|
742
|
+
if (stack.app_type === "spa") settings.token_delivery_method = "json_body";
|
|
743
|
+
return settings;
|
|
744
|
+
}
|
|
745
|
+
/** The server's issuer, from its discovery document; read before any app is created. */
|
|
746
|
+
async function serverIssuer(api) {
|
|
747
|
+
const response = await call(`${api.serverUrl}/.well-known/openid-configuration`, { headers: { accept: "application/json" } }, "read its discovery document");
|
|
748
|
+
const body = await response.json().catch(() => ({}));
|
|
749
|
+
if (!response.ok || typeof body.issuer !== "string" || body.issuer === "") throw new Failure(`${api.serverUrl} has no OpenID Connect discovery document (${response.status})`);
|
|
750
|
+
return body.issuer;
|
|
751
|
+
}
|
|
752
|
+
/** POST /management/apps on a self-hosted Passflow, authorised by its management key. */
|
|
753
|
+
async function provisionServerApp(api, stack, baseUrl) {
|
|
754
|
+
const issuer = await serverIssuer(api);
|
|
755
|
+
const response = await call(`${api.serverUrl}/management/apps`, {
|
|
756
|
+
method: "POST",
|
|
757
|
+
headers: {
|
|
758
|
+
"x-passflow-key": api.managementKey,
|
|
759
|
+
"content-type": "application/json",
|
|
760
|
+
accept: "application/json"
|
|
761
|
+
},
|
|
762
|
+
body: JSON.stringify(appSettings(stack, baseUrl))
|
|
763
|
+
}, "create the app");
|
|
764
|
+
if (response.status === 401 || response.status === 403) throw new Failure(`${api.serverUrl} refused the management key, so no app was created (${response.status})`);
|
|
765
|
+
if (!response.ok) throw new Failure(`${api.serverUrl} did not create the app (${response.status} ${await errorText(response)})`.trim());
|
|
766
|
+
const body = await response.json().catch(() => ({}));
|
|
767
|
+
return checkProvisioned({
|
|
768
|
+
issuer,
|
|
769
|
+
clientId: typeof body.id === "string" ? body.id : "",
|
|
770
|
+
...stack.app_type === "bff" && typeof body.secret === "string" && body.secret !== "" ? { clientSecret: body.secret } : {}
|
|
771
|
+
}, stack);
|
|
772
|
+
}
|
|
773
|
+
// src/signin.ts
|
|
774
|
+
/** The CLI's public client in Passflow Cloud's own sign-in, on every cloud. */
|
|
775
|
+
const cliClientId = "3MNLwqSULj51i0rxBCdJJrZjR8k";
|
|
776
|
+
/** Without access:tenant:all the cloud's organization routes answer 403. */
|
|
777
|
+
const cliScopes = [
|
|
778
|
+
"openid",
|
|
779
|
+
"email",
|
|
780
|
+
"access:tenant:all",
|
|
781
|
+
"tenant:all",
|
|
782
|
+
"id"
|
|
783
|
+
];
|
|
784
|
+
const signInTimeoutMs = 3e5;
|
|
785
|
+
const callbackPath = "/callback";
|
|
786
|
+
function base64url(bytes) {
|
|
787
|
+
return bytes.toString("base64url");
|
|
788
|
+
}
|
|
789
|
+
const page = (title, text) => `<!doctype html><meta charset="utf-8"><title>${title}</title><body style="font-family:system-ui;margin:4rem auto;max-width:32rem"><h1>${title}</h1><p>${text}</p></body>`;
|
|
790
|
+
function openBrowser(url) {
|
|
791
|
+
const [command, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", [
|
|
792
|
+
"/c",
|
|
793
|
+
"start",
|
|
794
|
+
"\"\"",
|
|
795
|
+
url.replace(/&/g, "^&")
|
|
796
|
+
]] : ["xdg-open", [url]];
|
|
797
|
+
const path = findExecutable(command, { exclude: [process.cwd()] });
|
|
798
|
+
if (path === void 0) return;
|
|
799
|
+
try {
|
|
800
|
+
const child = spawn(path, args, {
|
|
801
|
+
stdio: "ignore",
|
|
802
|
+
detached: true
|
|
803
|
+
});
|
|
804
|
+
child.on("error", () => {});
|
|
805
|
+
child.unref();
|
|
806
|
+
} catch {}
|
|
807
|
+
}
|
|
808
|
+
/**
|
|
809
|
+
* Listens on 127.0.0.1 for the browser's return. `code` settles once: with the authorization code, or with the
|
|
810
|
+
* reason the sign-in failed (a refusal, no code, or 5 minutes without an answer). A callback whose state the CLI
|
|
811
|
+
* did not send is answered 400 and ignored, so another process calling the port cannot end the sign-in.
|
|
812
|
+
*/
|
|
813
|
+
function listen(state, timeoutMs = signInTimeoutMs) {
|
|
814
|
+
let settle = () => {};
|
|
815
|
+
const code = new Promise((resolve, reject) => {
|
|
816
|
+
settle = (error, value) => error || !value ? reject(error ?? new Failure("sign-in failed")) : resolve(value);
|
|
817
|
+
});
|
|
818
|
+
code.catch(() => {});
|
|
819
|
+
let settled = false;
|
|
820
|
+
const finish = (error, value) => {
|
|
821
|
+
if (settled) return;
|
|
822
|
+
settled = true;
|
|
823
|
+
settle(error, value);
|
|
824
|
+
};
|
|
825
|
+
const server = createServer((request, response) => {
|
|
826
|
+
const url = new URL(request.url ?? "/", "http://127.0.0.1");
|
|
827
|
+
if (url.pathname !== callbackPath) {
|
|
828
|
+
response.writeHead(404).end();
|
|
829
|
+
return;
|
|
830
|
+
}
|
|
831
|
+
const reply = (status, title, text) => {
|
|
832
|
+
response.writeHead(status, {
|
|
833
|
+
"content-type": "text/html; charset=utf-8",
|
|
834
|
+
"cache-control": "no-store",
|
|
835
|
+
"referrer-policy": "no-referrer"
|
|
836
|
+
});
|
|
837
|
+
response.end(page(title, text));
|
|
838
|
+
};
|
|
839
|
+
if (settled) {
|
|
840
|
+
reply(400, "Sign-in already finished", "You can close this tab.");
|
|
841
|
+
return;
|
|
842
|
+
}
|
|
843
|
+
const returned = Buffer.from(url.searchParams.get("state") ?? "");
|
|
844
|
+
const expected = Buffer.from(state);
|
|
845
|
+
if (returned.length !== expected.length || !timingSafeEqual(returned, expected)) {
|
|
846
|
+
reply(400, "Not this sign-in", "This sign-in did not come from the request the Passflow CLI started.");
|
|
847
|
+
return;
|
|
848
|
+
}
|
|
849
|
+
const error = url.searchParams.get("error");
|
|
850
|
+
if (error) {
|
|
851
|
+
reply(200, "Sign-in failed", "Passflow declined the sign-in. Return to your terminal.");
|
|
852
|
+
finish(new Failure(`sign-in declined: ${shortText(error)} ${shortText(url.searchParams.get("error_description"))}`.trim()));
|
|
853
|
+
return;
|
|
854
|
+
}
|
|
855
|
+
const value = url.searchParams.get("code");
|
|
856
|
+
if (!value) {
|
|
857
|
+
reply(400, "Sign-in failed", "The sign-in returned no code.");
|
|
858
|
+
finish(new Failure("the sign-in returned no authorization code"));
|
|
859
|
+
return;
|
|
860
|
+
}
|
|
861
|
+
reply(200, "Signed in", "The Passflow CLI is signed in. You can close this tab and return to your terminal.");
|
|
862
|
+
finish(null, value);
|
|
863
|
+
});
|
|
864
|
+
const timer = setTimeout(() => finish(new Failure("no browser sign-in within 5 minutes")), timeoutMs);
|
|
865
|
+
const close = () => {
|
|
866
|
+
clearTimeout(timer);
|
|
867
|
+
server.close();
|
|
868
|
+
server.closeAllConnections();
|
|
869
|
+
};
|
|
870
|
+
return new Promise((resolve, reject) => {
|
|
871
|
+
server.once("error", (error) => {
|
|
872
|
+
close();
|
|
873
|
+
reject(new Failure(`cannot listen on 127.0.0.1 for the sign-in: ${error.message}`));
|
|
874
|
+
});
|
|
875
|
+
server.listen(0, "127.0.0.1", () => resolve({
|
|
876
|
+
port: server.address().port,
|
|
877
|
+
code,
|
|
878
|
+
close
|
|
879
|
+
}));
|
|
880
|
+
});
|
|
881
|
+
}
|
|
882
|
+
/**
|
|
883
|
+
* Signs the user in to Passflow Cloud in their browser: authorization code with PKCE (S256), returned to a
|
|
884
|
+
* listener on 127.0.0.1, within 5 minutes. Returns the access token, which is kept in memory only.
|
|
885
|
+
*/
|
|
886
|
+
async function browserSignIn(cloudUrl, log) {
|
|
887
|
+
const verifier = base64url(randomBytes(32));
|
|
888
|
+
const challenge = base64url(createHash("sha256").update(verifier).digest());
|
|
889
|
+
const state = base64url(randomBytes(32));
|
|
890
|
+
const listener = await listen(state);
|
|
891
|
+
const redirectUri = `http://127.0.0.1:${listener.port}${callbackPath}`;
|
|
892
|
+
const authorize = new URL("/oidc/authorize", cloudUrl);
|
|
893
|
+
authorize.search = new URLSearchParams({
|
|
894
|
+
client_id: cliClientId,
|
|
895
|
+
response_type: "code",
|
|
896
|
+
redirect_uri: redirectUri,
|
|
897
|
+
scope: cliScopes.join(" "),
|
|
898
|
+
state,
|
|
899
|
+
code_challenge: challenge,
|
|
900
|
+
code_challenge_method: "S256"
|
|
901
|
+
}).toString();
|
|
902
|
+
log("Opening your browser to sign in to Passflow. If it does not open, visit:");
|
|
903
|
+
log(` ${authorize.toString()}`);
|
|
904
|
+
openBrowser(authorize.toString());
|
|
905
|
+
let code;
|
|
906
|
+
try {
|
|
907
|
+
code = await listener.code;
|
|
908
|
+
} finally {
|
|
909
|
+
listener.close();
|
|
910
|
+
}
|
|
911
|
+
let response;
|
|
912
|
+
try {
|
|
913
|
+
response = await fetch(new URL("/oidc/token", cloudUrl), {
|
|
914
|
+
method: "POST",
|
|
915
|
+
headers: {
|
|
916
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
917
|
+
accept: "application/json"
|
|
918
|
+
},
|
|
919
|
+
body: new URLSearchParams({
|
|
920
|
+
grant_type: "authorization_code",
|
|
921
|
+
code,
|
|
922
|
+
redirect_uri: redirectUri,
|
|
923
|
+
client_id: cliClientId,
|
|
924
|
+
code_verifier: verifier
|
|
925
|
+
}),
|
|
926
|
+
redirect: "error",
|
|
927
|
+
signal: AbortSignal.timeout(3e4)
|
|
928
|
+
});
|
|
929
|
+
} catch (error) {
|
|
930
|
+
if (isRefusedRedirect(error)) throw new Failure(`${cloudUrl} answered the token request with a redirect. The CLI follows no redirect on a call that carries a credential: pass the final URL with --cloud-url.`);
|
|
931
|
+
throw new Failure(`cannot reach ${cloudUrl} to finish the sign-in: ${error.message}`);
|
|
932
|
+
}
|
|
933
|
+
const body = await response.json().catch(() => ({}));
|
|
934
|
+
if (!response.ok || typeof body.access_token !== "string" || body.access_token === "") throw new Failure(`the sign-in was not accepted (${response.status} ${shortText(body.error)} ${shortText(body.error_description)})`.trim());
|
|
935
|
+
return body.access_token;
|
|
936
|
+
}
|
|
937
|
+
/** The organizations the access token says the user belongs to. The server checks every call; this only lists. */
|
|
938
|
+
function organizationsOf(accessToken) {
|
|
939
|
+
try {
|
|
940
|
+
const payload = JSON.parse(Buffer.from(accessToken.split(".")[1] ?? "", "base64url").toString("utf8"));
|
|
941
|
+
const out = [];
|
|
942
|
+
for (const entry of Object.values(payload.passflow_tm ?? {})) if (typeof entry?.tenant_id === "string" && entry.tenant_id !== "") out.push({
|
|
943
|
+
id: entry.tenant_id,
|
|
944
|
+
name: typeof entry.tenant_name === "string" ? entry.tenant_name : entry.tenant_id
|
|
945
|
+
});
|
|
946
|
+
return out;
|
|
947
|
+
} catch {
|
|
948
|
+
return [];
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
// skills/index.json
|
|
952
|
+
var skills_default = {
|
|
953
|
+
schema: 1,
|
|
954
|
+
package_managers: {
|
|
955
|
+
"supported": [
|
|
956
|
+
"npm",
|
|
957
|
+
"pnpm",
|
|
958
|
+
"yarn-classic"
|
|
959
|
+
],
|
|
960
|
+
"refused": ["yarn-berry", "bun"],
|
|
961
|
+
"detect": [
|
|
962
|
+
{
|
|
963
|
+
"file": "pnpm-lock.yaml",
|
|
964
|
+
"manager": "pnpm"
|
|
965
|
+
},
|
|
966
|
+
{
|
|
967
|
+
"file": "package-lock.json",
|
|
968
|
+
"manager": "npm"
|
|
969
|
+
},
|
|
970
|
+
{
|
|
971
|
+
"file": "yarn.lock",
|
|
972
|
+
"manager": "yarn-classic"
|
|
973
|
+
},
|
|
974
|
+
{
|
|
975
|
+
"file": ".yarnrc.yml",
|
|
976
|
+
"manager": "yarn-berry"
|
|
977
|
+
},
|
|
978
|
+
{
|
|
979
|
+
"file": "bun.lock",
|
|
980
|
+
"manager": "bun"
|
|
981
|
+
},
|
|
982
|
+
{
|
|
983
|
+
"file": "bun.lockb",
|
|
984
|
+
"manager": "bun"
|
|
985
|
+
}
|
|
986
|
+
]
|
|
987
|
+
},
|
|
988
|
+
stacks: [
|
|
989
|
+
{
|
|
990
|
+
"id": "tanstack-start",
|
|
991
|
+
"skill": "passflow-tanstack-start",
|
|
992
|
+
"detect": { "all": [{
|
|
993
|
+
"package": "@tanstack/react-start",
|
|
994
|
+
"range": ">=1.169.5"
|
|
995
|
+
}, {
|
|
996
|
+
"package": "@tanstack/react-router",
|
|
997
|
+
"range": ">=1.170.46"
|
|
998
|
+
}] },
|
|
999
|
+
"app_type": "bff",
|
|
1000
|
+
"default_base_url": "http://localhost:3000",
|
|
1001
|
+
"env_file": ".env.local",
|
|
1002
|
+
"env_keys": [
|
|
1003
|
+
"PASSFLOW_ISSUER",
|
|
1004
|
+
"PASSFLOW_CLIENT_ID",
|
|
1005
|
+
"PASSFLOW_CLIENT_SECRET",
|
|
1006
|
+
"PASSFLOW_SECRET",
|
|
1007
|
+
"APP_BASE_URL"
|
|
1008
|
+
],
|
|
1009
|
+
"secret_env_keys": ["PASSFLOW_CLIENT_SECRET", "PASSFLOW_SECRET"],
|
|
1010
|
+
"not_provisioned_env_keys": [],
|
|
1011
|
+
"packages": [{
|
|
1012
|
+
"name": "@passflow/tanstack-react-start",
|
|
1013
|
+
"version_env": "PASSFLOW_TANSTACK_REACT_START_VERSION",
|
|
1014
|
+
"env_keys": [
|
|
1015
|
+
"PASSFLOW_ISSUER",
|
|
1016
|
+
"PASSFLOW_CLIENT_ID",
|
|
1017
|
+
"PASSFLOW_CLIENT_SECRET",
|
|
1018
|
+
"PASSFLOW_SECRET",
|
|
1019
|
+
"APP_BASE_URL"
|
|
1020
|
+
]
|
|
1021
|
+
}],
|
|
1022
|
+
"allowed_paths": [
|
|
1023
|
+
"src/**",
|
|
1024
|
+
"app/**",
|
|
1025
|
+
".gitignore",
|
|
1026
|
+
"package.json",
|
|
1027
|
+
"package-lock.json",
|
|
1028
|
+
"pnpm-lock.yaml",
|
|
1029
|
+
"yarn.lock"
|
|
1030
|
+
],
|
|
1031
|
+
"denied_paths": [
|
|
1032
|
+
"next.config.*",
|
|
1033
|
+
"vite.config.*",
|
|
1034
|
+
"vitest.config.*",
|
|
1035
|
+
"app.config.*",
|
|
1036
|
+
"tsconfig*.json",
|
|
1037
|
+
"jsconfig*.json",
|
|
1038
|
+
"postcss.config.*",
|
|
1039
|
+
"tailwind.config.*",
|
|
1040
|
+
"eslint.config.*",
|
|
1041
|
+
".eslintrc*",
|
|
1042
|
+
"babel.config.*",
|
|
1043
|
+
".babelrc*",
|
|
1044
|
+
"turbo.json",
|
|
1045
|
+
"nx.json",
|
|
1046
|
+
"Dockerfile*",
|
|
1047
|
+
"docker-compose*",
|
|
1048
|
+
".github/**",
|
|
1049
|
+
".env*",
|
|
1050
|
+
"**/.env*",
|
|
1051
|
+
"scripts/**",
|
|
1052
|
+
".npmrc",
|
|
1053
|
+
"**/.npmrc",
|
|
1054
|
+
".yarnrc",
|
|
1055
|
+
".yarnrc.yml",
|
|
1056
|
+
".yarn/**",
|
|
1057
|
+
".pnp.cjs",
|
|
1058
|
+
".pnp.loader.mjs",
|
|
1059
|
+
"pnpm-workspace.yaml",
|
|
1060
|
+
"npm-shrinkwrap.json",
|
|
1061
|
+
"bun.lock",
|
|
1062
|
+
"bun.lockb"
|
|
1063
|
+
]
|
|
1064
|
+
},
|
|
1065
|
+
{
|
|
1066
|
+
"id": "nextjs",
|
|
1067
|
+
"skill": "passflow-nextjs",
|
|
1068
|
+
"detect": { "all": [{
|
|
1069
|
+
"package": "next",
|
|
1070
|
+
"range": ">=16"
|
|
1071
|
+
}] },
|
|
1072
|
+
"app_type": "bff",
|
|
1073
|
+
"default_base_url": "http://localhost:3000",
|
|
1074
|
+
"env_file": ".env.local",
|
|
1075
|
+
"env_keys": [
|
|
1076
|
+
"PASSFLOW_ISSUER",
|
|
1077
|
+
"PASSFLOW_CLIENT_ID",
|
|
1078
|
+
"PASSFLOW_CLIENT_SECRET",
|
|
1079
|
+
"PASSFLOW_SECRET",
|
|
1080
|
+
"APP_BASE_URL"
|
|
1081
|
+
],
|
|
1082
|
+
"secret_env_keys": ["PASSFLOW_CLIENT_SECRET", "PASSFLOW_SECRET"],
|
|
1083
|
+
"not_provisioned_env_keys": [],
|
|
1084
|
+
"packages": [{
|
|
1085
|
+
"name": "@passflow/nextjs",
|
|
1086
|
+
"version_env": "PASSFLOW_NEXTJS_VERSION",
|
|
1087
|
+
"env_keys": [
|
|
1088
|
+
"PASSFLOW_ISSUER",
|
|
1089
|
+
"PASSFLOW_CLIENT_ID",
|
|
1090
|
+
"PASSFLOW_CLIENT_SECRET",
|
|
1091
|
+
"PASSFLOW_SECRET",
|
|
1092
|
+
"APP_BASE_URL"
|
|
1093
|
+
]
|
|
1094
|
+
}],
|
|
1095
|
+
"allowed_paths": [
|
|
1096
|
+
"app/**",
|
|
1097
|
+
"src/**",
|
|
1098
|
+
"lib/**",
|
|
1099
|
+
"components/**",
|
|
1100
|
+
"proxy.ts",
|
|
1101
|
+
"proxy.js",
|
|
1102
|
+
"middleware.ts",
|
|
1103
|
+
"middleware.js",
|
|
1104
|
+
"src/proxy.ts",
|
|
1105
|
+
"src/proxy.js",
|
|
1106
|
+
"src/middleware.ts",
|
|
1107
|
+
"src/middleware.js",
|
|
1108
|
+
".gitignore",
|
|
1109
|
+
"package.json",
|
|
1110
|
+
"package-lock.json",
|
|
1111
|
+
"pnpm-lock.yaml",
|
|
1112
|
+
"yarn.lock"
|
|
1113
|
+
],
|
|
1114
|
+
"denied_paths": [
|
|
1115
|
+
"next.config.*",
|
|
1116
|
+
"vite.config.*",
|
|
1117
|
+
"vitest.config.*",
|
|
1118
|
+
"app.config.*",
|
|
1119
|
+
"tsconfig*.json",
|
|
1120
|
+
"jsconfig*.json",
|
|
1121
|
+
"postcss.config.*",
|
|
1122
|
+
"tailwind.config.*",
|
|
1123
|
+
"eslint.config.*",
|
|
1124
|
+
".eslintrc*",
|
|
1125
|
+
"babel.config.*",
|
|
1126
|
+
".babelrc*",
|
|
1127
|
+
"turbo.json",
|
|
1128
|
+
"nx.json",
|
|
1129
|
+
"Dockerfile*",
|
|
1130
|
+
"docker-compose*",
|
|
1131
|
+
".github/**",
|
|
1132
|
+
".env*",
|
|
1133
|
+
"**/.env*",
|
|
1134
|
+
"scripts/**",
|
|
1135
|
+
".npmrc",
|
|
1136
|
+
"**/.npmrc",
|
|
1137
|
+
".yarnrc",
|
|
1138
|
+
".yarnrc.yml",
|
|
1139
|
+
".yarn/**",
|
|
1140
|
+
".pnp.cjs",
|
|
1141
|
+
".pnp.loader.mjs",
|
|
1142
|
+
"pnpm-workspace.yaml",
|
|
1143
|
+
"npm-shrinkwrap.json",
|
|
1144
|
+
"bun.lock",
|
|
1145
|
+
"bun.lockb"
|
|
1146
|
+
]
|
|
1147
|
+
},
|
|
1148
|
+
{
|
|
1149
|
+
"id": "react-vite",
|
|
1150
|
+
"skill": "passflow-react-vite",
|
|
1151
|
+
"detect": { "all": [{ "package": "vite" }, { "package": "react" }] },
|
|
1152
|
+
"app_type": "spa",
|
|
1153
|
+
"default_base_url": "http://localhost:5173",
|
|
1154
|
+
"env_file": ".env.local",
|
|
1155
|
+
"env_keys": [
|
|
1156
|
+
"VITE_PASSFLOW_URL",
|
|
1157
|
+
"VITE_PASSFLOW_APP_ID",
|
|
1158
|
+
"VITE_API_URL",
|
|
1159
|
+
"PASSFLOW_ISSUER",
|
|
1160
|
+
"PASSFLOW_AUDIENCE",
|
|
1161
|
+
"APP_BASE_URL"
|
|
1162
|
+
],
|
|
1163
|
+
"secret_env_keys": [],
|
|
1164
|
+
"not_provisioned_env_keys": ["VITE_API_URL"],
|
|
1165
|
+
"packages": [{
|
|
1166
|
+
"name": "@passflow/react",
|
|
1167
|
+
"version_env": "PASSFLOW_REACT_VERSION",
|
|
1168
|
+
"env_keys": [
|
|
1169
|
+
"VITE_PASSFLOW_URL",
|
|
1170
|
+
"VITE_PASSFLOW_APP_ID",
|
|
1171
|
+
"VITE_API_URL"
|
|
1172
|
+
]
|
|
1173
|
+
}, {
|
|
1174
|
+
"name": "@passflow/node",
|
|
1175
|
+
"version_env": "PASSFLOW_NODE_VERSION",
|
|
1176
|
+
"env_keys": [
|
|
1177
|
+
"PASSFLOW_ISSUER",
|
|
1178
|
+
"PASSFLOW_AUDIENCE",
|
|
1179
|
+
"APP_BASE_URL"
|
|
1180
|
+
]
|
|
1181
|
+
}],
|
|
1182
|
+
"allowed_paths": [
|
|
1183
|
+
"src/**",
|
|
1184
|
+
"server/**",
|
|
1185
|
+
"api/**",
|
|
1186
|
+
".gitignore",
|
|
1187
|
+
"package.json",
|
|
1188
|
+
"package-lock.json",
|
|
1189
|
+
"pnpm-lock.yaml",
|
|
1190
|
+
"yarn.lock"
|
|
1191
|
+
],
|
|
1192
|
+
"denied_paths": [
|
|
1193
|
+
"next.config.*",
|
|
1194
|
+
"vite.config.*",
|
|
1195
|
+
"vitest.config.*",
|
|
1196
|
+
"app.config.*",
|
|
1197
|
+
"tsconfig*.json",
|
|
1198
|
+
"jsconfig*.json",
|
|
1199
|
+
"postcss.config.*",
|
|
1200
|
+
"tailwind.config.*",
|
|
1201
|
+
"eslint.config.*",
|
|
1202
|
+
".eslintrc*",
|
|
1203
|
+
"babel.config.*",
|
|
1204
|
+
".babelrc*",
|
|
1205
|
+
"turbo.json",
|
|
1206
|
+
"nx.json",
|
|
1207
|
+
"Dockerfile*",
|
|
1208
|
+
"docker-compose*",
|
|
1209
|
+
".github/**",
|
|
1210
|
+
".env*",
|
|
1211
|
+
"**/.env*",
|
|
1212
|
+
"scripts/**",
|
|
1213
|
+
".npmrc",
|
|
1214
|
+
"**/.npmrc",
|
|
1215
|
+
".yarnrc",
|
|
1216
|
+
".yarnrc.yml",
|
|
1217
|
+
".yarn/**",
|
|
1218
|
+
".pnp.cjs",
|
|
1219
|
+
".pnp.loader.mjs",
|
|
1220
|
+
"pnpm-workspace.yaml",
|
|
1221
|
+
"npm-shrinkwrap.json",
|
|
1222
|
+
"bun.lock",
|
|
1223
|
+
"bun.lockb",
|
|
1224
|
+
"index.html"
|
|
1225
|
+
]
|
|
1226
|
+
},
|
|
1227
|
+
{
|
|
1228
|
+
"id": "node-api",
|
|
1229
|
+
"skill": "passflow-node-api",
|
|
1230
|
+
"detect": { "any": [
|
|
1231
|
+
{ "package": "express" },
|
|
1232
|
+
{ "package": "fastify" },
|
|
1233
|
+
{ "package": "hono" }
|
|
1234
|
+
] },
|
|
1235
|
+
"app_type": null,
|
|
1236
|
+
"default_base_url": null,
|
|
1237
|
+
"env_file": ".env",
|
|
1238
|
+
"env_keys": ["PASSFLOW_ISSUER", "PASSFLOW_AUDIENCE"],
|
|
1239
|
+
"secret_env_keys": [],
|
|
1240
|
+
"not_provisioned_env_keys": [],
|
|
1241
|
+
"packages": [{
|
|
1242
|
+
"name": "@passflow/node",
|
|
1243
|
+
"version_env": "PASSFLOW_NODE_VERSION",
|
|
1244
|
+
"env_keys": ["PASSFLOW_ISSUER", "PASSFLOW_AUDIENCE"]
|
|
1245
|
+
}],
|
|
1246
|
+
"allowed_paths": [
|
|
1247
|
+
"src/**",
|
|
1248
|
+
"server/**",
|
|
1249
|
+
"lib/**",
|
|
1250
|
+
"routes/**",
|
|
1251
|
+
"index.ts",
|
|
1252
|
+
"index.js",
|
|
1253
|
+
"index.mjs",
|
|
1254
|
+
"server.ts",
|
|
1255
|
+
"server.js",
|
|
1256
|
+
"server.mjs",
|
|
1257
|
+
"app.ts",
|
|
1258
|
+
"app.js",
|
|
1259
|
+
"app.mjs",
|
|
1260
|
+
"main.ts",
|
|
1261
|
+
"main.js",
|
|
1262
|
+
"main.mjs",
|
|
1263
|
+
".gitignore",
|
|
1264
|
+
"package.json",
|
|
1265
|
+
"package-lock.json",
|
|
1266
|
+
"pnpm-lock.yaml",
|
|
1267
|
+
"yarn.lock"
|
|
1268
|
+
],
|
|
1269
|
+
"denied_paths": [
|
|
1270
|
+
"next.config.*",
|
|
1271
|
+
"vite.config.*",
|
|
1272
|
+
"vitest.config.*",
|
|
1273
|
+
"app.config.*",
|
|
1274
|
+
"tsconfig*.json",
|
|
1275
|
+
"jsconfig*.json",
|
|
1276
|
+
"postcss.config.*",
|
|
1277
|
+
"tailwind.config.*",
|
|
1278
|
+
"eslint.config.*",
|
|
1279
|
+
".eslintrc*",
|
|
1280
|
+
"babel.config.*",
|
|
1281
|
+
".babelrc*",
|
|
1282
|
+
"turbo.json",
|
|
1283
|
+
"nx.json",
|
|
1284
|
+
"Dockerfile*",
|
|
1285
|
+
"docker-compose*",
|
|
1286
|
+
".github/**",
|
|
1287
|
+
".env*",
|
|
1288
|
+
"**/.env*",
|
|
1289
|
+
"scripts/**",
|
|
1290
|
+
".npmrc",
|
|
1291
|
+
"**/.npmrc",
|
|
1292
|
+
".yarnrc",
|
|
1293
|
+
".yarnrc.yml",
|
|
1294
|
+
".yarn/**",
|
|
1295
|
+
".pnp.cjs",
|
|
1296
|
+
".pnp.loader.mjs",
|
|
1297
|
+
"pnpm-workspace.yaml",
|
|
1298
|
+
"npm-shrinkwrap.json",
|
|
1299
|
+
"bun.lock",
|
|
1300
|
+
"bun.lockb"
|
|
1301
|
+
]
|
|
1302
|
+
}
|
|
1303
|
+
]
|
|
1304
|
+
};
|
|
1305
|
+
// src/skills.ts
|
|
1306
|
+
/** skills/index.json as vendored under sdk/cli/skills when the CLI was built. */
|
|
1307
|
+
function skillsIndex() {
|
|
1308
|
+
const index = skills_default;
|
|
1309
|
+
if (index.schema !== 1) throw new Failure(`this CLI reads skills index schema 1, not ${index.schema}`);
|
|
1310
|
+
return index;
|
|
1311
|
+
}
|
|
1312
|
+
/** The skill directories ship beside dist/ in the package. */
|
|
1313
|
+
function skillSource(name) {
|
|
1314
|
+
return fileURLToPath(new URL(`../skills/${name}/`, import.meta.url));
|
|
1315
|
+
}
|
|
1316
|
+
/** The places an agent looks for skills, relative to the project. */
|
|
1317
|
+
const skillHomes = [".claude/skills", ".agents/skills"];
|
|
1318
|
+
/** The file the CLI writes beside a skill it installs: the skill, the skills commit it came from, each file's sha256. */
|
|
1319
|
+
const manifestName = ".passflow-skill.json";
|
|
1320
|
+
/** lstat, or `undefined` when nothing is there. */
|
|
1321
|
+
function lstatOrNone(path) {
|
|
1322
|
+
try {
|
|
1323
|
+
return lstatSync(path);
|
|
1324
|
+
} catch (error) {
|
|
1325
|
+
if (error.code === "ENOENT") return void 0;
|
|
1326
|
+
throw error;
|
|
1327
|
+
}
|
|
1328
|
+
}
|
|
1329
|
+
/**
|
|
1330
|
+
* The sha256 of every file under `dir`, by `/`-separated relative path, leaving out the top-level manifest.
|
|
1331
|
+
* `undefined` when the tree holds anything but directories and plain files, such as a symlink: it never matches.
|
|
1332
|
+
*/
|
|
1333
|
+
function fileHashes(dir) {
|
|
1334
|
+
const hashes = /* @__PURE__ */ new Map();
|
|
1335
|
+
for (const entry of readdirSync(dir, {
|
|
1336
|
+
recursive: true,
|
|
1337
|
+
withFileTypes: true
|
|
1338
|
+
})) {
|
|
1339
|
+
if (entry.isDirectory()) continue;
|
|
1340
|
+
if (!entry.isFile()) return void 0;
|
|
1341
|
+
const path = join(entry.parentPath, entry.name);
|
|
1342
|
+
const name = relative(dir, path).split(sep).join("/");
|
|
1343
|
+
if (name === ".passflow-skill.json") continue;
|
|
1344
|
+
hashes.set(name, createHash("sha256").update(readFileSync(path)).digest("hex"));
|
|
1345
|
+
}
|
|
1346
|
+
return hashes;
|
|
1347
|
+
}
|
|
1348
|
+
function sameFiles(a, b) {
|
|
1349
|
+
return a.size === b.size && [...a].every(([name, hash]) => b.get(name) === hash);
|
|
1350
|
+
}
|
|
1351
|
+
/**
|
|
1352
|
+
* The usepassflow/skills commit the bundled skills were vendored from: skills/REVISION, which the vendor script
|
|
1353
|
+
* writes with the checkout's full HEAD commit.
|
|
1354
|
+
*/
|
|
1355
|
+
function skillsRevision() {
|
|
1356
|
+
const path = fileURLToPath(new URL("../skills/REVISION", import.meta.url));
|
|
1357
|
+
let revision;
|
|
1358
|
+
try {
|
|
1359
|
+
revision = readFileSync(path, "utf8").trim();
|
|
1360
|
+
} catch {
|
|
1361
|
+
throw new Failure("skills/REVISION is missing from this CLI package");
|
|
1362
|
+
}
|
|
1363
|
+
if (!/^[0-9a-f]{40}$/.test(revision)) throw new Failure("skills/REVISION does not hold a full commit id");
|
|
1364
|
+
return revision;
|
|
1365
|
+
}
|
|
1366
|
+
/** The hashes a manifest records, when it is a plain file that names this skill; otherwise `undefined`. */
|
|
1367
|
+
function recordedFiles(dir, name) {
|
|
1368
|
+
const path = join(dir, manifestName);
|
|
1369
|
+
if (!lstatOrNone(path)?.isFile()) return void 0;
|
|
1370
|
+
let manifest;
|
|
1371
|
+
try {
|
|
1372
|
+
manifest = JSON.parse(readFileSync(path, "utf8"));
|
|
1373
|
+
} catch {
|
|
1374
|
+
return;
|
|
1375
|
+
}
|
|
1376
|
+
if (manifest.skill !== name || typeof manifest.files !== "object" || manifest.files === null) return void 0;
|
|
1377
|
+
const files = Object.entries(manifest.files);
|
|
1378
|
+
return files.every(([, hash]) => typeof hash === "string") ? new Map(files) : void 0;
|
|
1379
|
+
}
|
|
1380
|
+
/** The bundled copy of a skill and its file hashes. */
|
|
1381
|
+
function bundled(name) {
|
|
1382
|
+
const source = skillSource(name);
|
|
1383
|
+
const hashes = existsSync(join(source, "SKILL.md")) ? fileHashes(source) : void 0;
|
|
1384
|
+
if (!hashes) throw new Failure(`the ${name} skill is missing from this CLI package`);
|
|
1385
|
+
return {
|
|
1386
|
+
source,
|
|
1387
|
+
hashes
|
|
1388
|
+
};
|
|
1389
|
+
}
|
|
1390
|
+
/**
|
|
1391
|
+
* Decides, before anything is created, what happens in .claude/skills/<name>/ and .agents/skills/<name>/, and
|
|
1392
|
+
* refuses a destination Passflow must not write. Any of `.claude`, `.claude/skills`, `.agents`, `.agents/skills`
|
|
1393
|
+
* or the skill's own directory that is a symlink or not a directory is refused: a symlink could lead outside the
|
|
1394
|
+
* project. A skill directory that matches the bundled copy is left as it is. One whose manifest still records
|
|
1395
|
+
* every file it holds is replaced. Any other (no manifest, or a file changed, added or removed) is refused, so
|
|
1396
|
+
* local work is never deleted.
|
|
1397
|
+
*/
|
|
1398
|
+
function preflightSkill(projectDir, name) {
|
|
1399
|
+
const { hashes } = bundled(name);
|
|
1400
|
+
const plan = /* @__PURE__ */ new Map();
|
|
1401
|
+
for (const home of skillHomes) {
|
|
1402
|
+
let path = projectDir;
|
|
1403
|
+
let action = "install";
|
|
1404
|
+
for (const part of [...home.split("/"), name]) {
|
|
1405
|
+
path = join(path, part);
|
|
1406
|
+
const stat = lstatOrNone(path);
|
|
1407
|
+
if (stat === void 0) break;
|
|
1408
|
+
const shown = relative(projectDir, path);
|
|
1409
|
+
if (stat.isSymbolicLink()) throw new Refusal(`${shown} is a symlink. Passflow installs its skill only into plain directories in the project.`);
|
|
1410
|
+
if (!stat.isDirectory()) throw new Refusal(`${shown} is not a directory.`);
|
|
1411
|
+
if (part !== name) continue;
|
|
1412
|
+
const local = fileHashes(path);
|
|
1413
|
+
const recorded = recordedFiles(path, name);
|
|
1414
|
+
if (local && sameFiles(local, hashes)) action = "current";
|
|
1415
|
+
else if (local && recorded && sameFiles(local, recorded)) action = "replace";
|
|
1416
|
+
else throw new Refusal(`${shown} is not a copy of the ${name} skill that Passflow installed and nobody changed since, so Passflow leaves it alone. Move or delete ${shown}, then run passflow integrate again.`);
|
|
1417
|
+
}
|
|
1418
|
+
plan.set(`${home}/${name}`, action);
|
|
1419
|
+
}
|
|
1420
|
+
return plan;
|
|
1421
|
+
}
|
|
1422
|
+
/**
|
|
1423
|
+
* Installs the stack's skill as `preflightSkill` decides, which runs again first: a directory it creates or
|
|
1424
|
+
* replaces gets the bundled copy and a new manifest. Returns each directory, relative to the project, with what
|
|
1425
|
+
* was done there.
|
|
1426
|
+
*/
|
|
1427
|
+
function installSkill(projectDir, name) {
|
|
1428
|
+
const { source, hashes } = bundled(name);
|
|
1429
|
+
const plan = preflightSkill(projectDir, name);
|
|
1430
|
+
const manifest = {
|
|
1431
|
+
skill: name,
|
|
1432
|
+
revision: skillsRevision(),
|
|
1433
|
+
files: Object.fromEntries(hashes)
|
|
1434
|
+
};
|
|
1435
|
+
for (const [destination, action] of plan) {
|
|
1436
|
+
if (action === "current") continue;
|
|
1437
|
+
const target = join(projectDir, destination);
|
|
1438
|
+
rmSync(target, {
|
|
1439
|
+
recursive: true,
|
|
1440
|
+
force: true
|
|
1441
|
+
});
|
|
1442
|
+
cpSync(source, target, { recursive: true });
|
|
1443
|
+
writeFileSync(join(target, manifestName), `${JSON.stringify(manifest, null, 2)}\n`);
|
|
1444
|
+
}
|
|
1445
|
+
return [...plan];
|
|
1446
|
+
}
|
|
1447
|
+
// src/integrate.ts
|
|
1448
|
+
const log = (line = "") => {
|
|
1449
|
+
process.stdout.write(`${line}\n`);
|
|
1450
|
+
};
|
|
1451
|
+
const knownNames = /* @__PURE__ */ new Set([
|
|
1452
|
+
"PASSFLOW_ISSUER",
|
|
1453
|
+
"VITE_PASSFLOW_URL",
|
|
1454
|
+
"PASSFLOW_CLIENT_ID",
|
|
1455
|
+
"VITE_PASSFLOW_APP_ID",
|
|
1456
|
+
"PASSFLOW_AUDIENCE",
|
|
1457
|
+
"PASSFLOW_CLIENT_SECRET",
|
|
1458
|
+
"PASSFLOW_SECRET",
|
|
1459
|
+
"APP_BASE_URL",
|
|
1460
|
+
"VITE_API_URL"
|
|
1461
|
+
]);
|
|
1462
|
+
function valueFor(name, values) {
|
|
1463
|
+
switch (name) {
|
|
1464
|
+
case "PASSFLOW_ISSUER":
|
|
1465
|
+
case "VITE_PASSFLOW_URL": return values.issuer;
|
|
1466
|
+
case "PASSFLOW_CLIENT_ID":
|
|
1467
|
+
case "VITE_PASSFLOW_APP_ID":
|
|
1468
|
+
case "PASSFLOW_AUDIENCE": return values.clientId;
|
|
1469
|
+
case "PASSFLOW_CLIENT_SECRET":
|
|
1470
|
+
if (!values.clientSecret) throw new Failure("no client secret to write");
|
|
1471
|
+
return values.clientSecret;
|
|
1472
|
+
case "PASSFLOW_SECRET": return randomBytes(32).toString("base64url");
|
|
1473
|
+
case "APP_BASE_URL":
|
|
1474
|
+
if (!values.baseUrl) throw new Failure("no base URL to write");
|
|
1475
|
+
return values.baseUrl;
|
|
1476
|
+
case "VITE_API_URL":
|
|
1477
|
+
if (!values.apiUrl) throw new Failure("no API URL to write");
|
|
1478
|
+
return values.apiUrl;
|
|
1479
|
+
default: throw new Failure(`${name} is unknown to this CLI version`);
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
/** Whether the name holds a secret: the stack's secret names, and the session key the CLI generates. */
|
|
1483
|
+
function isSecret(stack, name) {
|
|
1484
|
+
return stack.secret_env_keys.includes(name) || name === "PASSFLOW_SECRET";
|
|
1485
|
+
}
|
|
1486
|
+
/** One of several, picked by a flag, by being the only one, or by asking; otherwise the flag is required. */
|
|
1487
|
+
async function pick(what, flag, items, label) {
|
|
1488
|
+
const only = items.length === 1 ? items[0] : void 0;
|
|
1489
|
+
if (only !== void 0) return only;
|
|
1490
|
+
if (items.length === 0) throw new Failure(`no ${what} to choose from`);
|
|
1491
|
+
if (!canAsk()) throw new Refusal(`pass ${flag}: there is more than one ${what} (${items.map(label).join(", ")}).`);
|
|
1492
|
+
return choose(`Which ${what}?`, items, label);
|
|
1493
|
+
}
|
|
1494
|
+
async function provisionInCloud(options, stack, baseUrl) {
|
|
1495
|
+
const apiKey = process.env.PASSFLOW_API_KEY ?? "";
|
|
1496
|
+
let api;
|
|
1497
|
+
if (apiKey !== "") {
|
|
1498
|
+
const missing = [
|
|
1499
|
+
"org",
|
|
1500
|
+
"project",
|
|
1501
|
+
"env"
|
|
1502
|
+
].filter((flag) => !options[flag]).map((flag) => `--${flag}`);
|
|
1503
|
+
if (missing.length > 0) throw new Refusal(`with PASSFLOW_API_KEY, pass ${missing.join(", ")} as well.`);
|
|
1504
|
+
log(`Signing in to ${options.cloudUrl} with PASSFLOW_API_KEY.`);
|
|
1505
|
+
api = {
|
|
1506
|
+
baseUrl: options.cloudUrl,
|
|
1507
|
+
bearer: apiKey
|
|
1508
|
+
};
|
|
1509
|
+
} else {
|
|
1510
|
+
const token = await browserSignIn(options.cloudUrl, log);
|
|
1511
|
+
log("Signed in.");
|
|
1512
|
+
api = {
|
|
1513
|
+
baseUrl: options.cloudUrl,
|
|
1514
|
+
bearer: token
|
|
1515
|
+
};
|
|
1516
|
+
}
|
|
1517
|
+
let org = options.org;
|
|
1518
|
+
if (!org) {
|
|
1519
|
+
const orgs = organizationsOf(api.bearer);
|
|
1520
|
+
if (orgs.length === 0) throw new Refusal("pass --org: the sign-in named no organization.");
|
|
1521
|
+
org = (await pick("organization", "--org", orgs, (o) => `${displayName(o.name)} (${displayName(o.id)})`)).id;
|
|
1522
|
+
}
|
|
1523
|
+
let project = options.project;
|
|
1524
|
+
if (!project) {
|
|
1525
|
+
const projects = await listProjects(api, org);
|
|
1526
|
+
if (projects.length === 0) throw new Failure(`organization ${displayName(org)} has no projects. Create one in the Passflow portal.`);
|
|
1527
|
+
project = (await pick("project", "--project", projects, (p) => `${displayName(p.name)} (${displayName(p.key)})`)).key;
|
|
1528
|
+
}
|
|
1529
|
+
let env = options.env;
|
|
1530
|
+
if (!env) {
|
|
1531
|
+
const environments = (await listEnvironments(api, org, project)).filter((e) => !e.isProduction);
|
|
1532
|
+
if (environments.length === 0) throw new Failure(`project ${displayName(project)} has no non-production environment. Pass --env prod to use production.`);
|
|
1533
|
+
env = (await pick("environment", "--env", environments, (e) => `${displayName(e.name)} (${displayName(e.slug)})`)).slug;
|
|
1534
|
+
}
|
|
1535
|
+
log(`Creating the app in organization ${displayName(org)}, project ${displayName(project)}, environment ${displayName(env)}.`);
|
|
1536
|
+
return provisionCloudApp(api, {
|
|
1537
|
+
org,
|
|
1538
|
+
project,
|
|
1539
|
+
env
|
|
1540
|
+
}, stack, baseUrl);
|
|
1541
|
+
}
|
|
1542
|
+
/** One or more Passflow client IDs, comma-separated, normalised to `a,b` with no repeats. */
|
|
1543
|
+
function checkAudience(audience) {
|
|
1544
|
+
const ids = [...new Set(audience.split(",").map((id) => id.trim()).filter(Boolean))];
|
|
1545
|
+
if (ids.length === 0 || !ids.every((id) => /^[A-Za-z0-9_-]+$/.test(id))) throw new Refusal("--audience must be one or more Passflow client IDs, separated by commas.");
|
|
1546
|
+
return ids.join(",");
|
|
1547
|
+
}
|
|
1548
|
+
async function nodeApiValues(options) {
|
|
1549
|
+
let issuer = options.issuer;
|
|
1550
|
+
let audience = options.audience;
|
|
1551
|
+
if ((!issuer || !audience) && !canAsk()) throw new Refusal("a Node API gets no app of its own: pass --issuer and --audience, the issuer and the client ID of the app whose tokens it accepts.");
|
|
1552
|
+
if (!issuer || !audience) log("A Node API gets no app of its own. It accepts the tokens of the app that signs users in.");
|
|
1553
|
+
issuer ??= await ask("Issuer URL of that app (for example https://<key>.passflow.cloud): ");
|
|
1554
|
+
audience ??= await ask("Client ID of that app (several apps: separate them with commas): ");
|
|
1555
|
+
return {
|
|
1556
|
+
issuer: checkUrl("--issuer", issuer),
|
|
1557
|
+
clientId: checkAudience(audience)
|
|
1558
|
+
};
|
|
1559
|
+
}
|
|
1560
|
+
/** `passflow integrate`. Returns the exit code. */
|
|
1561
|
+
async function integrate(options) {
|
|
1562
|
+
const dir = resolve(options.dir);
|
|
1563
|
+
const index = skillsIndex();
|
|
1564
|
+
const pkg = readPackageJson(dir);
|
|
1565
|
+
const stack = detectStack(pkg, index);
|
|
1566
|
+
const manager = detectPackageManager(dir, pkg, index);
|
|
1567
|
+
log(`Stack: ${stack.id} (skill ${stack.skill}), package manager: ${manager}.`);
|
|
1568
|
+
const unknown = stack.env_keys.filter((name) => !knownNames.has(name));
|
|
1569
|
+
if (unknown.length > 0) throw new Failure(`this CLI version cannot write ${unknown.join(", ")}. Update passflow.`);
|
|
1570
|
+
const envPath = join(dir, stack.env_file);
|
|
1571
|
+
const examplePath = join(dir, ".env.example");
|
|
1572
|
+
const inCheckout = isGitCheckout(dir);
|
|
1573
|
+
const state = preflightEnvFile(dir, stack.env_file, inCheckout);
|
|
1574
|
+
assertPlainFile(examplePath);
|
|
1575
|
+
const needsIgnoreRule = !isIgnored(dir, stack.env_file, inCheckout);
|
|
1576
|
+
if (needsIgnoreRule) assertPlainFile(join(dir, ".gitignore"));
|
|
1577
|
+
preflightSkill(dir, stack.skill);
|
|
1578
|
+
const provisioned = stack.env_keys.filter((name) => !stack.not_provisioned_env_keys.includes(name));
|
|
1579
|
+
const present = provisioned.filter((name) => state.keys.has(name));
|
|
1580
|
+
const configured = present.length === provisioned.length;
|
|
1581
|
+
if (present.length > 0 && !configured) {
|
|
1582
|
+
const missing = provisioned.filter((name) => !state.keys.has(name));
|
|
1583
|
+
throw new Refusal(`${stack.env_file} has some of the Passflow settings but not all: it has ${present.join(", ")} and lacks ${missing.join(", ")}. Remove the Passflow lines to create a new app, or add the missing ones yourself.`);
|
|
1584
|
+
}
|
|
1585
|
+
const baseUrl = stack.app_type ? checkBaseUrl("--base-url", options.baseUrl ?? stack.default_base_url ?? "") : void 0;
|
|
1586
|
+
const apiUrl = stack.env_keys.includes("VITE_API_URL") ? checkUrl("--api-url", options.apiUrl) : void 0;
|
|
1587
|
+
let values;
|
|
1588
|
+
if (configured) log(`${stack.env_file} already has the Passflow settings: no app is created.`);
|
|
1589
|
+
else {
|
|
1590
|
+
let app;
|
|
1591
|
+
if (!stack.app_type) app = await nodeApiValues(options);
|
|
1592
|
+
else if (options.server && options.managementKey && baseUrl) {
|
|
1593
|
+
log(`Creating the app on ${options.server}.`);
|
|
1594
|
+
app = await provisionServerApp({
|
|
1595
|
+
serverUrl: options.server,
|
|
1596
|
+
managementKey: options.managementKey
|
|
1597
|
+
}, stack, baseUrl);
|
|
1598
|
+
} else if (baseUrl) app = await provisionInCloud(options, stack, baseUrl);
|
|
1599
|
+
else throw new Failure("no base URL");
|
|
1600
|
+
if (stack.app_type) log(`Created ${stack.app_type} app ${displayName(app.clientId)} for ${baseUrl}.`);
|
|
1601
|
+
values = {
|
|
1602
|
+
issuer: app.issuer,
|
|
1603
|
+
clientId: app.clientId,
|
|
1604
|
+
...app.clientSecret ? { clientSecret: app.clientSecret } : {},
|
|
1605
|
+
...baseUrl ? { baseUrl } : {},
|
|
1606
|
+
...apiUrl ? { apiUrl } : {}
|
|
1607
|
+
};
|
|
1608
|
+
}
|
|
1609
|
+
const inCheckoutNow = isGitCheckout(dir);
|
|
1610
|
+
preflightEnvFile(dir, stack.env_file, inCheckoutNow);
|
|
1611
|
+
if (!needsIgnoreRule && !isIgnored(dir, stack.env_file, inCheckoutNow)) throw new Refusal(`${stack.env_file} is no longer ignored by git (did .gitignore or the branch change during sign-in?), so no secret was written. Run passflow integrate again.`);
|
|
1612
|
+
if (needsIgnoreRule) {
|
|
1613
|
+
addToGitignore(dir, stack.env_file, inCheckoutNow);
|
|
1614
|
+
log(`Added ${stack.env_file} to .gitignore.`);
|
|
1615
|
+
}
|
|
1616
|
+
const forEnv = values ? stack.env_keys.map((name) => [name, valueFor(name, values)]) : stack.not_provisioned_env_keys.map((name) => [name, valueFor(name, {
|
|
1617
|
+
issuer: "",
|
|
1618
|
+
clientId: "",
|
|
1619
|
+
...apiUrl ? { apiUrl } : {}
|
|
1620
|
+
})]);
|
|
1621
|
+
const has = readEnvFile(envPath).keys;
|
|
1622
|
+
if (process.platform === "win32" && forEnv.some(([name]) => !has.has(name) && isSecret(stack, name))) log(`Passflow can't restrict who reads ${stack.env_file} on Windows. It holds secrets: check that only your account can read it.`);
|
|
1623
|
+
const written = appendEnv(envPath, forEnv, { ownerOnly: true });
|
|
1624
|
+
if (written.previousMode !== void 0) log(`Set ${stack.env_file} to mode 600 (was ${written.previousMode.toString(8)}): only you can read its secrets.`);
|
|
1625
|
+
if (written.names.length > 0) log(`Wrote ${written.names.join(", ")} to ${stack.env_file}.`);
|
|
1626
|
+
const empty = provisioned.filter((name) => state.emptyKeys.has(name));
|
|
1627
|
+
if (configured && empty.length > 0) log(`${stack.env_file} has no value for ${empty.join(", ")}: fill them in.`);
|
|
1628
|
+
const exampleWritten = appendEnv(examplePath, stack.env_keys.map((name) => [name, !values || isSecret(stack, name) ? "" : valueFor(name, values)])).names;
|
|
1629
|
+
if (exampleWritten.length > 0) log(`Wrote ${exampleWritten.join(", ")} to .env.example, with the secrets left empty.`);
|
|
1630
|
+
for (const [path, action] of installSkill(dir, stack.skill)) if (action === "current") log(`The ${stack.skill} skill in ${path}/ is already up to date.`);
|
|
1631
|
+
else log(`${action === "replace" ? "Updated" : "Installed"} the ${stack.skill} skill in ${path}/.`);
|
|
1632
|
+
const prompt = agentPrompt(stack);
|
|
1633
|
+
if (options.agent) {
|
|
1634
|
+
log(`Starting ${options.agent}.`);
|
|
1635
|
+
return runAgent(options.agent, prompt, dir);
|
|
1636
|
+
}
|
|
1637
|
+
log();
|
|
1638
|
+
log("Next: give your coding agent this prompt, or run passflow integrate again with --agent claude|codex|cursor-agent.");
|
|
1639
|
+
log();
|
|
1640
|
+
log(prompt);
|
|
1641
|
+
return 0;
|
|
1642
|
+
}
|
|
1643
|
+
// src/cli.ts
|
|
1644
|
+
const defaultCloudUrl = "https://auth.passflow.cloud";
|
|
1645
|
+
const defaultApiUrl = "http://localhost:8086";
|
|
1646
|
+
const usage = `Usage: passflow integrate [options]
|
|
1647
|
+
|
|
1648
|
+
Detects your app's stack, creates a Passflow app for it, writes its env file, installs the
|
|
1649
|
+
matching agent skill, and hands over to your coding agent.
|
|
1650
|
+
|
|
1651
|
+
Passflow Cloud (the default):
|
|
1652
|
+
Signs you in through your browser. Set PASSFLOW_API_KEY (an organization API key with
|
|
1653
|
+
write access) to sign in without a browser; then --org, --project and --env are required.
|
|
1654
|
+
--org <id> organization
|
|
1655
|
+
--project <key> project
|
|
1656
|
+
--env <slug> environment (default: the project's non-production one)
|
|
1657
|
+
--cloud-url <url> another Passflow Cloud (default ${defaultCloudUrl})
|
|
1658
|
+
|
|
1659
|
+
Self-hosted Passflow:
|
|
1660
|
+
--server <url> your Passflow server
|
|
1661
|
+
--management-key <key> its management key. Prefer PASSFLOW_MANAGEMENT_KEY: a flag
|
|
1662
|
+
stays in your shell history and shows in ps.
|
|
1663
|
+
|
|
1664
|
+
The app:
|
|
1665
|
+
--dir <path> the app's root (default: the current directory)
|
|
1666
|
+
--base-url <url> the app's origin, with no path (default: the stack's dev URL)
|
|
1667
|
+
--api-url <url> React + Vite: the API's origin for VITE_API_URL (default ${defaultApiUrl})
|
|
1668
|
+
--issuer <url> Node API: the issuer of the app whose tokens the API accepts
|
|
1669
|
+
--audience <client ids> Node API: the client IDs of the apps whose tokens it accepts, comma-separated
|
|
1670
|
+
|
|
1671
|
+
Hand-off:
|
|
1672
|
+
--agent <name> start claude, codex or cursor-agent with the prompt
|
|
1673
|
+
--no-agent print the prompt (the default)
|
|
1674
|
+
|
|
1675
|
+
-h, --help this help
|
|
1676
|
+
-v, --version the CLI's version
|
|
1677
|
+
|
|
1678
|
+
Exit status: 0 done, 1 failed, 2 refused (the project or the options) before anything was created.
|
|
1679
|
+
`;
|
|
1680
|
+
async function main(argv) {
|
|
1681
|
+
const { values, positionals } = parseArgs({
|
|
1682
|
+
args: argv,
|
|
1683
|
+
allowPositionals: true,
|
|
1684
|
+
strict: true,
|
|
1685
|
+
options: {
|
|
1686
|
+
help: {
|
|
1687
|
+
type: "boolean",
|
|
1688
|
+
short: "h"
|
|
1689
|
+
},
|
|
1690
|
+
version: {
|
|
1691
|
+
type: "boolean",
|
|
1692
|
+
short: "v"
|
|
1693
|
+
},
|
|
1694
|
+
dir: { type: "string" },
|
|
1695
|
+
server: { type: "string" },
|
|
1696
|
+
"management-key": { type: "string" },
|
|
1697
|
+
"cloud-url": { type: "string" },
|
|
1698
|
+
org: { type: "string" },
|
|
1699
|
+
project: { type: "string" },
|
|
1700
|
+
env: { type: "string" },
|
|
1701
|
+
"base-url": { type: "string" },
|
|
1702
|
+
"api-url": { type: "string" },
|
|
1703
|
+
issuer: { type: "string" },
|
|
1704
|
+
audience: { type: "string" },
|
|
1705
|
+
agent: { type: "string" },
|
|
1706
|
+
"no-agent": { type: "boolean" }
|
|
1707
|
+
}
|
|
1708
|
+
});
|
|
1709
|
+
if (values.version) {
|
|
1710
|
+
process.stdout.write(`${version}\n`);
|
|
1711
|
+
return 0;
|
|
1712
|
+
}
|
|
1713
|
+
if (values.help) {
|
|
1714
|
+
process.stdout.write(usage);
|
|
1715
|
+
return 0;
|
|
1716
|
+
}
|
|
1717
|
+
if (positionals.length !== 1 || positionals[0] !== "integrate") throw new Refusal(`unknown command.\n\n${usage}`);
|
|
1718
|
+
if (values.agent !== void 0 && values["no-agent"]) throw new Refusal("--agent and --no-agent cannot be used together.");
|
|
1719
|
+
if (values.agent !== void 0 && !agents.includes(values.agent)) throw new Refusal(`--agent must be one of ${agents.join(", ")}.`);
|
|
1720
|
+
const managementKey = values["management-key"] ?? process.env.PASSFLOW_MANAGEMENT_KEY ?? "";
|
|
1721
|
+
const server = values.server === void 0 ? void 0 : checkUrl("--server", values.server);
|
|
1722
|
+
if (server && managementKey === "") throw new Refusal("--server needs --management-key (or PASSFLOW_MANAGEMENT_KEY).");
|
|
1723
|
+
if (!server && values["management-key"] !== void 0) throw new Refusal("--management-key needs --server.");
|
|
1724
|
+
if (server && (values.org || values.project || values.env || values["cloud-url"])) throw new Refusal("--org, --project, --env and --cloud-url are for Passflow Cloud; drop them with --server.");
|
|
1725
|
+
return integrate({
|
|
1726
|
+
dir: values.dir ?? process.cwd(),
|
|
1727
|
+
...server ? {
|
|
1728
|
+
server,
|
|
1729
|
+
managementKey
|
|
1730
|
+
} : {},
|
|
1731
|
+
cloudUrl: checkUrl("--cloud-url", values["cloud-url"] ?? defaultCloudUrl),
|
|
1732
|
+
...values.org ? { org: values.org } : {},
|
|
1733
|
+
...values.project ? { project: values.project } : {},
|
|
1734
|
+
...values.env ? { env: values.env } : {},
|
|
1735
|
+
...values["base-url"] ? { baseUrl: values["base-url"] } : {},
|
|
1736
|
+
apiUrl: values["api-url"] ?? defaultApiUrl,
|
|
1737
|
+
...values.issuer ? { issuer: values.issuer } : {},
|
|
1738
|
+
...values.audience ? { audience: values.audience } : {},
|
|
1739
|
+
...values.agent ? { agent: values.agent } : {}
|
|
1740
|
+
});
|
|
1741
|
+
}
|
|
1742
|
+
main(process.argv.slice(2)).then((code) => {
|
|
1743
|
+
process.exitCode = code;
|
|
1744
|
+
}, (error) => {
|
|
1745
|
+
if (error instanceof Refusal) {
|
|
1746
|
+
process.stderr.write(`passflow: refused: ${error.message}\n`);
|
|
1747
|
+
process.exitCode = 2;
|
|
1748
|
+
} else if (error instanceof Failure) {
|
|
1749
|
+
process.stderr.write(`passflow: ${error.message}\n`);
|
|
1750
|
+
process.exitCode = 1;
|
|
1751
|
+
} else if (error instanceof TypeError && error.code?.startsWith("ERR_PARSE_ARGS")) {
|
|
1752
|
+
process.stderr.write(`passflow: ${error.message}\n\n${usage}`);
|
|
1753
|
+
process.exitCode = 2;
|
|
1754
|
+
} else {
|
|
1755
|
+
process.stderr.write(`passflow: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
1756
|
+
process.exitCode = 1;
|
|
1757
|
+
}
|
|
1758
|
+
});
|
|
1759
|
+
export {};
|