@ratio-app/cli 0.1.1
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/README.md +504 -0
- package/bin/run.mjs +5 -0
- package/dist/commands/__test__/throw.d.ts +25 -0
- package/dist/commands/__test__/throw.js +238 -0
- package/dist/commands/__test__/throw.js.map +1 -0
- package/dist/commands/app/create.d.ts +55 -0
- package/dist/commands/app/create.js +609 -0
- package/dist/commands/app/create.js.map +1 -0
- package/dist/commands/app/deploy.d.ts +14 -0
- package/dist/commands/app/deploy.js +179 -0
- package/dist/commands/app/deploy.js.map +1 -0
- package/dist/commands/app/dev.d.ts +28 -0
- package/dist/commands/app/dev.js +701 -0
- package/dist/commands/app/dev.js.map +1 -0
- package/dist/commands/app/generate.d.ts +14 -0
- package/dist/commands/app/generate.js +179 -0
- package/dist/commands/app/generate.js.map +1 -0
- package/dist/commands/app/info.d.ts +14 -0
- package/dist/commands/app/info.js +179 -0
- package/dist/commands/app/info.js.map +1 -0
- package/dist/commands/app/link.d.ts +118 -0
- package/dist/commands/app/link.js +1120 -0
- package/dist/commands/app/link.js.map +1 -0
- package/dist/commands/auth/login.d.ts +43 -0
- package/dist/commands/auth/login.js +987 -0
- package/dist/commands/auth/login.js.map +1 -0
- package/dist/commands/auth/logout.d.ts +15 -0
- package/dist/commands/auth/logout.js +486 -0
- package/dist/commands/auth/logout.js.map +1 -0
- package/dist/commands/auth/whoami.d.ts +16 -0
- package/dist/commands/auth/whoami.js +531 -0
- package/dist/commands/auth/whoami.js.map +1 -0
- package/dist/commands/dev/listen.d.ts +84 -0
- package/dist/commands/dev/listen.js +1187 -0
- package/dist/commands/dev/listen.js.map +1 -0
- package/dist/commands/dev/trigger.d.ts +88 -0
- package/dist/commands/dev/trigger.js +729 -0
- package/dist/commands/dev/trigger.js.map +1 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +617 -0
- package/dist/index.js.map +1 -0
- package/dist/lib/auth/authorize-code-exchange.d.ts +50 -0
- package/dist/lib/auth/authorize-code-exchange.js +114 -0
- package/dist/lib/auth/authorize-code-exchange.js.map +1 -0
- package/dist/lib/auth/authorize-url.d.ts +42 -0
- package/dist/lib/auth/authorize-url.js +35 -0
- package/dist/lib/auth/authorize-url.js.map +1 -0
- package/dist/lib/auth/browser.d.ts +16 -0
- package/dist/lib/auth/browser.js +48 -0
- package/dist/lib/auth/browser.js.map +1 -0
- package/dist/lib/auth/config.d.ts +41 -0
- package/dist/lib/auth/config.js +21 -0
- package/dist/lib/auth/config.js.map +1 -0
- package/dist/lib/auth/http-refresher.d.ts +30 -0
- package/dist/lib/auth/http-refresher.js +103 -0
- package/dist/lib/auth/http-refresher.js.map +1 -0
- package/dist/lib/auth/identity.d.ts +26 -0
- package/dist/lib/auth/identity.js +10 -0
- package/dist/lib/auth/identity.js.map +1 -0
- package/dist/lib/auth/index.d.ts +13 -0
- package/dist/lib/auth/index.js +527 -0
- package/dist/lib/auth/index.js.map +1 -0
- package/dist/lib/auth/loopback-server.d.ts +65 -0
- package/dist/lib/auth/loopback-server.js +245 -0
- package/dist/lib/auth/loopback-server.js.map +1 -0
- package/dist/lib/auth/manual-prompt.d.ts +17 -0
- package/dist/lib/auth/manual-prompt.js +20 -0
- package/dist/lib/auth/manual-prompt.js.map +1 -0
- package/dist/lib/auth/pkce.d.ts +24 -0
- package/dist/lib/auth/pkce.js +15 -0
- package/dist/lib/auth/pkce.js.map +1 -0
- package/dist/lib/auth/state.d.ts +20 -0
- package/dist/lib/auth/state.js +19 -0
- package/dist/lib/auth/state.js.map +1 -0
- package/dist/lib/auth/verbose-trace.d.ts +25 -0
- package/dist/lib/auth/verbose-trace.js +17 -0
- package/dist/lib/auth/verbose-trace.js.map +1 -0
- package/dist/lib/credentials/clock.d.ts +18 -0
- package/dist/lib/credentials/clock.js +10 -0
- package/dist/lib/credentials/clock.js.map +1 -0
- package/dist/lib/credentials/index.d.ts +5 -0
- package/dist/lib/credentials/index.js +340 -0
- package/dist/lib/credentials/index.js.map +1 -0
- package/dist/lib/credentials/path.d.ts +26 -0
- package/dist/lib/credentials/path.js +32 -0
- package/dist/lib/credentials/path.js.map +1 -0
- package/dist/lib/credentials/refresher.d.ts +26 -0
- package/dist/lib/credentials/refresher.js +34 -0
- package/dist/lib/credentials/refresher.js.map +1 -0
- package/dist/lib/credentials/schema.d.ts +138 -0
- package/dist/lib/credentials/schema.js +85 -0
- package/dist/lib/credentials/schema.js.map +1 -0
- package/dist/lib/credentials/store.d.ts +102 -0
- package/dist/lib/credentials/store.js +337 -0
- package/dist/lib/credentials/store.js.map +1 -0
- package/dist/lib/credentials/types.d.ts +65 -0
- package/dist/lib/credentials/types.js +1 -0
- package/dist/lib/credentials/types.js.map +1 -0
- package/dist/lib/dev-store-gate.d.ts +66 -0
- package/dist/lib/dev-store-gate.js +15 -0
- package/dist/lib/dev-store-gate.js.map +1 -0
- package/dist/lib/errors.d.ts +60 -0
- package/dist/lib/errors.js +101 -0
- package/dist/lib/errors.js.map +1 -0
- package/dist/lib/manifest/index.d.ts +2 -0
- package/dist/lib/manifest/index.js +144 -0
- package/dist/lib/manifest/index.js.map +1 -0
- package/dist/lib/manifest/read-manifest.d.ts +32 -0
- package/dist/lib/manifest/read-manifest.js +87 -0
- package/dist/lib/manifest/read-manifest.js.map +1 -0
- package/dist/lib/manifest/write-client-id.d.ts +33 -0
- package/dist/lib/manifest/write-client-id.js +94 -0
- package/dist/lib/manifest/write-client-id.js.map +1 -0
- package/dist/lib/messages.d.ts +15 -0
- package/dist/lib/messages.js +16 -0
- package/dist/lib/messages.js.map +1 -0
- package/dist/lib/orchestrator/child-runner.d.ts +140 -0
- package/dist/lib/orchestrator/child-runner.js +471 -0
- package/dist/lib/orchestrator/child-runner.js.map +1 -0
- package/dist/lib/preview/index.d.ts +11 -0
- package/dist/lib/preview/index.js +17 -0
- package/dist/lib/preview/index.js.map +1 -0
- package/dist/lib/preview/types.d.ts +16 -0
- package/dist/lib/preview/types.js +11 -0
- package/dist/lib/preview/types.js.map +1 -0
- package/dist/lib/ratio-command.d.ts +52 -0
- package/dist/lib/ratio-command.js +141 -0
- package/dist/lib/ratio-command.js.map +1 -0
- package/dist/lib/relay/index.d.ts +7 -0
- package/dist/lib/relay/index.js +362 -0
- package/dist/lib/relay/index.js.map +1 -0
- package/dist/lib/relay/relay-client.d.ts +91 -0
- package/dist/lib/relay/relay-client.js +362 -0
- package/dist/lib/relay/relay-client.js.map +1 -0
- package/dist/lib/relay/types.d.ts +71 -0
- package/dist/lib/relay/types.js +1 -0
- package/dist/lib/relay/types.js.map +1 -0
- package/dist/lib/render-error.d.ts +35 -0
- package/dist/lib/render-error.js +115 -0
- package/dist/lib/render-error.js.map +1 -0
- package/dist/lib/verbose-flag.d.ts +12 -0
- package/dist/lib/verbose-flag.js +17 -0
- package/dist/lib/verbose-flag.js.map +1 -0
- package/dist/render-CrHGqTPH.d.ts +115 -0
- package/dist/templates/.gitkeep +0 -0
- package/dist/templates/minimal/.env.example.tmpl +4 -0
- package/dist/templates/minimal/README.md.tmpl +26 -0
- package/dist/templates/minimal/gitignore +5 -0
- package/dist/templates/minimal/manifest.json +5 -0
- package/dist/templates/minimal/package.json.tmpl +25 -0
- package/dist/templates/minimal/ratio.config.jsonc.tmpl +17 -0
- package/dist/templates/minimal/src/index.ts.tmpl +26 -0
- package/dist/templates/minimal/src/install.ts.tmpl +37 -0
- package/dist/templates/minimal/src/webhooks.ts.tmpl +57 -0
- package/dist/templates/minimal/tsconfig.json +17 -0
- package/dist/templates/serverless/README.md.tmpl +28 -0
- package/dist/templates/serverless/gitignore +6 -0
- package/dist/templates/serverless/manifest.json +5 -0
- package/dist/templates/serverless/package.json.tmpl +22 -0
- package/dist/templates/serverless/ratio.config.jsonc.tmpl +17 -0
- package/dist/templates/serverless/src/index.ts.tmpl +20 -0
- package/dist/templates/serverless/src/install.ts.tmpl +20 -0
- package/dist/templates/serverless/src/webhooks.ts.tmpl +36 -0
- package/dist/templates/serverless/tsconfig.json +18 -0
- package/dist/templates/serverless/wrangler.toml.tmpl +9 -0
- package/dist/templates/with-admin-ui/.env.example.tmpl +4 -0
- package/dist/templates/with-admin-ui/README.md.tmpl +28 -0
- package/dist/templates/with-admin-ui/gitignore +6 -0
- package/dist/templates/with-admin-ui/manifest.json +5 -0
- package/dist/templates/with-admin-ui/package.json.tmpl +31 -0
- package/dist/templates/with-admin-ui/ratio.config.jsonc.tmpl +17 -0
- package/dist/templates/with-admin-ui/src/admin/app/globals.css +19 -0
- package/dist/templates/with-admin-ui/src/admin/app/layout.tsx.tmpl +13 -0
- package/dist/templates/with-admin-ui/src/admin/app/page.tsx.tmpl +8 -0
- package/dist/templates/with-admin-ui/src/admin/next-env.d.ts.tmpl +5 -0
- package/dist/templates/with-admin-ui/src/admin/next.config.mjs +3 -0
- package/dist/templates/with-admin-ui/src/admin/tsconfig.json +20 -0
- package/dist/templates/with-admin-ui/src/index.ts.tmpl +26 -0
- package/dist/templates/with-admin-ui/src/install.ts.tmpl +37 -0
- package/dist/templates/with-admin-ui/src/webhooks.ts.tmpl +57 -0
- package/dist/templates/with-admin-ui/tsconfig.json +17 -0
- package/package.json +78 -0
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
// src/lib/credentials/clock.ts
|
|
2
|
+
var SystemClock = class {
|
|
3
|
+
now() {
|
|
4
|
+
return Date.now();
|
|
5
|
+
}
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
// src/lib/credentials/path.ts
|
|
9
|
+
import os from "os";
|
|
10
|
+
import path from "path";
|
|
11
|
+
function snapshotPathEnv() {
|
|
12
|
+
const snapshot = {};
|
|
13
|
+
const xdgConfigHome = process.env["XDG_CONFIG_HOME"];
|
|
14
|
+
if (xdgConfigHome !== void 0) {
|
|
15
|
+
snapshot.XDG_CONFIG_HOME = xdgConfigHome;
|
|
16
|
+
}
|
|
17
|
+
const appData = process.env["APPDATA"];
|
|
18
|
+
if (appData !== void 0) {
|
|
19
|
+
snapshot.APPDATA = appData;
|
|
20
|
+
}
|
|
21
|
+
return snapshot;
|
|
22
|
+
}
|
|
23
|
+
function defaultCredentialsPath(platform, homedir, env) {
|
|
24
|
+
const resolvedPlatform = platform ?? process.platform;
|
|
25
|
+
const resolvedHome = homedir ?? os.homedir();
|
|
26
|
+
const resolvedEnv = env ?? snapshotPathEnv();
|
|
27
|
+
if (resolvedPlatform === "win32") {
|
|
28
|
+
const appData = resolvedEnv.APPDATA;
|
|
29
|
+
const base2 = appData !== void 0 && appData !== "" ? appData : path.win32.join(resolvedHome, "AppData", "Roaming");
|
|
30
|
+
return path.win32.join(base2, "ratio", "credentials");
|
|
31
|
+
}
|
|
32
|
+
const xdgConfigHome = resolvedEnv.XDG_CONFIG_HOME;
|
|
33
|
+
const base = typeof xdgConfigHome === "string" && xdgConfigHome !== "" ? xdgConfigHome : path.posix.join(resolvedHome, ".config");
|
|
34
|
+
return path.posix.join(base, "ratio", "credentials");
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// src/lib/errors.ts
|
|
38
|
+
var RatioCLIError = class extends Error {
|
|
39
|
+
code;
|
|
40
|
+
exitCode;
|
|
41
|
+
hint;
|
|
42
|
+
docsUrl;
|
|
43
|
+
constructor(opts) {
|
|
44
|
+
super(opts.message);
|
|
45
|
+
this.name = new.target.name;
|
|
46
|
+
this.code = opts.code;
|
|
47
|
+
this.exitCode = opts.exitCode;
|
|
48
|
+
if (opts.hint !== void 0) this.hint = opts.hint;
|
|
49
|
+
if (opts.docsUrl !== void 0) this.docsUrl = opts.docsUrl;
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
var NotLoggedInError = class extends RatioCLIError {
|
|
53
|
+
constructor(message, hint = "Run 'ratio auth login' to sign in.") {
|
|
54
|
+
super({ code: "NOT_LOGGED_IN", exitCode: 3, message, hint });
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
var TokenExpiredError = class extends RatioCLIError {
|
|
58
|
+
constructor(message, hint = "Run 'ratio auth login' to refresh your session.") {
|
|
59
|
+
super({ code: "TOKEN_EXPIRED", exitCode: 3, message, hint });
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
var ValidationError = class extends RatioCLIError {
|
|
63
|
+
constructor(message, hint) {
|
|
64
|
+
const opts = {
|
|
65
|
+
code: "VALIDATION_ERROR",
|
|
66
|
+
exitCode: 8,
|
|
67
|
+
message
|
|
68
|
+
};
|
|
69
|
+
if (hint !== void 0) opts.hint = hint;
|
|
70
|
+
super(opts);
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
// src/lib/credentials/refresher.ts
|
|
75
|
+
var NotImplementedRefresher = class {
|
|
76
|
+
async refresh(refreshToken) {
|
|
77
|
+
void refreshToken;
|
|
78
|
+
throw new NotLoggedInError(
|
|
79
|
+
"Token refresh is not available yet in this CLI version."
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
// src/lib/credentials/store.ts
|
|
85
|
+
import crypto from "crypto";
|
|
86
|
+
import fs from "fs";
|
|
87
|
+
import { dirname } from "path";
|
|
88
|
+
|
|
89
|
+
// src/lib/credentials/schema.ts
|
|
90
|
+
import { z } from "zod";
|
|
91
|
+
var identitySchema = z.object({
|
|
92
|
+
developerId: z.string(),
|
|
93
|
+
email: z.string(),
|
|
94
|
+
// Token-derived fields captured at login. Optional (additive) so files
|
|
95
|
+
// written before these fields existed still validate as version 1.
|
|
96
|
+
merchantId: z.string().optional(),
|
|
97
|
+
scopes: z.array(z.string()).optional()
|
|
98
|
+
}).strict();
|
|
99
|
+
var profileSchema = z.object({
|
|
100
|
+
accessToken: z.string(),
|
|
101
|
+
refreshToken: z.string(),
|
|
102
|
+
expiresAt: z.string().datetime({ offset: true }),
|
|
103
|
+
identity: identitySchema,
|
|
104
|
+
obtainedAt: z.string().datetime({ offset: true })
|
|
105
|
+
}).strict();
|
|
106
|
+
var developerSessionSchema = z.object({
|
|
107
|
+
jwt: z.string(),
|
|
108
|
+
developerId: z.string(),
|
|
109
|
+
email: z.string(),
|
|
110
|
+
expiresAt: z.string().datetime({ offset: true }),
|
|
111
|
+
obtainedAt: z.string().datetime({ offset: true })
|
|
112
|
+
}).strict();
|
|
113
|
+
var credentialsSchema = z.object({
|
|
114
|
+
version: z.literal(1),
|
|
115
|
+
server: z.string(),
|
|
116
|
+
clientId: z.string(),
|
|
117
|
+
profiles: z.record(z.string(), profileSchema),
|
|
118
|
+
// Optional cached developer session. Additive so files written before
|
|
119
|
+
// this field existed still validate as version 1.
|
|
120
|
+
developer: developerSessionSchema.optional()
|
|
121
|
+
}).strict();
|
|
122
|
+
function parseCredentials(input) {
|
|
123
|
+
if (typeof input === "object" && input !== null && "version" in input) {
|
|
124
|
+
const version = input.version;
|
|
125
|
+
if (version !== 1) {
|
|
126
|
+
const label = typeof version === "number" ? String(version) : "unknown";
|
|
127
|
+
throw new ValidationError(
|
|
128
|
+
`credentials file version ${label} is unsupported by this CLI \u2014 upgrade the CLI or sign in again`
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
const result = credentialsSchema.safeParse(input);
|
|
133
|
+
if (!result.success) {
|
|
134
|
+
throw new ValidationError(
|
|
135
|
+
"credentials file schema mismatch \u2014 expected v1 shape"
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
return result.data;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// src/lib/credentials/store.ts
|
|
142
|
+
var REFRESH_WINDOW_MS = 3e5;
|
|
143
|
+
var ENV_TOKEN_VAR = "RATIO_API_TOKEN";
|
|
144
|
+
var ENV_DEVELOPER_TOKEN_VAR = "RATIO_DEVELOPER_TOKEN";
|
|
145
|
+
function hasErrnoCode(err, code) {
|
|
146
|
+
return err instanceof Error && err.code === code;
|
|
147
|
+
}
|
|
148
|
+
var FileCredentialStore = class {
|
|
149
|
+
filePath;
|
|
150
|
+
clock;
|
|
151
|
+
refresher;
|
|
152
|
+
envReader;
|
|
153
|
+
platform;
|
|
154
|
+
constructor(opts) {
|
|
155
|
+
this.filePath = opts?.filePath ?? defaultCredentialsPath();
|
|
156
|
+
this.clock = opts?.clock ?? new SystemClock();
|
|
157
|
+
this.refresher = opts?.refresher ?? new NotImplementedRefresher();
|
|
158
|
+
this.envReader = opts?.envReader ?? (() => process.env);
|
|
159
|
+
this.platform = opts?.platform ?? process.platform;
|
|
160
|
+
}
|
|
161
|
+
async load() {
|
|
162
|
+
this.reapplyFileModeIfDrifted();
|
|
163
|
+
let raw;
|
|
164
|
+
try {
|
|
165
|
+
raw = fs.readFileSync(this.filePath, "utf8");
|
|
166
|
+
} catch (err) {
|
|
167
|
+
if (hasErrnoCode(err, "ENOENT")) {
|
|
168
|
+
throw new NotLoggedInError("You are not signed in.");
|
|
169
|
+
}
|
|
170
|
+
throw err;
|
|
171
|
+
}
|
|
172
|
+
let parsed;
|
|
173
|
+
try {
|
|
174
|
+
parsed = JSON.parse(raw);
|
|
175
|
+
} catch {
|
|
176
|
+
throw new ValidationError(
|
|
177
|
+
'credentials file is not valid JSON \u2014 run "ratio auth login" to reset'
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
return parseCredentials(parsed);
|
|
181
|
+
}
|
|
182
|
+
async save(creds) {
|
|
183
|
+
const dir = dirname(this.filePath);
|
|
184
|
+
fs.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
185
|
+
if (this.platform !== "win32") {
|
|
186
|
+
fs.chmodSync(dir, 448);
|
|
187
|
+
}
|
|
188
|
+
const tmpPath = `${this.filePath}.${process.pid}.${crypto.randomBytes(8).toString("hex")}.tmp`;
|
|
189
|
+
try {
|
|
190
|
+
fs.writeFileSync(tmpPath, JSON.stringify(creds, null, 2), {
|
|
191
|
+
mode: 384
|
|
192
|
+
});
|
|
193
|
+
fs.renameSync(tmpPath, this.filePath);
|
|
194
|
+
} catch (err) {
|
|
195
|
+
try {
|
|
196
|
+
fs.unlinkSync(tmpPath);
|
|
197
|
+
} catch {
|
|
198
|
+
}
|
|
199
|
+
throw err;
|
|
200
|
+
}
|
|
201
|
+
if (this.platform !== "win32") {
|
|
202
|
+
fs.chmodSync(this.filePath, 384);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
async clear() {
|
|
206
|
+
try {
|
|
207
|
+
fs.unlinkSync(this.filePath);
|
|
208
|
+
} catch (err) {
|
|
209
|
+
if (hasErrnoCode(err, "ENOENT")) {
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
throw err;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
async getValidAccessToken(profileName) {
|
|
216
|
+
const envToken = this.envReader()[ENV_TOKEN_VAR];
|
|
217
|
+
if (typeof envToken === "string" && envToken.length > 0) {
|
|
218
|
+
return envToken;
|
|
219
|
+
}
|
|
220
|
+
const creds = await this.load();
|
|
221
|
+
const name = profileName ?? "default";
|
|
222
|
+
const profile = creds.profiles[name];
|
|
223
|
+
if (profile === void 0) {
|
|
224
|
+
throw new NotLoggedInError("You are not signed in.");
|
|
225
|
+
}
|
|
226
|
+
const msUntilExpiry = new Date(profile.expiresAt).getTime() - this.clock.now();
|
|
227
|
+
if (msUntilExpiry < REFRESH_WINDOW_MS) {
|
|
228
|
+
return this.refreshAndPersist(creds, name, profile);
|
|
229
|
+
}
|
|
230
|
+
return profile.accessToken;
|
|
231
|
+
}
|
|
232
|
+
async getValidDeveloperToken() {
|
|
233
|
+
const envToken = this.envReader()[ENV_DEVELOPER_TOKEN_VAR];
|
|
234
|
+
if (typeof envToken === "string" && envToken.length > 0) {
|
|
235
|
+
return envToken;
|
|
236
|
+
}
|
|
237
|
+
let creds;
|
|
238
|
+
try {
|
|
239
|
+
creds = await this.load();
|
|
240
|
+
} catch (err) {
|
|
241
|
+
if (err instanceof NotLoggedInError) {
|
|
242
|
+
throw new NotLoggedInError("Developer signin required.");
|
|
243
|
+
}
|
|
244
|
+
throw err;
|
|
245
|
+
}
|
|
246
|
+
const session = creds.developer;
|
|
247
|
+
if (session === void 0) {
|
|
248
|
+
throw new NotLoggedInError("Developer signin required.");
|
|
249
|
+
}
|
|
250
|
+
const msUntilExpiry = new Date(session.expiresAt).getTime() - this.clock.now();
|
|
251
|
+
if (msUntilExpiry < REFRESH_WINDOW_MS) {
|
|
252
|
+
throw new NotLoggedInError("Developer signin required.");
|
|
253
|
+
}
|
|
254
|
+
return session.jwt;
|
|
255
|
+
}
|
|
256
|
+
async saveDeveloperSession(session) {
|
|
257
|
+
let creds;
|
|
258
|
+
try {
|
|
259
|
+
creds = await this.load();
|
|
260
|
+
} catch (err) {
|
|
261
|
+
if (err instanceof NotLoggedInError) {
|
|
262
|
+
creds = { version: 1, server: "", clientId: "", profiles: {} };
|
|
263
|
+
} else {
|
|
264
|
+
throw err;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
const updated = {
|
|
268
|
+
...creds,
|
|
269
|
+
developer: session
|
|
270
|
+
};
|
|
271
|
+
await this.save(updated);
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Exchange the profile's refresh token for a fresh token set, merge it
|
|
275
|
+
* into the loaded credentials (preserving every other profile), persist
|
|
276
|
+
* atomically, and return the new access token. A refresher failure is
|
|
277
|
+
* wrapped in TokenExpiredError; the underlying message is deliberately
|
|
278
|
+
* discarded so a secret can never leak through the error surface.
|
|
279
|
+
*/
|
|
280
|
+
async refreshAndPersist(creds, name, profile) {
|
|
281
|
+
let refreshed;
|
|
282
|
+
try {
|
|
283
|
+
refreshed = await this.refresher.refresh(profile.refreshToken);
|
|
284
|
+
} catch {
|
|
285
|
+
throw new TokenExpiredError(
|
|
286
|
+
"Your session has expired and could not be refreshed."
|
|
287
|
+
);
|
|
288
|
+
}
|
|
289
|
+
const updated = {
|
|
290
|
+
...creds,
|
|
291
|
+
profiles: {
|
|
292
|
+
...creds.profiles,
|
|
293
|
+
[name]: {
|
|
294
|
+
...profile,
|
|
295
|
+
accessToken: refreshed.accessToken,
|
|
296
|
+
refreshToken: refreshed.refreshToken,
|
|
297
|
+
expiresAt: refreshed.expiresAt
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
};
|
|
301
|
+
await this.save(updated);
|
|
302
|
+
return refreshed.accessToken;
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* POSIX-only startup permission check: if the file exists with a mode
|
|
306
|
+
* other than 0600, re-apply 0600 and emit a warning to stderr. Never
|
|
307
|
+
* runs on Windows (stat modes there do not map to POSIX bits and chmod
|
|
308
|
+
* must not be called). Missing file is NOT an error here — load()
|
|
309
|
+
* reports it as NotLoggedInError.
|
|
310
|
+
*/
|
|
311
|
+
reapplyFileModeIfDrifted() {
|
|
312
|
+
if (this.platform === "win32") {
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
315
|
+
let stat;
|
|
316
|
+
try {
|
|
317
|
+
stat = fs.statSync(this.filePath);
|
|
318
|
+
} catch (err) {
|
|
319
|
+
if (hasErrnoCode(err, "ENOENT")) {
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
throw err;
|
|
323
|
+
}
|
|
324
|
+
const mode = stat.mode & 511;
|
|
325
|
+
if (mode !== 384) {
|
|
326
|
+
fs.chmodSync(this.filePath, 384);
|
|
327
|
+
process.stderr.write(
|
|
328
|
+
`[warn] credentials file permissions were 0o${mode.toString(8)}; corrected to 0600.
|
|
329
|
+
`
|
|
330
|
+
);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
};
|
|
334
|
+
export {
|
|
335
|
+
FileCredentialStore,
|
|
336
|
+
NotImplementedRefresher,
|
|
337
|
+
SystemClock,
|
|
338
|
+
defaultCredentialsPath
|
|
339
|
+
};
|
|
340
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/lib/credentials/clock.ts","../../../src/lib/credentials/path.ts","../../../src/lib/errors.ts","../../../src/lib/credentials/refresher.ts","../../../src/lib/credentials/store.ts","../../../src/lib/credentials/schema.ts"],"sourcesContent":["/**\n * Injectable wall-clock seam for the credential store.\n *\n * This is the ONLY file in the credentials module allowed to sample the\n * real wall clock. Every other file receives a {@link Clock} instance so\n * tests can drive expiry-window logic deterministically with a fake.\n */\n\n/** Injectable time source. */\nexport interface Clock {\n /** Milliseconds since Unix epoch. */\n now(): number;\n}\n\n/** Production {@link Clock} backed by the system wall clock. */\nexport class SystemClock implements Clock {\n now(): number {\n return Date.now();\n }\n}\n","/**\n * Pure path resolution for the credentials file.\n *\n * POSIX: `$XDG_CONFIG_HOME/ratio/credentials` when the override is a\n * non-empty string, otherwise `~/.config/ratio/credentials`.\n * Windows: `%APPDATA%\\ratio\\credentials`, falling back to\n * `<home>\\AppData\\Roaming\\ratio\\credentials` when APPDATA is unset.\n *\n * `path.win32.join` / `path.posix.join` are used explicitly (never bare\n * `path.join`) so the result is deterministic when a test running on a\n * POSIX host fakes `platform === 'win32'`.\n */\n\nimport os from 'node:os';\nimport path from 'node:path';\n\n/** The subset of environment variables the path algorithm consults. */\nexport interface PathEnv {\n readonly XDG_CONFIG_HOME?: string;\n readonly APPDATA?: string;\n}\n\n/** Snapshot the two relevant variables from the real process env. */\nfunction snapshotPathEnv(): PathEnv {\n const snapshot: { XDG_CONFIG_HOME?: string; APPDATA?: string } = {};\n const xdgConfigHome = process.env['XDG_CONFIG_HOME'];\n if (xdgConfigHome !== undefined) {\n snapshot.XDG_CONFIG_HOME = xdgConfigHome;\n }\n const appData = process.env['APPDATA'];\n if (appData !== undefined) {\n snapshot.APPDATA = appData;\n }\n return snapshot;\n}\n\n/**\n * Pure function. Returns the on-disk path for the credentials file.\n * platform defaults to process.platform, homedir defaults to os.homedir(),\n * env defaults to a snapshot of {XDG_CONFIG_HOME, APPDATA} from process.env.\n * All three are injectable so unit tests fake Windows without a Windows host.\n */\nexport function defaultCredentialsPath(\n platform?: NodeJS.Platform,\n homedir?: string,\n env?: PathEnv,\n): string {\n const resolvedPlatform = platform ?? process.platform;\n const resolvedHome = homedir ?? os.homedir();\n const resolvedEnv = env ?? snapshotPathEnv();\n\n if (resolvedPlatform === 'win32') {\n const appData = resolvedEnv.APPDATA;\n const base =\n appData !== undefined && appData !== ''\n ? appData\n : path.win32.join(resolvedHome, 'AppData', 'Roaming');\n return path.win32.join(base, 'ratio', 'credentials');\n }\n\n const xdgConfigHome = resolvedEnv.XDG_CONFIG_HOME;\n const base =\n typeof xdgConfigHome === 'string' && xdgConfigHome !== ''\n ? xdgConfigHome\n : path.posix.join(resolvedHome, '.config');\n return path.posix.join(base, 'ratio', 'credentials');\n}\n","/**\n * Error hierarchy for the Ratio CLI. Every error thrown from a command's\n * run() is expected to be an instance of RatioCLIError so the global\n * render-error handler can map it to a deterministic stderr line and exit\n * code. Uncaught Error subclasses render as \"INTERNAL: <msg>\" with exit 1.\n *\n * No import from @oclif/core — this file is dependency-free so tests\n * can import it without oclif overhead.\n */\n\nexport class RatioCLIError extends Error {\n readonly code: string;\n readonly exitCode: number;\n readonly hint?: string;\n readonly docsUrl?: string;\n\n constructor(opts: {\n code: string;\n exitCode: number;\n message: string;\n hint?: string;\n docsUrl?: string;\n }) {\n super(opts.message);\n this.name = new.target.name;\n this.code = opts.code;\n this.exitCode = opts.exitCode;\n if (opts.hint !== undefined) this.hint = opts.hint;\n if (opts.docsUrl !== undefined) this.docsUrl = opts.docsUrl;\n }\n}\n\n/** Coming-soon stub UX. Renders on stdout with exit 0. */\nexport class ComingSoonError extends RatioCLIError {\n constructor(message: string) {\n super({ code: 'COMING_SOON', exitCode: 0, message });\n }\n}\n\n/** User has no credentials and command requires auth. */\nexport class NotLoggedInError extends RatioCLIError {\n constructor(\n message: string,\n hint: string = \"Run 'ratio auth login' to sign in.\",\n ) {\n super({ code: 'NOT_LOGGED_IN', exitCode: 3, message, hint });\n }\n}\n\nexport class TokenExpiredError extends RatioCLIError {\n constructor(\n message: string,\n hint: string = \"Run 'ratio auth login' to refresh your session.\",\n ) {\n super({ code: 'TOKEN_EXPIRED', exitCode: 3, message, hint });\n }\n}\n\nexport class ScopeDeniedError extends RatioCLIError {\n constructor(message: string, hint?: string) {\n const opts: { code: string; exitCode: number; message: string; hint?: string } = {\n code: 'SCOPE_DENIED',\n exitCode: 4,\n message,\n };\n if (hint !== undefined) opts.hint = hint;\n super(opts);\n }\n}\n\nexport class NetworkError extends RatioCLIError {\n constructor(message: string, hint: string = 'Check your network and retry.') {\n super({ code: 'NETWORK_ERROR', exitCode: 5, message, hint });\n }\n}\n\nexport class RelayConnectError extends RatioCLIError {\n constructor(\n message: string,\n hint: string = 'Verify the tunnel URL and that the auth-server is reachable.',\n ) {\n super({ code: 'RELAY_CONNECT', exitCode: 6, message, hint });\n }\n}\n\nexport class TemplateExistsError extends RatioCLIError {\n constructor(\n message: string,\n hint: string = 'Choose a different name or remove the existing directory.',\n ) {\n super({ code: 'TEMPLATE_EXISTS', exitCode: 7, message, hint });\n }\n}\n\nexport class ValidationError extends RatioCLIError {\n constructor(message: string, hint?: string) {\n const opts: { code: string; exitCode: number; message: string; hint?: string } = {\n code: 'VALIDATION_ERROR',\n exitCode: 8,\n message,\n };\n if (hint !== undefined) opts.hint = hint;\n super(opts);\n }\n}\n\nexport class RelayResumeGapError extends RatioCLIError {\n constructor(\n message: string,\n hint: string = 'Reconnect from the current cursor; older events are outside the buffer window.',\n ) {\n super({ code: 'RELAY_RESUME_GAP', exitCode: 9, message, hint });\n }\n}\n\nexport class OrchestratorSpawnError extends RatioCLIError {\n constructor(\n message: string,\n hint: string = \"Could not start your app's dev command — check that the command in ratio.config.jsonc runs from this directory.\",\n ) {\n super({ code: 'ORCHESTRATOR_SPAWN', exitCode: 10, message, hint });\n }\n}\n\nexport class OrchestratorDrainTimeoutError extends RatioCLIError {\n constructor(\n message: string,\n hint: string = 'Your dev command did not exit cleanly within 5 seconds — it was forcibly terminated.',\n ) {\n super({ code: 'ORCHESTRATOR_DRAIN', exitCode: 11, message, hint });\n }\n}\n\nexport function isRatioCLIError(err: unknown): err is RatioCLIError {\n return err instanceof RatioCLIError;\n}\n","/**\n * Injectable token-refresh seam for the credential store.\n *\n * The store never performs network I/O itself: when a stored token is\n * close to expiry the store calls the injected {@link TokenRefresher}\n * and persists whatever it returns. The concrete HTTP implementation is\n * wired in by the auth commands; this module only defines the seam plus\n * a throw-if-called placeholder used before sign-in support is wired.\n */\n\nimport { NotLoggedInError } from '../errors.js';\nimport type { TokenSet } from './types.js';\n\n/** Injectable seam that exchanges a refresh token for a fresh token set. */\nexport interface TokenRefresher {\n refresh(refreshToken: string): Promise<TokenSet>;\n}\n\n/**\n * v1 stub. Always rejects with a static-message NotLoggedInError; it\n * never inspects, echoes, or logs the token it was handed. The real\n * HTTP implementation is supplied by the auth commands.\n */\nexport class NotImplementedRefresher implements TokenRefresher {\n async refresh(refreshToken: string): Promise<TokenSet> {\n // Deliberately unused: this placeholder must never touch the token.\n void refreshToken;\n throw new NotLoggedInError(\n 'Token refresh is not available yet in this CLI version.',\n );\n }\n}\n","/**\n * File-backed credential store.\n *\n * Token resolution precedence (highest first):\n * 1. `RATIO_API_TOKEN` from the injected env reader — returned as-is\n * with ZERO filesystem access and ZERO refresher involvement.\n * 2. The requested profile (default: \"default\") from the credentials\n * file, silently refreshed via the injected TokenRefresher when it\n * is within 5 minutes of expiry.\n *\n * Write contract: atomic tmp + rename in the SAME directory, tmp created\n * with mode 0600 at open time (POSIX), parent directory created 0700,\n * belt-and-braces chmod 0600 after rename. On Windows no chmod / mode\n * checks are ever performed. Concurrent writers are last-writer-wins by\n * design — the atomic rename guarantees no half-written file, which is\n * sufficient for a single-developer CLI.\n *\n * No secret (access token, refresh token, raw file contents) is ever\n * included in an error message or a log line.\n */\n\nimport crypto from 'node:crypto';\nimport fs from 'node:fs';\nimport { dirname } from 'node:path';\nimport {\n NotLoggedInError,\n TokenExpiredError,\n ValidationError,\n} from '../errors.js';\nimport { SystemClock } from './clock.js';\nimport type { Clock } from './clock.js';\nimport { defaultCredentialsPath } from './path.js';\nimport { NotImplementedRefresher } from './refresher.js';\nimport type { TokenRefresher } from './refresher.js';\nimport { parseCredentials } from './schema.js';\nimport type { Credentials, DeveloperSession, Profile, TokenSet } from './types.js';\n\n/** Milliseconds before expiry at which a silent refresh is triggered. */\nconst REFRESH_WINDOW_MS = 300_000;\n\n/** Env var that short-circuits all file access when set to a non-empty string. */\nconst ENV_TOKEN_VAR = 'RATIO_API_TOKEN';\n\n/**\n * Env var that short-circuits developer-session file access when set to a\n * non-empty string. Strictly separate from RATIO_API_TOKEN: this one carries\n * the developer sign-in bearer used for app-management calls, never the\n * OAuth access token.\n */\nconst ENV_DEVELOPER_TOKEN_VAR = 'RATIO_DEVELOPER_TOKEN';\n\nexport interface CredentialStoreOptions {\n /** Defaults to defaultCredentialsPath(). */\n readonly filePath?: string;\n /** Defaults to new SystemClock(). */\n readonly clock?: Clock;\n /** Defaults to new NotImplementedRefresher(). */\n readonly refresher?: TokenRefresher;\n /** Defaults to () => process.env — injected for env-precedence tests. */\n readonly envReader?: () => Readonly<Record<string, string | undefined>>;\n /** Defaults to process.platform. */\n readonly platform?: NodeJS.Platform;\n}\n\nexport interface CredentialStore {\n /** Reads the full credentials file. Throws NotLoggedInError if missing. */\n load(): Promise<Credentials>;\n /** Atomic write with 0600 on POSIX. tmp + rename in same dir. */\n save(creds: Credentials): Promise<void>;\n /** Deletes the credentials file. Idempotent. */\n clear(): Promise<void>;\n /**\n * Env precedence: if envReader().RATIO_API_TOKEN is set, returns it\n * WITHOUT reading the file, WITHOUT touching the refresher, WITHOUT\n * any fs I/O. This is the auditable \"no disk access\" path.\n *\n * Otherwise: reads the file, validates, computes\n * msUntilExpiry = new Date(profile.expiresAt).getTime() - clock.now()\n * If msUntilExpiry < 300_000 (5 min), calls refresher.refresh(...),\n * persists the new TokenSet atomically, returns the new accessToken.\n * Otherwise returns profile.accessToken.\n */\n getValidAccessToken(profileName?: string): Promise<string>;\n /**\n * Env precedence: RATIO_DEVELOPER_TOKEN if set (no fs I/O).\n * Otherwise: load(); if creds.developer is absent or within 5 minutes of\n * expiry, throws NotLoggedInError ('Developer signin required.').\n * Otherwise returns creds.developer.jwt.\n * NO refresh attempt — the caller drives the re-prompt UX.\n */\n getValidDeveloperToken(): Promise<string>;\n /**\n * Merge a DeveloperSession into the loaded credentials (creating the file\n * if absent), atomic tmp+rename, 0600.\n */\n saveDeveloperSession(session: DeveloperSession): Promise<void>;\n}\n\n/** Narrow an unknown thrown value to a Node errno error with the given code. */\nfunction hasErrnoCode(err: unknown, code: string): boolean {\n return (\n err instanceof Error &&\n (err as NodeJS.ErrnoException).code === code\n );\n}\n\nexport class FileCredentialStore implements CredentialStore {\n private readonly filePath: string;\n private readonly clock: Clock;\n private readonly refresher: TokenRefresher;\n private readonly envReader: () => Readonly<\n Record<string, string | undefined>\n >;\n private readonly platform: NodeJS.Platform;\n\n constructor(opts?: CredentialStoreOptions) {\n this.filePath = opts?.filePath ?? defaultCredentialsPath();\n this.clock = opts?.clock ?? new SystemClock();\n this.refresher = opts?.refresher ?? new NotImplementedRefresher();\n this.envReader = opts?.envReader ?? (() => process.env);\n this.platform = opts?.platform ?? process.platform;\n }\n\n async load(): Promise<Credentials> {\n this.reapplyFileModeIfDrifted();\n\n let raw: string;\n try {\n raw = fs.readFileSync(this.filePath, 'utf8');\n } catch (err) {\n if (hasErrnoCode(err, 'ENOENT')) {\n throw new NotLoggedInError('You are not signed in.');\n }\n throw err;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n // Never echo the raw contents — they may hold a truncated token.\n throw new ValidationError(\n 'credentials file is not valid JSON — run \"ratio auth login\" to reset',\n );\n }\n\n return parseCredentials(parsed);\n }\n\n async save(creds: Credentials): Promise<void> {\n const dir = dirname(this.filePath);\n fs.mkdirSync(dir, { recursive: true, mode: 0o700 });\n if (this.platform !== 'win32') {\n // mkdirSync does not re-mode a pre-existing directory; re-apply.\n fs.chmodSync(dir, 0o700);\n }\n\n const tmpPath = `${this.filePath}.${process.pid}.${crypto\n .randomBytes(8)\n .toString('hex')}.tmp`;\n try {\n // mode at open time closes the create-then-chmod race window.\n fs.writeFileSync(tmpPath, JSON.stringify(creds, null, 2), {\n mode: 0o600,\n });\n fs.renameSync(tmpPath, this.filePath);\n } catch (err) {\n try {\n fs.unlinkSync(tmpPath);\n } catch {\n // Best-effort cleanup: the tmp file may never have been created.\n }\n throw err;\n }\n\n if (this.platform !== 'win32') {\n // Belt-and-braces: rename may preserve a prior destination mode.\n fs.chmodSync(this.filePath, 0o600);\n }\n }\n\n async clear(): Promise<void> {\n try {\n fs.unlinkSync(this.filePath);\n } catch (err) {\n if (hasErrnoCode(err, 'ENOENT')) {\n return; // Idempotent: already gone.\n }\n throw err;\n }\n }\n\n async getValidAccessToken(profileName?: string): Promise<string> {\n const envToken = this.envReader()[ENV_TOKEN_VAR];\n if (typeof envToken === 'string' && envToken.length > 0) {\n return envToken;\n }\n\n const creds = await this.load();\n const name = profileName ?? 'default';\n const profile = creds.profiles[name];\n if (profile === undefined) {\n throw new NotLoggedInError('You are not signed in.');\n }\n\n const msUntilExpiry =\n new Date(profile.expiresAt).getTime() - this.clock.now();\n if (msUntilExpiry < REFRESH_WINDOW_MS) {\n return this.refreshAndPersist(creds, name, profile);\n }\n\n return profile.accessToken;\n }\n\n async getValidDeveloperToken(): Promise<string> {\n const envToken = this.envReader()[ENV_DEVELOPER_TOKEN_VAR];\n if (typeof envToken === 'string' && envToken.length > 0) {\n return envToken;\n }\n\n let creds: Credentials;\n try {\n creds = await this.load();\n } catch (err) {\n if (err instanceof NotLoggedInError) {\n throw new NotLoggedInError('Developer signin required.');\n }\n throw err;\n }\n\n const session = creds.developer;\n if (session === undefined) {\n throw new NotLoggedInError('Developer signin required.');\n }\n\n const msUntilExpiry =\n new Date(session.expiresAt).getTime() - this.clock.now();\n if (msUntilExpiry < REFRESH_WINDOW_MS) {\n // No refresh endpoint exists for developer sessions — the caller\n // drives a fresh interactive sign-in instead.\n throw new NotLoggedInError('Developer signin required.');\n }\n\n return session.jwt;\n }\n\n async saveDeveloperSession(session: DeveloperSession): Promise<void> {\n let creds: Credentials;\n try {\n creds = await this.load();\n } catch (err) {\n if (err instanceof NotLoggedInError) {\n // Edge case: no prior credentials file. Create a fresh v1 shell so\n // the merged write below still validates on the next load().\n creds = { version: 1, server: '', clientId: '', profiles: {} };\n } else {\n throw err;\n }\n }\n\n const updated: Credentials = {\n ...creds,\n developer: session,\n };\n await this.save(updated);\n }\n\n /**\n * Exchange the profile's refresh token for a fresh token set, merge it\n * into the loaded credentials (preserving every other profile), persist\n * atomically, and return the new access token. A refresher failure is\n * wrapped in TokenExpiredError; the underlying message is deliberately\n * discarded so a secret can never leak through the error surface.\n */\n private async refreshAndPersist(\n creds: Credentials,\n name: string,\n profile: Profile,\n ): Promise<string> {\n let refreshed: TokenSet;\n try {\n refreshed = await this.refresher.refresh(profile.refreshToken);\n } catch {\n throw new TokenExpiredError(\n 'Your session has expired and could not be refreshed.',\n );\n }\n\n const updated: Credentials = {\n ...creds,\n profiles: {\n ...creds.profiles,\n [name]: {\n ...profile,\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n expiresAt: refreshed.expiresAt,\n },\n },\n };\n await this.save(updated);\n return refreshed.accessToken;\n }\n\n /**\n * POSIX-only startup permission check: if the file exists with a mode\n * other than 0600, re-apply 0600 and emit a warning to stderr. Never\n * runs on Windows (stat modes there do not map to POSIX bits and chmod\n * must not be called). Missing file is NOT an error here — load()\n * reports it as NotLoggedInError.\n */\n private reapplyFileModeIfDrifted(): void {\n if (this.platform === 'win32') {\n return;\n }\n\n let stat: fs.Stats;\n try {\n stat = fs.statSync(this.filePath);\n } catch (err) {\n if (hasErrnoCode(err, 'ENOENT')) {\n return; // load() turns the missing file into NotLoggedInError.\n }\n throw err;\n }\n\n const mode = stat.mode & 0o777;\n if (mode !== 0o600) {\n fs.chmodSync(this.filePath, 0o600);\n process.stderr.write(\n `[warn] credentials file permissions were 0o${mode.toString(8)}; corrected to 0600.\\n`,\n );\n }\n }\n}\n","/**\n * Runtime validation for the on-disk credentials file.\n *\n * The parser is deliberately strict: unknown top-level keys, missing\n * fields, non-ISO timestamps, and any `version` other than `1` are all\n * rejected with a typed ValidationError. Error messages NEVER embed the\n * raw file contents — a malformed file may contain a truncated token.\n */\n\nimport { z } from 'zod';\nimport { ValidationError } from '../errors.js';\nimport type { Credentials } from './types.js';\n\nconst identitySchema = z\n .object({\n developerId: z.string(),\n email: z.string(),\n // Token-derived fields captured at login. Optional (additive) so files\n // written before these fields existed still validate as version 1.\n merchantId: z.string().optional(),\n scopes: z.array(z.string()).optional(),\n })\n .strict();\n\nconst profileSchema = z\n .object({\n accessToken: z.string(),\n refreshToken: z.string(),\n expiresAt: z.string().datetime({ offset: true }),\n identity: identitySchema,\n obtainedAt: z.string().datetime({ offset: true }),\n })\n .strict();\n\nconst developerSessionSchema = z\n .object({\n jwt: z.string(),\n developerId: z.string(),\n email: z.string(),\n expiresAt: z.string().datetime({ offset: true }),\n obtainedAt: z.string().datetime({ offset: true }),\n })\n .strict();\n\n/** Strict zod schema for the version-1 credentials file. */\nexport const credentialsSchema = z\n .object({\n version: z.literal(1),\n server: z.string(),\n clientId: z.string(),\n profiles: z.record(z.string(), profileSchema),\n // Optional cached developer session. Additive so files written before\n // this field existed still validate as version 1.\n developer: developerSessionSchema.optional(),\n })\n .strict();\n\n/**\n * Validate an already-JSON-parsed value against the version-1 shape.\n *\n * Throws ValidationError on any mismatch. A recognisable-but-unsupported\n * `version` gets a dedicated upgrade message; the version label is only\n * echoed when it is a number so arbitrary file contents can never leak\n * into an error message.\n */\nexport function parseCredentials(input: unknown): Credentials {\n if (typeof input === 'object' && input !== null && 'version' in input) {\n const version = (input as { version: unknown }).version;\n if (version !== 1) {\n const label = typeof version === 'number' ? String(version) : 'unknown';\n throw new ValidationError(\n `credentials file version ${label} is unsupported by this CLI — upgrade the CLI or sign in again`,\n );\n }\n }\n\n const result = credentialsSchema.safeParse(input);\n if (!result.success) {\n throw new ValidationError(\n 'credentials file schema mismatch — expected v1 shape',\n );\n }\n return result.data as Credentials;\n}\n"],"mappings":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I,SAAS,KAAO;AAClB,SAAG,UAAU,KAAK,UAAU,GAAK;AACjC,cAAQ,OAAO;AAAA,QACb,8CAA8C,KAAK,SAAS,CAAC,CAAC;AAAA;AAAA,MAChE;AAAA,IACF;AAAA,EACF;AACF;","names":["base"]}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure path resolution for the credentials file.
|
|
3
|
+
*
|
|
4
|
+
* POSIX: `$XDG_CONFIG_HOME/ratio/credentials` when the override is a
|
|
5
|
+
* non-empty string, otherwise `~/.config/ratio/credentials`.
|
|
6
|
+
* Windows: `%APPDATA%\ratio\credentials`, falling back to
|
|
7
|
+
* `<home>\AppData\Roaming\ratio\credentials` when APPDATA is unset.
|
|
8
|
+
*
|
|
9
|
+
* `path.win32.join` / `path.posix.join` are used explicitly (never bare
|
|
10
|
+
* `path.join`) so the result is deterministic when a test running on a
|
|
11
|
+
* POSIX host fakes `platform === 'win32'`.
|
|
12
|
+
*/
|
|
13
|
+
/** The subset of environment variables the path algorithm consults. */
|
|
14
|
+
interface PathEnv {
|
|
15
|
+
readonly XDG_CONFIG_HOME?: string;
|
|
16
|
+
readonly APPDATA?: string;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Pure function. Returns the on-disk path for the credentials file.
|
|
20
|
+
* platform defaults to process.platform, homedir defaults to os.homedir(),
|
|
21
|
+
* env defaults to a snapshot of {XDG_CONFIG_HOME, APPDATA} from process.env.
|
|
22
|
+
* All three are injectable so unit tests fake Windows without a Windows host.
|
|
23
|
+
*/
|
|
24
|
+
declare function defaultCredentialsPath(platform?: NodeJS.Platform, homedir?: string, env?: PathEnv): string;
|
|
25
|
+
|
|
26
|
+
export { type PathEnv, defaultCredentialsPath };
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// src/lib/credentials/path.ts
|
|
2
|
+
import os from "os";
|
|
3
|
+
import path from "path";
|
|
4
|
+
function snapshotPathEnv() {
|
|
5
|
+
const snapshot = {};
|
|
6
|
+
const xdgConfigHome = process.env["XDG_CONFIG_HOME"];
|
|
7
|
+
if (xdgConfigHome !== void 0) {
|
|
8
|
+
snapshot.XDG_CONFIG_HOME = xdgConfigHome;
|
|
9
|
+
}
|
|
10
|
+
const appData = process.env["APPDATA"];
|
|
11
|
+
if (appData !== void 0) {
|
|
12
|
+
snapshot.APPDATA = appData;
|
|
13
|
+
}
|
|
14
|
+
return snapshot;
|
|
15
|
+
}
|
|
16
|
+
function defaultCredentialsPath(platform, homedir, env) {
|
|
17
|
+
const resolvedPlatform = platform ?? process.platform;
|
|
18
|
+
const resolvedHome = homedir ?? os.homedir();
|
|
19
|
+
const resolvedEnv = env ?? snapshotPathEnv();
|
|
20
|
+
if (resolvedPlatform === "win32") {
|
|
21
|
+
const appData = resolvedEnv.APPDATA;
|
|
22
|
+
const base2 = appData !== void 0 && appData !== "" ? appData : path.win32.join(resolvedHome, "AppData", "Roaming");
|
|
23
|
+
return path.win32.join(base2, "ratio", "credentials");
|
|
24
|
+
}
|
|
25
|
+
const xdgConfigHome = resolvedEnv.XDG_CONFIG_HOME;
|
|
26
|
+
const base = typeof xdgConfigHome === "string" && xdgConfigHome !== "" ? xdgConfigHome : path.posix.join(resolvedHome, ".config");
|
|
27
|
+
return path.posix.join(base, "ratio", "credentials");
|
|
28
|
+
}
|
|
29
|
+
export {
|
|
30
|
+
defaultCredentialsPath
|
|
31
|
+
};
|
|
32
|
+
//# sourceMappingURL=path.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/lib/credentials/path.ts"],"sourcesContent":["/**\n * Pure path resolution for the credentials file.\n *\n * POSIX: `$XDG_CONFIG_HOME/ratio/credentials` when the override is a\n * non-empty string, otherwise `~/.config/ratio/credentials`.\n * Windows: `%APPDATA%\\ratio\\credentials`, falling back to\n * `<home>\\AppData\\Roaming\\ratio\\credentials` when APPDATA is unset.\n *\n * `path.win32.join` / `path.posix.join` are used explicitly (never bare\n * `path.join`) so the result is deterministic when a test running on a\n * POSIX host fakes `platform === 'win32'`.\n */\n\nimport os from 'node:os';\nimport path from 'node:path';\n\n/** The subset of environment variables the path algorithm consults. */\nexport interface PathEnv {\n readonly XDG_CONFIG_HOME?: string;\n readonly APPDATA?: string;\n}\n\n/** Snapshot the two relevant variables from the real process env. */\nfunction snapshotPathEnv(): PathEnv {\n const snapshot: { XDG_CONFIG_HOME?: string; APPDATA?: string } = {};\n const xdgConfigHome = process.env['XDG_CONFIG_HOME'];\n if (xdgConfigHome !== undefined) {\n snapshot.XDG_CONFIG_HOME = xdgConfigHome;\n }\n const appData = process.env['APPDATA'];\n if (appData !== undefined) {\n snapshot.APPDATA = appData;\n }\n return snapshot;\n}\n\n/**\n * Pure function. Returns the on-disk path for the credentials file.\n * platform defaults to process.platform, homedir defaults to os.homedir(),\n * env defaults to a snapshot of {XDG_CONFIG_HOME, APPDATA} from process.env.\n * All three are injectable so unit tests fake Windows without a Windows host.\n */\nexport function defaultCredentialsPath(\n platform?: NodeJS.Platform,\n homedir?: string,\n env?: PathEnv,\n): string {\n const resolvedPlatform = platform ?? process.platform;\n const resolvedHome = homedir ?? os.homedir();\n const resolvedEnv = env ?? snapshotPathEnv();\n\n if (resolvedPlatform === 'win32') {\n const appData = resolvedEnv.APPDATA;\n const base =\n appData !== undefined && appData !== ''\n ? appData\n : path.win32.join(resolvedHome, 'AppData', 'Roaming');\n return path.win32.join(base, 'ratio', 'credentials');\n }\n\n const xdgConfigHome = resolvedEnv.XDG_CONFIG_HOME;\n const base =\n typeof xdgConfigHome === 'string' && xdgConfigHome !== ''\n ? xdgConfigHome\n : path.posix.join(resolvedHome, '.config');\n return path.posix.join(base, 'ratio', 'credentials');\n}\n"],"mappings":";AAaA,OAAO,QAAQ;AACf,OAAO,UAAU;AASjB,SAAS,kBAA2B;AAClC,QAAM,WAA2D,CAAC;AAClE,QAAM,gBAAgB,QAAQ,IAAI,iBAAiB;AACnD,MAAI,kBAAkB,QAAW;AAC/B,aAAS,kBAAkB;AAAA,EAC7B;AACA,QAAM,UAAU,QAAQ,IAAI,SAAS;AACrC,MAAI,YAAY,QAAW;AACzB,aAAS,UAAU;AAAA,EACrB;AACA,SAAO;AACT;AAQO,SAAS,uBACd,UACA,SACA,KACQ;AACR,QAAM,mBAAmB,YAAY,QAAQ;AAC7C,QAAM,eAAe,WAAW,GAAG,QAAQ;AAC3C,QAAM,cAAc,OAAO,gBAAgB;AAE3C,MAAI,qBAAqB,SAAS;AAChC,UAAM,UAAU,YAAY;AAC5B,UAAMA,QACJ,YAAY,UAAa,YAAY,KACjC,UACA,KAAK,MAAM,KAAK,cAAc,WAAW,SAAS;AACxD,WAAO,KAAK,MAAM,KAAKA,OAAM,SAAS,aAAa;AAAA,EACrD;AAEA,QAAM,gBAAgB,YAAY;AAClC,QAAM,OACJ,OAAO,kBAAkB,YAAY,kBAAkB,KACnD,gBACA,KAAK,MAAM,KAAK,cAAc,SAAS;AAC7C,SAAO,KAAK,MAAM,KAAK,MAAM,SAAS,aAAa;AACrD;","names":["base"]}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { TokenSet } from './types.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Injectable token-refresh seam for the credential store.
|
|
5
|
+
*
|
|
6
|
+
* The store never performs network I/O itself: when a stored token is
|
|
7
|
+
* close to expiry the store calls the injected {@link TokenRefresher}
|
|
8
|
+
* and persists whatever it returns. The concrete HTTP implementation is
|
|
9
|
+
* wired in by the auth commands; this module only defines the seam plus
|
|
10
|
+
* a throw-if-called placeholder used before sign-in support is wired.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** Injectable seam that exchanges a refresh token for a fresh token set. */
|
|
14
|
+
interface TokenRefresher {
|
|
15
|
+
refresh(refreshToken: string): Promise<TokenSet>;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* v1 stub. Always rejects with a static-message NotLoggedInError; it
|
|
19
|
+
* never inspects, echoes, or logs the token it was handed. The real
|
|
20
|
+
* HTTP implementation is supplied by the auth commands.
|
|
21
|
+
*/
|
|
22
|
+
declare class NotImplementedRefresher implements TokenRefresher {
|
|
23
|
+
refresh(refreshToken: string): Promise<TokenSet>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export { NotImplementedRefresher, type TokenRefresher };
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// src/lib/errors.ts
|
|
2
|
+
var RatioCLIError = class extends Error {
|
|
3
|
+
code;
|
|
4
|
+
exitCode;
|
|
5
|
+
hint;
|
|
6
|
+
docsUrl;
|
|
7
|
+
constructor(opts) {
|
|
8
|
+
super(opts.message);
|
|
9
|
+
this.name = new.target.name;
|
|
10
|
+
this.code = opts.code;
|
|
11
|
+
this.exitCode = opts.exitCode;
|
|
12
|
+
if (opts.hint !== void 0) this.hint = opts.hint;
|
|
13
|
+
if (opts.docsUrl !== void 0) this.docsUrl = opts.docsUrl;
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
var NotLoggedInError = class extends RatioCLIError {
|
|
17
|
+
constructor(message, hint = "Run 'ratio auth login' to sign in.") {
|
|
18
|
+
super({ code: "NOT_LOGGED_IN", exitCode: 3, message, hint });
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
// src/lib/credentials/refresher.ts
|
|
23
|
+
var NotImplementedRefresher = class {
|
|
24
|
+
async refresh(refreshToken) {
|
|
25
|
+
void refreshToken;
|
|
26
|
+
throw new NotLoggedInError(
|
|
27
|
+
"Token refresh is not available yet in this CLI version."
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
export {
|
|
32
|
+
NotImplementedRefresher
|
|
33
|
+
};
|
|
34
|
+
//# sourceMappingURL=refresher.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/lib/errors.ts","../../../src/lib/credentials/refresher.ts"],"sourcesContent":["/**\n * Error hierarchy for the Ratio CLI. Every error thrown from a command's\n * run() is expected to be an instance of RatioCLIError so the global\n * render-error handler can map it to a deterministic stderr line and exit\n * code. Uncaught Error subclasses render as \"INTERNAL: <msg>\" with exit 1.\n *\n * No import from @oclif/core — this file is dependency-free so tests\n * can import it without oclif overhead.\n */\n\nexport class RatioCLIError extends Error {\n readonly code: string;\n readonly exitCode: number;\n readonly hint?: string;\n readonly docsUrl?: string;\n\n constructor(opts: {\n code: string;\n exitCode: number;\n message: string;\n hint?: string;\n docsUrl?: string;\n }) {\n super(opts.message);\n this.name = new.target.name;\n this.code = opts.code;\n this.exitCode = opts.exitCode;\n if (opts.hint !== undefined) this.hint = opts.hint;\n if (opts.docsUrl !== undefined) this.docsUrl = opts.docsUrl;\n }\n}\n\n/** Coming-soon stub UX. Renders on stdout with exit 0. */\nexport class ComingSoonError extends RatioCLIError {\n constructor(message: string) {\n super({ code: 'COMING_SOON', exitCode: 0, message });\n }\n}\n\n/** User has no credentials and command requires auth. */\nexport class NotLoggedInError extends RatioCLIError {\n constructor(\n message: string,\n hint: string = \"Run 'ratio auth login' to sign in.\",\n ) {\n super({ code: 'NOT_LOGGED_IN', exitCode: 3, message, hint });\n }\n}\n\nexport class TokenExpiredError extends RatioCLIError {\n constructor(\n message: string,\n hint: string = \"Run 'ratio auth login' to refresh your session.\",\n ) {\n super({ code: 'TOKEN_EXPIRED', exitCode: 3, message, hint });\n }\n}\n\nexport class ScopeDeniedError extends RatioCLIError {\n constructor(message: string, hint?: string) {\n const opts: { code: string; exitCode: number; message: string; hint?: string } = {\n code: 'SCOPE_DENIED',\n exitCode: 4,\n message,\n };\n if (hint !== undefined) opts.hint = hint;\n super(opts);\n }\n}\n\nexport class NetworkError extends RatioCLIError {\n constructor(message: string, hint: string = 'Check your network and retry.') {\n super({ code: 'NETWORK_ERROR', exitCode: 5, message, hint });\n }\n}\n\nexport class RelayConnectError extends RatioCLIError {\n constructor(\n message: string,\n hint: string = 'Verify the tunnel URL and that the auth-server is reachable.',\n ) {\n super({ code: 'RELAY_CONNECT', exitCode: 6, message, hint });\n }\n}\n\nexport class TemplateExistsError extends RatioCLIError {\n constructor(\n message: string,\n hint: string = 'Choose a different name or remove the existing directory.',\n ) {\n super({ code: 'TEMPLATE_EXISTS', exitCode: 7, message, hint });\n }\n}\n\nexport class ValidationError extends RatioCLIError {\n constructor(message: string, hint?: string) {\n const opts: { code: string; exitCode: number; message: string; hint?: string } = {\n code: 'VALIDATION_ERROR',\n exitCode: 8,\n message,\n };\n if (hint !== undefined) opts.hint = hint;\n super(opts);\n }\n}\n\nexport class RelayResumeGapError extends RatioCLIError {\n constructor(\n message: string,\n hint: string = 'Reconnect from the current cursor; older events are outside the buffer window.',\n ) {\n super({ code: 'RELAY_RESUME_GAP', exitCode: 9, message, hint });\n }\n}\n\nexport class OrchestratorSpawnError extends RatioCLIError {\n constructor(\n message: string,\n hint: string = \"Could not start your app's dev command — check that the command in ratio.config.jsonc runs from this directory.\",\n ) {\n super({ code: 'ORCHESTRATOR_SPAWN', exitCode: 10, message, hint });\n }\n}\n\nexport class OrchestratorDrainTimeoutError extends RatioCLIError {\n constructor(\n message: string,\n hint: string = 'Your dev command did not exit cleanly within 5 seconds — it was forcibly terminated.',\n ) {\n super({ code: 'ORCHESTRATOR_DRAIN', exitCode: 11, message, hint });\n }\n}\n\nexport function isRatioCLIError(err: unknown): err is RatioCLIError {\n return err instanceof RatioCLIError;\n}\n","/**\n * Injectable token-refresh seam for the credential store.\n *\n * The store never performs network I/O itself: when a stored token is\n * close to expiry the store calls the injected {@link TokenRefresher}\n * and persists whatever it returns. The concrete HTTP implementation is\n * wired in by the auth commands; this module only defines the seam plus\n * a throw-if-called placeholder used before sign-in support is wired.\n */\n\nimport { NotLoggedInError } from '../errors.js';\nimport type { TokenSet } from './types.js';\n\n/** Injectable seam that exchanges a refresh token for a fresh token set. */\nexport interface TokenRefresher {\n refresh(refreshToken: string): Promise<TokenSet>;\n}\n\n/**\n * v1 stub. Always rejects with a static-message NotLoggedInError; it\n * never inspects, echoes, or logs the token it was handed. The real\n * HTTP implementation is supplied by the auth commands.\n */\nexport class NotImplementedRefresher implements TokenRefresher {\n async refresh(refreshToken: string): Promise<TokenSet> {\n // Deliberately unused: this placeholder must never touch the token.\n void refreshToken;\n throw new NotLoggedInError(\n 'Token refresh is not available yet in this CLI version.',\n );\n }\n}\n"],"mappings":";AAUO,IAAM,gBAAN,cAA4B,MAAM;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,MAMT;AACD,UAAM,KAAK,OAAO;AAClB,SAAK,OAAO,WAAW;AACvB,SAAK,OAAO,KAAK;AACjB,SAAK,WAAW,KAAK;AACrB,QAAI,KAAK,SAAS,OAAW,MAAK,OAAO,KAAK;AAC9C,QAAI,KAAK,YAAY,OAAW,MAAK,UAAU,KAAK;AAAA,EACtD;AACF;AAUO,IAAM,mBAAN,cAA+B,cAAc;AAAA,EAClD,YACE,SACA,OAAe,sCACf;AACA,UAAM,EAAE,MAAM,iBAAiB,UAAU,GAAG,SAAS,KAAK,CAAC;AAAA,EAC7D;AACF;;;ACxBO,IAAM,0BAAN,MAAwD;AAAA,EAC7D,MAAM,QAAQ,cAAyC;AAErD,SAAK;AACL,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|