@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,527 @@
|
|
|
1
|
+
// src/lib/auth/pkce.ts
|
|
2
|
+
import crypto from "crypto";
|
|
3
|
+
function computeS256Challenge(codeVerifier) {
|
|
4
|
+
return crypto.createHash("sha256").update(codeVerifier, "ascii").digest("base64url");
|
|
5
|
+
}
|
|
6
|
+
function generatePkcePair() {
|
|
7
|
+
const codeVerifier = crypto.randomBytes(96).toString("base64url");
|
|
8
|
+
const codeChallenge = computeS256Challenge(codeVerifier);
|
|
9
|
+
return { codeVerifier, codeChallenge, codeChallengeMethod: "S256" };
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// src/lib/auth/state.ts
|
|
13
|
+
import crypto2 from "crypto";
|
|
14
|
+
function generateState() {
|
|
15
|
+
return crypto2.randomBytes(32).toString("base64url");
|
|
16
|
+
}
|
|
17
|
+
function timingSafeEqualState(a, b) {
|
|
18
|
+
const aBuf = Buffer.from(a, "utf8");
|
|
19
|
+
const bBuf = Buffer.from(b, "utf8");
|
|
20
|
+
if (aBuf.length !== bBuf.length) {
|
|
21
|
+
crypto2.timingSafeEqual(aBuf, aBuf);
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
return crypto2.timingSafeEqual(aBuf, bBuf);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// src/lib/auth/config.ts
|
|
28
|
+
var DEFAULT_SERVER_URL = "https://gkx.ratio.win";
|
|
29
|
+
var RATIO_CLI_MERCHANT_ID = "ratio-cli-dev";
|
|
30
|
+
var RATIO_CLI_CLIENT_ID = "ratio-cli";
|
|
31
|
+
function resolveServerUrl(opts) {
|
|
32
|
+
const env = opts?.env ?? process.env;
|
|
33
|
+
if (typeof env["RATIO_SERVER_URL"] === "string" && env["RATIO_SERVER_URL"].length > 0) {
|
|
34
|
+
return env["RATIO_SERVER_URL"];
|
|
35
|
+
}
|
|
36
|
+
if (typeof opts?.credentials?.server === "string" && opts.credentials.server.length > 0) {
|
|
37
|
+
return opts.credentials.server;
|
|
38
|
+
}
|
|
39
|
+
return DEFAULT_SERVER_URL;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// src/lib/auth/authorize-url.ts
|
|
43
|
+
function buildBrowserAuthorizeUrl(o) {
|
|
44
|
+
const params = new URLSearchParams();
|
|
45
|
+
params.set("client_id", o.clientId);
|
|
46
|
+
params.set("merchant_id", o.merchantId ?? RATIO_CLI_MERCHANT_ID);
|
|
47
|
+
params.set("code_challenge", o.codeChallenge);
|
|
48
|
+
params.set("code_challenge_method", "S256");
|
|
49
|
+
params.set("state", o.state);
|
|
50
|
+
params.set("redirect_uri", o.redirectUri);
|
|
51
|
+
if (o.scopes && o.scopes.length > 0) {
|
|
52
|
+
params.set("scope", o.scopes.join(","));
|
|
53
|
+
}
|
|
54
|
+
return `${o.serverUrl}/oauth/authorize?${params.toString()}`;
|
|
55
|
+
}
|
|
56
|
+
function buildManualAuthorizeUrl(o) {
|
|
57
|
+
const params = new URLSearchParams();
|
|
58
|
+
params.set("client_id", o.clientId);
|
|
59
|
+
params.set("merchant_id", o.merchantId ?? RATIO_CLI_MERCHANT_ID);
|
|
60
|
+
params.set("code_challenge", o.codeChallenge);
|
|
61
|
+
params.set("code_challenge_method", "S256");
|
|
62
|
+
params.set("state", o.state);
|
|
63
|
+
params.set("display_code", "1");
|
|
64
|
+
if (o.scopes && o.scopes.length > 0) {
|
|
65
|
+
params.set("scope", o.scopes.join(","));
|
|
66
|
+
}
|
|
67
|
+
return `${o.serverUrl}/oauth/authorize?${params.toString()}`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// src/lib/auth/authorize-code-exchange.ts
|
|
71
|
+
import { z } from "zod";
|
|
72
|
+
|
|
73
|
+
// src/lib/errors.ts
|
|
74
|
+
var RatioCLIError = class extends Error {
|
|
75
|
+
code;
|
|
76
|
+
exitCode;
|
|
77
|
+
hint;
|
|
78
|
+
docsUrl;
|
|
79
|
+
constructor(opts) {
|
|
80
|
+
super(opts.message);
|
|
81
|
+
this.name = new.target.name;
|
|
82
|
+
this.code = opts.code;
|
|
83
|
+
this.exitCode = opts.exitCode;
|
|
84
|
+
if (opts.hint !== void 0) this.hint = opts.hint;
|
|
85
|
+
if (opts.docsUrl !== void 0) this.docsUrl = opts.docsUrl;
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
var NotLoggedInError = class extends RatioCLIError {
|
|
89
|
+
constructor(message, hint = "Run 'ratio auth login' to sign in.") {
|
|
90
|
+
super({ code: "NOT_LOGGED_IN", exitCode: 3, message, hint });
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
var TokenExpiredError = class extends RatioCLIError {
|
|
94
|
+
constructor(message, hint = "Run 'ratio auth login' to refresh your session.") {
|
|
95
|
+
super({ code: "TOKEN_EXPIRED", exitCode: 3, message, hint });
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
var NetworkError = class extends RatioCLIError {
|
|
99
|
+
constructor(message, hint = "Check your network and retry.") {
|
|
100
|
+
super({ code: "NETWORK_ERROR", exitCode: 5, message, hint });
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
var ValidationError = class extends RatioCLIError {
|
|
104
|
+
constructor(message, hint) {
|
|
105
|
+
const opts = {
|
|
106
|
+
code: "VALIDATION_ERROR",
|
|
107
|
+
exitCode: 8,
|
|
108
|
+
message
|
|
109
|
+
};
|
|
110
|
+
if (hint !== void 0) opts.hint = hint;
|
|
111
|
+
super(opts);
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
// src/lib/auth/verbose-trace.ts
|
|
116
|
+
var noopTracer = () => {
|
|
117
|
+
};
|
|
118
|
+
function createVerboseTracer(verbose, write = (line) => {
|
|
119
|
+
process.stderr.write(line);
|
|
120
|
+
}) {
|
|
121
|
+
if (!verbose) return noopTracer;
|
|
122
|
+
return (msg) => {
|
|
123
|
+
write(`[verbose] ${msg}
|
|
124
|
+
`);
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// src/lib/auth/authorize-code-exchange.ts
|
|
129
|
+
var TokenResponseSchema = z.object({
|
|
130
|
+
access_token: z.string().min(1),
|
|
131
|
+
refresh_token: z.string().min(1),
|
|
132
|
+
expires_in: z.number().int().positive(),
|
|
133
|
+
token_type: z.string().optional(),
|
|
134
|
+
scope: z.string().optional(),
|
|
135
|
+
merchant_id: z.string().optional()
|
|
136
|
+
});
|
|
137
|
+
function exchangeCodeForTokens(i) {
|
|
138
|
+
return _exchangeCodeForTokensImpl(i);
|
|
139
|
+
}
|
|
140
|
+
async function _exchangeCodeForTokensImpl(i) {
|
|
141
|
+
const fetchFn = i.fetchImpl ?? fetch;
|
|
142
|
+
const body = {
|
|
143
|
+
grant_type: "authorization_code",
|
|
144
|
+
code: i.code,
|
|
145
|
+
clientId: i.clientId,
|
|
146
|
+
codeVerifier: i.codeVerifier
|
|
147
|
+
};
|
|
148
|
+
if (i.redirectUri !== void 0) {
|
|
149
|
+
body["redirectUri"] = i.redirectUri;
|
|
150
|
+
}
|
|
151
|
+
const trace = i.trace ?? noopTracer;
|
|
152
|
+
const startedAt = Date.now();
|
|
153
|
+
let response;
|
|
154
|
+
try {
|
|
155
|
+
response = await fetchFn(`${i.serverUrl}/oauth/token`, {
|
|
156
|
+
method: "POST",
|
|
157
|
+
headers: { "Content-Type": "application/json" },
|
|
158
|
+
body: JSON.stringify(body)
|
|
159
|
+
});
|
|
160
|
+
} catch {
|
|
161
|
+
trace(`POST /oauth/token \u2192 network error (${Date.now() - startedAt}ms)`);
|
|
162
|
+
throw new NetworkError("Failed to reach the Ratio server during token exchange.");
|
|
163
|
+
}
|
|
164
|
+
trace(`POST /oauth/token \u2192 ${response.status} (${Date.now() - startedAt}ms)`);
|
|
165
|
+
if (response.status >= 400 && response.status < 500) {
|
|
166
|
+
throw new ValidationError(
|
|
167
|
+
"The authorization code was rejected. Run 'ratio auth login' again."
|
|
168
|
+
);
|
|
169
|
+
}
|
|
170
|
+
if (response.status >= 500 || !response.ok) {
|
|
171
|
+
throw new NetworkError("The Ratio server returned an error during token exchange.");
|
|
172
|
+
}
|
|
173
|
+
let raw;
|
|
174
|
+
try {
|
|
175
|
+
raw = await response.json();
|
|
176
|
+
} catch {
|
|
177
|
+
throw new ValidationError("Token response was not valid JSON.");
|
|
178
|
+
}
|
|
179
|
+
const parsed = TokenResponseSchema.safeParse(raw);
|
|
180
|
+
if (!parsed.success) {
|
|
181
|
+
throw new ValidationError("Token response shape was unexpected. Run ratio auth login again.");
|
|
182
|
+
}
|
|
183
|
+
const data = parsed.data;
|
|
184
|
+
const expiresAt = new Date(Date.now() + data.expires_in * 1e3).toISOString();
|
|
185
|
+
const tokens = {
|
|
186
|
+
accessToken: data.access_token,
|
|
187
|
+
refreshToken: data.refresh_token,
|
|
188
|
+
expiresAt
|
|
189
|
+
};
|
|
190
|
+
const scopeStr = data.scope ?? "";
|
|
191
|
+
const scopes = scopeStr.length > 0 ? scopeStr.split(/[\s,]+/).filter(Boolean) : [];
|
|
192
|
+
const identity = {
|
|
193
|
+
clientId: i.clientId,
|
|
194
|
+
merchantId: data.merchant_id ?? "ratio-cli-dev",
|
|
195
|
+
scopes
|
|
196
|
+
};
|
|
197
|
+
return { tokens, identity };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// src/lib/auth/http-refresher.ts
|
|
201
|
+
import { z as z2 } from "zod";
|
|
202
|
+
var RefreshResponseSchema = z2.object({
|
|
203
|
+
access_token: z2.string().min(1),
|
|
204
|
+
refresh_token: z2.string().min(1),
|
|
205
|
+
expires_in: z2.number().int().positive()
|
|
206
|
+
});
|
|
207
|
+
var HttpTokenRefresher = class {
|
|
208
|
+
serverUrl;
|
|
209
|
+
clientId;
|
|
210
|
+
fetchImpl;
|
|
211
|
+
trace;
|
|
212
|
+
constructor(opts) {
|
|
213
|
+
this.serverUrl = opts.serverUrl;
|
|
214
|
+
this.clientId = opts.clientId;
|
|
215
|
+
this.fetchImpl = opts.fetchImpl ?? fetch;
|
|
216
|
+
this.trace = opts.trace ?? noopTracer;
|
|
217
|
+
}
|
|
218
|
+
async refresh(refreshToken) {
|
|
219
|
+
const body = {
|
|
220
|
+
grant_type: "refresh_token",
|
|
221
|
+
refresh_token: refreshToken,
|
|
222
|
+
clientId: this.clientId
|
|
223
|
+
};
|
|
224
|
+
this.trace("refresh: fired (access token expired or expiring)");
|
|
225
|
+
const startedAt = Date.now();
|
|
226
|
+
let response;
|
|
227
|
+
try {
|
|
228
|
+
response = await this.fetchImpl(`${this.serverUrl}/oauth/token`, {
|
|
229
|
+
method: "POST",
|
|
230
|
+
headers: { "Content-Type": "application/json" },
|
|
231
|
+
body: JSON.stringify(body)
|
|
232
|
+
});
|
|
233
|
+
} catch {
|
|
234
|
+
this.trace(`POST /oauth/token \u2192 network error (${Date.now() - startedAt}ms)`);
|
|
235
|
+
throw new NetworkError("Failed to reach the Ratio server during token refresh.");
|
|
236
|
+
}
|
|
237
|
+
this.trace(`POST /oauth/token \u2192 ${response.status} (${Date.now() - startedAt}ms)`);
|
|
238
|
+
if (response.status >= 400 && response.status < 500) {
|
|
239
|
+
throw new TokenExpiredError(
|
|
240
|
+
"Your session has expired and could not be refreshed."
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
if (response.status >= 500 || !response.ok) {
|
|
244
|
+
throw new NetworkError("The Ratio server returned an error during token refresh.");
|
|
245
|
+
}
|
|
246
|
+
let raw;
|
|
247
|
+
try {
|
|
248
|
+
raw = await response.json();
|
|
249
|
+
} catch {
|
|
250
|
+
throw new NetworkError("Token refresh response was not valid JSON.");
|
|
251
|
+
}
|
|
252
|
+
const parsed = RefreshResponseSchema.safeParse(raw);
|
|
253
|
+
if (!parsed.success) {
|
|
254
|
+
throw new TokenExpiredError(
|
|
255
|
+
"Your session has expired and could not be refreshed."
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
const data = parsed.data;
|
|
259
|
+
const expiresAt = new Date(Date.now() + data.expires_in * 1e3).toISOString();
|
|
260
|
+
return {
|
|
261
|
+
accessToken: data.access_token,
|
|
262
|
+
refreshToken: data.refresh_token,
|
|
263
|
+
expiresAt
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
// src/lib/auth/loopback-server.ts
|
|
269
|
+
import http from "http";
|
|
270
|
+
function awaitLoopbackCallback(o) {
|
|
271
|
+
const trace = o.trace ?? noopTracer;
|
|
272
|
+
return new Promise((resolve, reject) => {
|
|
273
|
+
let settled = false;
|
|
274
|
+
function settle(fn) {
|
|
275
|
+
if (settled) return;
|
|
276
|
+
settled = true;
|
|
277
|
+
server.close(() => fn());
|
|
278
|
+
}
|
|
279
|
+
const server = http.createServer((req, res) => {
|
|
280
|
+
const reqUrl = new URL(req.url ?? "/", `http://127.0.0.1`);
|
|
281
|
+
if (reqUrl.pathname !== "/callback") {
|
|
282
|
+
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
283
|
+
res.end("Not found");
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
const code = reqUrl.searchParams.get("code");
|
|
287
|
+
const state = reqUrl.searchParams.get("state");
|
|
288
|
+
if (!state || !timingSafeEqualState(state, o.expectedState)) {
|
|
289
|
+
trace("callback: state mismatch");
|
|
290
|
+
res.writeHead(400, { "Content-Type": "text/plain" });
|
|
291
|
+
res.end("State mismatch");
|
|
292
|
+
settle(
|
|
293
|
+
() => reject(
|
|
294
|
+
new ValidationError("Authorization callback failed a security check.")
|
|
295
|
+
)
|
|
296
|
+
);
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
if (!code || code.length === 0) {
|
|
300
|
+
trace("callback: missing code");
|
|
301
|
+
res.writeHead(400, { "Content-Type": "text/plain" });
|
|
302
|
+
res.end("Missing code");
|
|
303
|
+
settle(
|
|
304
|
+
() => reject(
|
|
305
|
+
new ValidationError("Authorization callback did not return a code.")
|
|
306
|
+
)
|
|
307
|
+
);
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
res.writeHead(200, { "Content-Type": "text/html" });
|
|
311
|
+
res.end("<html><body><h1>Signed in! You can close this tab.</h1></body></html>");
|
|
312
|
+
const addr = server.address();
|
|
313
|
+
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
|
314
|
+
const redirectUri = `http://127.0.0.1:${port}/callback`;
|
|
315
|
+
trace(`callback: received on port ${port} (state ok)`);
|
|
316
|
+
settle(() => resolve({ code, redirectUri }));
|
|
317
|
+
});
|
|
318
|
+
server.on("error", (err) => {
|
|
319
|
+
settle(() => reject(err));
|
|
320
|
+
});
|
|
321
|
+
server.listen(0, "127.0.0.1", () => {
|
|
322
|
+
const boundAddr = server.address();
|
|
323
|
+
const boundPort = typeof boundAddr === "object" && boundAddr !== null ? boundAddr.port : 0;
|
|
324
|
+
trace(`loopback: bound 127.0.0.1:${boundPort}`);
|
|
325
|
+
const timer = setTimeout(() => {
|
|
326
|
+
trace(`callback: timeout fired after ${o.timeoutMs}ms`);
|
|
327
|
+
settle(
|
|
328
|
+
() => reject(
|
|
329
|
+
new NotLoggedInError(
|
|
330
|
+
"Browser flow timed out. Run 'ratio auth login --manual' to complete without a browser."
|
|
331
|
+
)
|
|
332
|
+
)
|
|
333
|
+
);
|
|
334
|
+
}, o.timeoutMs);
|
|
335
|
+
if (typeof timer.unref === "function") {
|
|
336
|
+
timer.unref();
|
|
337
|
+
}
|
|
338
|
+
if (o.signal) {
|
|
339
|
+
o.signal.addEventListener("abort", () => {
|
|
340
|
+
trace("callback: cancelled");
|
|
341
|
+
clearTimeout(timer);
|
|
342
|
+
settle(
|
|
343
|
+
() => reject(
|
|
344
|
+
new NotLoggedInError(
|
|
345
|
+
"Browser flow was cancelled. Run 'ratio auth login --manual' to complete without a browser."
|
|
346
|
+
)
|
|
347
|
+
)
|
|
348
|
+
);
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
});
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
function buildLoopbackRedirectUri(port) {
|
|
355
|
+
return `http://127.0.0.1:${port}/callback`;
|
|
356
|
+
}
|
|
357
|
+
function startLoopbackSession(trace = noopTracer) {
|
|
358
|
+
return new Promise((resolve, reject) => {
|
|
359
|
+
let settled = false;
|
|
360
|
+
function settle(fn) {
|
|
361
|
+
if (settled) return;
|
|
362
|
+
settled = true;
|
|
363
|
+
fn();
|
|
364
|
+
}
|
|
365
|
+
const server = http.createServer();
|
|
366
|
+
server.on("error", reject);
|
|
367
|
+
server.listen(0, "127.0.0.1", () => {
|
|
368
|
+
const addr = server.address();
|
|
369
|
+
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
|
370
|
+
const redirectUri = buildLoopbackRedirectUri(port);
|
|
371
|
+
trace(`loopback: bound 127.0.0.1:${port}`);
|
|
372
|
+
resolve({
|
|
373
|
+
port,
|
|
374
|
+
redirectUri,
|
|
375
|
+
awaitCallback(opts) {
|
|
376
|
+
const timeoutMs = opts.timeoutMs ?? 3e4;
|
|
377
|
+
return new Promise((res, rej) => {
|
|
378
|
+
server.on("request", (req, response) => {
|
|
379
|
+
const reqUrl = new URL(req.url ?? "/", `http://127.0.0.1`);
|
|
380
|
+
if (reqUrl.pathname !== "/callback") {
|
|
381
|
+
response.writeHead(404, { "Content-Type": "text/plain" });
|
|
382
|
+
response.end("Not found");
|
|
383
|
+
return;
|
|
384
|
+
}
|
|
385
|
+
const code = reqUrl.searchParams.get("code");
|
|
386
|
+
const state = reqUrl.searchParams.get("state");
|
|
387
|
+
if (!state || !timingSafeEqualState(state, opts.expectedState)) {
|
|
388
|
+
trace("callback: state mismatch");
|
|
389
|
+
response.writeHead(400, { "Content-Type": "text/plain" });
|
|
390
|
+
response.end("State mismatch");
|
|
391
|
+
settle(() => {
|
|
392
|
+
clearTimeout(timer);
|
|
393
|
+
server.close(
|
|
394
|
+
() => rej(new ValidationError("Authorization callback failed a security check."))
|
|
395
|
+
);
|
|
396
|
+
});
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
if (!code || code.length === 0) {
|
|
400
|
+
trace("callback: missing code");
|
|
401
|
+
response.writeHead(400, { "Content-Type": "text/plain" });
|
|
402
|
+
response.end("Missing code");
|
|
403
|
+
settle(() => {
|
|
404
|
+
clearTimeout(timer);
|
|
405
|
+
server.close(
|
|
406
|
+
() => rej(new ValidationError("Authorization callback did not return a code."))
|
|
407
|
+
);
|
|
408
|
+
});
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
response.writeHead(200, { "Content-Type": "text/html" });
|
|
412
|
+
response.end(
|
|
413
|
+
"<html><body><h1>Signed in! You can close this tab.</h1></body></html>"
|
|
414
|
+
);
|
|
415
|
+
trace(`callback: received on port ${port} (state ok)`);
|
|
416
|
+
settle(() => {
|
|
417
|
+
clearTimeout(timer);
|
|
418
|
+
server.close(() => res({ code, redirectUri }));
|
|
419
|
+
});
|
|
420
|
+
});
|
|
421
|
+
const timer = setTimeout(() => {
|
|
422
|
+
trace(`callback: timeout fired after ${timeoutMs}ms`);
|
|
423
|
+
settle(() => {
|
|
424
|
+
server.close(
|
|
425
|
+
() => rej(
|
|
426
|
+
new NotLoggedInError(
|
|
427
|
+
"Browser flow timed out. Run 'ratio auth login --manual' to complete without a browser."
|
|
428
|
+
)
|
|
429
|
+
)
|
|
430
|
+
);
|
|
431
|
+
});
|
|
432
|
+
}, timeoutMs);
|
|
433
|
+
if (typeof timer.unref === "function") {
|
|
434
|
+
timer.unref();
|
|
435
|
+
}
|
|
436
|
+
if (opts.signal) {
|
|
437
|
+
opts.signal.addEventListener("abort", () => {
|
|
438
|
+
trace("callback: cancelled");
|
|
439
|
+
clearTimeout(timer);
|
|
440
|
+
settle(() => {
|
|
441
|
+
server.close(
|
|
442
|
+
() => rej(
|
|
443
|
+
new NotLoggedInError(
|
|
444
|
+
"Browser flow was cancelled. Run 'ratio auth login --manual' to complete without a browser."
|
|
445
|
+
)
|
|
446
|
+
)
|
|
447
|
+
);
|
|
448
|
+
});
|
|
449
|
+
});
|
|
450
|
+
}
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
});
|
|
454
|
+
});
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
// src/lib/auth/browser.ts
|
|
459
|
+
function defaultBrowserOpener() {
|
|
460
|
+
return {
|
|
461
|
+
async open(url) {
|
|
462
|
+
let openFn;
|
|
463
|
+
try {
|
|
464
|
+
const mod = await import("open");
|
|
465
|
+
openFn = mod.default;
|
|
466
|
+
} catch {
|
|
467
|
+
throw new NotLoggedInError(
|
|
468
|
+
"Could not open a browser. Run 'ratio auth login --manual' to complete without a browser."
|
|
469
|
+
);
|
|
470
|
+
}
|
|
471
|
+
try {
|
|
472
|
+
await openFn(url);
|
|
473
|
+
} catch {
|
|
474
|
+
throw new NotLoggedInError(
|
|
475
|
+
"Could not open a browser. Run 'ratio auth login --manual' to complete without a browser."
|
|
476
|
+
);
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
};
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
// src/lib/auth/manual-prompt.ts
|
|
483
|
+
import { createInterface } from "readline/promises";
|
|
484
|
+
import { stdin as input, stdout as output } from "process";
|
|
485
|
+
function defaultStdinPrompt() {
|
|
486
|
+
return {
|
|
487
|
+
async askForCode(prompt) {
|
|
488
|
+
const rl = createInterface({ input, output });
|
|
489
|
+
try {
|
|
490
|
+
const answer = await rl.question(prompt);
|
|
491
|
+
return answer.trim();
|
|
492
|
+
} finally {
|
|
493
|
+
rl.close();
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
};
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
// src/lib/auth/identity.ts
|
|
500
|
+
function renderIdentity(identity) {
|
|
501
|
+
const scopePart = identity.scopes.length > 0 ? ` scopes=[${identity.scopes.join(", ")}]` : "";
|
|
502
|
+
const appPart = identity.appName ? ` app="${identity.appName}"` : "";
|
|
503
|
+
return `clientId=${identity.clientId} merchantId=${identity.merchantId}${appPart}${scopePart}`;
|
|
504
|
+
}
|
|
505
|
+
export {
|
|
506
|
+
DEFAULT_SERVER_URL,
|
|
507
|
+
HttpTokenRefresher,
|
|
508
|
+
RATIO_CLI_CLIENT_ID,
|
|
509
|
+
RATIO_CLI_MERCHANT_ID,
|
|
510
|
+
awaitLoopbackCallback,
|
|
511
|
+
buildBrowserAuthorizeUrl,
|
|
512
|
+
buildLoopbackRedirectUri,
|
|
513
|
+
buildManualAuthorizeUrl,
|
|
514
|
+
computeS256Challenge,
|
|
515
|
+
createVerboseTracer,
|
|
516
|
+
defaultBrowserOpener,
|
|
517
|
+
defaultStdinPrompt,
|
|
518
|
+
exchangeCodeForTokens,
|
|
519
|
+
generatePkcePair,
|
|
520
|
+
generateState,
|
|
521
|
+
noopTracer,
|
|
522
|
+
renderIdentity,
|
|
523
|
+
resolveServerUrl,
|
|
524
|
+
startLoopbackSession,
|
|
525
|
+
timingSafeEqualState
|
|
526
|
+
};
|
|
527
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/lib/auth/pkce.ts","../../../src/lib/auth/state.ts","../../../src/lib/auth/config.ts","../../../src/lib/auth/authorize-url.ts","../../../src/lib/auth/authorize-code-exchange.ts","../../../src/lib/errors.ts","../../../src/lib/auth/verbose-trace.ts","../../../src/lib/auth/http-refresher.ts","../../../src/lib/auth/loopback-server.ts","../../../src/lib/auth/browser.ts","../../../src/lib/auth/manual-prompt.ts","../../../src/lib/auth/identity.ts"],"sourcesContent":["/**\n * PKCE (RFC 7636) helpers — S256 code challenge only.\n *\n * The \"plain\" method is rejected by the backend DTO validator and is\n * never generated here. All operations are synchronous and pure.\n */\n\nimport crypto from 'node:crypto';\n\nexport interface PkcePair {\n readonly codeVerifier: string; // 43-128 chars, unreserved-only (RFC 7636 §4.1)\n readonly codeChallenge: string; // base64url(SHA-256(codeVerifier))\n readonly codeChallengeMethod: 'S256';\n}\n\n/**\n * Compute the S256 code challenge for a given code verifier.\n * BASE64URL-ENCODE(SHA256(ASCII(code_verifier))) without padding.\n * Algorithm matches the backend pkce utility byte-for-byte.\n */\nexport function computeS256Challenge(codeVerifier: string): string {\n return crypto.createHash('sha256').update(codeVerifier, 'ascii').digest('base64url');\n}\n\n/**\n * Generate a fresh PKCE pair for one authorization request.\n * codeVerifier is 96 random base64url bytes → 128 chars (within RFC 7636 43-128 range).\n */\nexport function generatePkcePair(): PkcePair {\n const codeVerifier = crypto.randomBytes(96).toString('base64url');\n const codeChallenge = computeS256Challenge(codeVerifier);\n return { codeVerifier, codeChallenge, codeChallengeMethod: 'S256' };\n}\n","/**\n * OAuth state parameter helpers.\n *\n * State is generated once per authorization request and must be compared\n * in constant time to prevent timing-oracle CSRF attacks.\n */\n\nimport crypto from 'node:crypto';\n\n/**\n * Generate a fresh state value: 32 random bytes encoded as base64url.\n * 32 bytes = 256 bits of entropy, well above the 128-bit minimum.\n */\nexport function generateState(): string {\n return crypto.randomBytes(32).toString('base64url');\n}\n\n/**\n * Constant-time comparison of two state strings.\n * Returns true iff a === b without leaking timing information.\n * Both strings are converted to UTF-8 Buffers before comparison;\n * length-mismatch is handled without a fast-fail branch.\n */\nexport function timingSafeEqualState(a: string, b: string): boolean {\n const aBuf = Buffer.from(a, 'utf8');\n const bBuf = Buffer.from(b, 'utf8');\n if (aBuf.length !== bBuf.length) {\n // Perform a dummy comparison to avoid timing-observable fast-path.\n crypto.timingSafeEqual(aBuf, aBuf);\n return false;\n }\n return crypto.timingSafeEqual(aBuf, bBuf);\n}\n","/**\n * Server-URL resolution for the Ratio CLI auth flow.\n *\n * Resolution order (highest priority first):\n * 1. RATIO_SERVER_URL environment variable\n * 2. Credentials.server from the stored credential file (passed in as opts.credentials.server)\n * 3. The compiled-in default: https://gkx.ratio.win\n *\n * The default is the ONLY place this URL appears in non-config source files.\n * All other auth-library modules call resolveServerUrl() — never hardcode.\n *\n * A-28: the merchantId constant lives here so it appears in exactly ONE\n * production file and is grep-able.\n */\n\n/** Compiled-in default server URL. */\nexport const DEFAULT_SERVER_URL = 'https://gkx.ratio.win';\n\n/**\n * Synthetic merchantId sent in the authorize URL.\n * A-28 adjudication: backend auto-creates missing merchants via\n * ensureMerchantExists(); 'ratio-cli-dev' is the designated synthetic value.\n * Appears in exactly ONE production file (this one).\n */\nexport const RATIO_CLI_MERCHANT_ID = 'ratio-cli-dev';\n\n/** The fixed clientId for the ratio-cli public OAuth client. */\nexport const RATIO_CLI_CLIENT_ID = 'ratio-cli' as const;\n\nexport interface ServerConfig {\n readonly url: string;\n}\n\nexport interface ResolveServerUrlOptions {\n readonly credentials?: { readonly server?: string };\n readonly env?: Readonly<Record<string, string | undefined>>;\n}\n\n/**\n * Resolve the backend server URL using the three-level precedence chain.\n * Injectable for tests: pass `env` to avoid reading `process.env` directly.\n */\nexport function resolveServerUrl(opts?: ResolveServerUrlOptions): string {\n const env = opts?.env ?? process.env;\n if (typeof env['RATIO_SERVER_URL'] === 'string' && env['RATIO_SERVER_URL'].length > 0) {\n return env['RATIO_SERVER_URL'];\n }\n if (typeof opts?.credentials?.server === 'string' && opts.credentials.server.length > 0) {\n return opts.credentials.server;\n }\n return DEFAULT_SERVER_URL;\n}\n","/**\n * Pure URL builders for the OAuth authorization step.\n *\n * The browser flow uses a redirectUri (loopback callback) so the portal\n * redirects back to the CLI. The manual flow uses ?display_code=1 so\n * the portal renders a copyable code for the user to paste.\n *\n * Zero network I/O in this module — pure string construction only.\n */\n\nimport { RATIO_CLI_CLIENT_ID, RATIO_CLI_MERCHANT_ID } from './config.js';\n\nexport interface AuthorizeUrlBrowserOptions {\n readonly serverUrl: string;\n readonly clientId: typeof RATIO_CLI_CLIENT_ID;\n readonly codeChallenge: string;\n readonly state: string;\n readonly redirectUri: string; // http://127.0.0.1:<port>/callback\n readonly scopes?: readonly string[];\n readonly merchantId?: string;\n}\n\nexport interface AuthorizeUrlManualOptions {\n readonly serverUrl: string;\n readonly clientId: typeof RATIO_CLI_CLIENT_ID;\n readonly codeChallenge: string;\n readonly state: string;\n readonly scopes?: readonly string[];\n readonly merchantId?: string;\n}\n\n/**\n * Build the authorize URL for the browser flow.\n * Includes redirect_uri for the loopback callback; does NOT include display_code.\n */\nexport function buildBrowserAuthorizeUrl(o: AuthorizeUrlBrowserOptions): string {\n const params = new URLSearchParams();\n params.set('client_id', o.clientId);\n params.set('merchant_id', o.merchantId ?? RATIO_CLI_MERCHANT_ID);\n params.set('code_challenge', o.codeChallenge);\n params.set('code_challenge_method', 'S256');\n params.set('state', o.state);\n params.set('redirect_uri', o.redirectUri);\n if (o.scopes && o.scopes.length > 0) {\n params.set('scope', o.scopes.join(','));\n }\n return `${o.serverUrl}/oauth/authorize?${params.toString()}`;\n}\n\n/**\n * Build the authorize URL for the manual copy-paste flow.\n * Includes display_code=1 so the portal renders a copyable code.\n * Does NOT include redirect_uri.\n */\nexport function buildManualAuthorizeUrl(o: AuthorizeUrlManualOptions): string {\n const params = new URLSearchParams();\n params.set('client_id', o.clientId);\n params.set('merchant_id', o.merchantId ?? RATIO_CLI_MERCHANT_ID);\n params.set('code_challenge', o.codeChallenge);\n params.set('code_challenge_method', 'S256');\n params.set('state', o.state);\n params.set('display_code', '1');\n if (o.scopes && o.scopes.length > 0) {\n params.set('scope', o.scopes.join(','));\n }\n return `${o.serverUrl}/oauth/authorize?${params.toString()}`;\n}\n","/**\n * OAuth authorization-code exchange step.\n *\n * Used by BOTH the browser flow (with redirectUri) and the manual flow\n * (without redirectUri). Returns typed tokens + identity derived from\n * the token response.\n *\n * A-29 adjudication: identity = token-derived {clientId, merchantId, scopes}.\n * The backend token envelope does not expose developerId/email. This is a\n * known ADR contradiction resolved pre-implementation; the schema tolerates\n * absence and additive identity fields can be added when a backend endpoint\n * for developer identity is available.\n *\n * Token response schema is pinned with zod for fast detection of envelope drift.\n * Any schema mismatch throws a static-message ValidationError — the raw body\n * is never included in any error message (secret-leak prevention).\n */\n\nimport { z } from 'zod';\nimport { NetworkError, ValidationError } from '../errors.js';\nimport type { TokenSet } from '../credentials/index.js';\nimport { RATIO_CLI_CLIENT_ID } from './config.js';\nimport { noopTracer } from './verbose-trace.js';\nimport type { VerboseTracer } from './verbose-trace.js';\n\n/** Token response envelope from POST /oauth/token (authorization_code grant). */\nconst TokenResponseSchema = z.object({\n access_token: z.string().min(1),\n refresh_token: z.string().min(1),\n expires_in: z.number().int().positive(),\n token_type: z.string().optional(),\n scope: z.string().optional(),\n merchant_id: z.string().optional(),\n});\n\n/** Token-derived identity (A-29 shape). */\nexport interface TokenDerivedIdentity {\n readonly clientId: string;\n readonly merchantId: string;\n readonly scopes: readonly string[];\n}\n\nexport interface CodeExchangeInput {\n readonly serverUrl: string;\n readonly code: string;\n readonly codeVerifier: string;\n readonly redirectUri?: string; // undefined for --manual\n readonly clientId: typeof RATIO_CLI_CLIENT_ID;\n readonly fetchImpl?: typeof fetch; // injectable for tests\n /** Verbose diagnostic sink — never receives token/code/verifier/state. */\n readonly trace?: VerboseTracer;\n}\n\nexport interface CodeExchangeOutput {\n readonly tokens: TokenSet;\n readonly identity: TokenDerivedIdentity;\n}\n\n/**\n * Exchange an authorization code for tokens.\n * POSTs to /oauth/token with grant_type=authorization_code.\n * Never logs or includes token values in error messages.\n */\nexport function exchangeCodeForTokens(i: CodeExchangeInput): Promise<CodeExchangeOutput> {\n return _exchangeCodeForTokensImpl(i);\n}\n\nasync function _exchangeCodeForTokensImpl(i: CodeExchangeInput): Promise<CodeExchangeOutput> {\n const fetchFn = i.fetchImpl ?? fetch;\n\n const body: Record<string, string> = {\n grant_type: 'authorization_code',\n code: i.code,\n clientId: i.clientId,\n codeVerifier: i.codeVerifier,\n };\n if (i.redirectUri !== undefined) {\n body['redirectUri'] = i.redirectUri;\n }\n\n const trace = i.trace ?? noopTracer;\n const startedAt = Date.now();\n\n let response: Response;\n try {\n response = await fetchFn(`${i.serverUrl}/oauth/token`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n });\n } catch {\n trace(`POST /oauth/token → network error (${Date.now() - startedAt}ms)`);\n throw new NetworkError('Failed to reach the Ratio server during token exchange.');\n }\n\n trace(`POST /oauth/token → ${response.status} (${Date.now() - startedAt}ms)`);\n\n if (response.status >= 400 && response.status < 500) {\n throw new ValidationError(\n \"The authorization code was rejected. Run 'ratio auth login' again.\",\n );\n }\n\n if (response.status >= 500 || !response.ok) {\n throw new NetworkError('The Ratio server returned an error during token exchange.');\n }\n\n let raw: unknown;\n try {\n raw = await response.json();\n } catch {\n throw new ValidationError('Token response was not valid JSON.');\n }\n\n const parsed = TokenResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new ValidationError('Token response shape was unexpected. Run ratio auth login again.');\n }\n\n const data = parsed.data;\n const expiresAt = new Date(Date.now() + data.expires_in * 1000).toISOString();\n\n const tokens: TokenSet = {\n accessToken: data.access_token,\n refreshToken: data.refresh_token,\n expiresAt,\n };\n\n const scopeStr = data.scope ?? '';\n const scopes = scopeStr.length > 0 ? scopeStr.split(/[\\s,]+/).filter(Boolean) : [];\n\n const identity: TokenDerivedIdentity = {\n clientId: i.clientId,\n merchantId: data.merchant_id ?? 'ratio-cli-dev',\n scopes,\n };\n\n return { tokens, identity };\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 * Minimal verbose diagnostic seam for the auth flow.\n *\n * When `--verbose` is on, the auth HTTP/loopback boundaries emit ONE line\n * per boundary crossing (method, path, status, timing, flow events) so a\n * failing login/refresh can be diagnosed from the CLI transcript alone.\n *\n * Safety contract (enforced by tests):\n * - Lines go to STDERR only — never stdout — so `--json` consumers and\n * shell pipelines are never corrupted.\n * - NO secret material is ever passed to a tracer: no access/refresh\n * token, no authorization code, no code_verifier, no state value.\n * Only method, path, HTTP status, port numbers, and durations.\n */\n\n/** A tracer receives one pre-formatted diagnostic message per event. */\nexport type VerboseTracer = (msg: string) => void;\n\n/** Shared no-op used when `--verbose` is off (default everywhere). */\nexport const noopTracer: VerboseTracer = () => {};\n\n/**\n * Build a tracer. Returns the shared no-op unless `verbose` is true.\n * Output sink is injectable for tests; defaults to process.stderr.\n */\nexport function createVerboseTracer(\n verbose: boolean,\n write: (line: string) => void = (line) => {\n process.stderr.write(line);\n },\n): VerboseTracer {\n if (!verbose) return noopTracer;\n return (msg: string) => {\n write(`[verbose] ${msg}\\n`);\n };\n}\n","/**\n * HTTP implementation of the TokenRefresher interface.\n *\n * POSTs to /oauth/token with grant_type=refresh_token.\n * Maps 4xx → TokenExpiredError, 5xx/network → NetworkError.\n * Never logs or echoes the token value in any error message.\n */\n\nimport { z } from 'zod';\nimport { NetworkError, TokenExpiredError } from '../errors.js';\nimport type { TokenRefresher, TokenSet } from '../credentials/index.js';\nimport { RATIO_CLI_CLIENT_ID } from './config.js';\nimport { noopTracer } from './verbose-trace.js';\nimport type { VerboseTracer } from './verbose-trace.js';\n\n/** Refresh response envelope — subset of the full token response. */\nconst RefreshResponseSchema = z.object({\n access_token: z.string().min(1),\n refresh_token: z.string().min(1),\n expires_in: z.number().int().positive(),\n});\n\nexport interface HttpTokenRefresherOptions {\n readonly serverUrl: string;\n readonly clientId: typeof RATIO_CLI_CLIENT_ID;\n readonly fetchImpl?: typeof fetch; // injectable for tests\n /** Verbose diagnostic sink — never receives the refresh token value. */\n readonly trace?: VerboseTracer;\n}\n\nexport class HttpTokenRefresher implements TokenRefresher {\n private readonly serverUrl: string;\n private readonly clientId: string;\n private readonly fetchImpl: typeof fetch;\n private readonly trace: VerboseTracer;\n\n constructor(opts: HttpTokenRefresherOptions) {\n this.serverUrl = opts.serverUrl;\n this.clientId = opts.clientId;\n this.fetchImpl = opts.fetchImpl ?? fetch;\n this.trace = opts.trace ?? noopTracer;\n }\n\n async refresh(refreshToken: string): Promise<TokenSet> {\n const body = {\n grant_type: 'refresh_token',\n refresh_token: refreshToken,\n clientId: this.clientId,\n };\n\n this.trace('refresh: fired (access token expired or expiring)');\n const startedAt = Date.now();\n\n let response: Response;\n try {\n response = await this.fetchImpl(`${this.serverUrl}/oauth/token`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n });\n } catch {\n this.trace(`POST /oauth/token → network error (${Date.now() - startedAt}ms)`);\n throw new NetworkError('Failed to reach the Ratio server during token refresh.');\n }\n\n this.trace(`POST /oauth/token → ${response.status} (${Date.now() - startedAt}ms)`);\n\n if (response.status >= 400 && response.status < 500) {\n throw new TokenExpiredError(\n 'Your session has expired and could not be refreshed.',\n );\n }\n\n if (response.status >= 500 || !response.ok) {\n throw new NetworkError('The Ratio server returned an error during token refresh.');\n }\n\n let raw: unknown;\n try {\n raw = await response.json();\n } catch {\n throw new NetworkError('Token refresh response was not valid JSON.');\n }\n\n const parsed = RefreshResponseSchema.safeParse(raw);\n if (!parsed.success) {\n throw new TokenExpiredError(\n 'Your session has expired and could not be refreshed.',\n );\n }\n\n const data = parsed.data;\n const expiresAt = new Date(Date.now() + data.expires_in * 1000).toISOString();\n\n return {\n accessToken: data.access_token,\n refreshToken: data.refresh_token,\n expiresAt,\n };\n }\n}\n","/**\n * Ephemeral loopback HTTP server for the OAuth browser callback.\n *\n * Binds 127.0.0.1:0 (OS-assigned port). Awaits ONE GET /callback\n * request with ?code=...&state=... query parameters, verifies the state\n * via timingSafeEqualState, closes the server, and resolves.\n *\n * Security properties:\n * - Binds 127.0.0.1 only — never 0.0.0.0 or ::\n * - Port is OS-assigned (listen(0)) — never hardcoded\n * - State compared via timingSafeEqual — no fast-fail timing side channel\n * - Server closes on success, timeout, or state mismatch — no port leak\n * - Non-callback paths receive a 404 response\n */\n\nimport http from 'node:http';\nimport { NotLoggedInError, ValidationError } from '../errors.js';\nimport { timingSafeEqualState } from './state.js';\nimport { noopTracer } from './verbose-trace.js';\nimport type { VerboseTracer } from './verbose-trace.js';\n\nexport interface LoopbackAwaitOptions {\n readonly expectedState: string;\n readonly timeoutMs: number; // default 30_000 for prod, injectable for tests\n readonly signal?: AbortSignal;\n /** Verbose diagnostic sink — never receives code/state values. */\n readonly trace?: VerboseTracer;\n}\n\nexport interface LoopbackAwaitResult {\n readonly code: string;\n readonly redirectUri: string; // http://127.0.0.1:<actualPort>/callback\n}\n\n/**\n * Binds 127.0.0.1:0, awaits ONE GET /callback?code=...&state=..., verifies\n * state via timingSafeEqual against expectedState, closes the server cleanly,\n * resolves with { code, redirectUri }. On timeout or state mismatch or\n * non-callback request path, rejects with the appropriate typed error.\n */\nexport function awaitLoopbackCallback(o: LoopbackAwaitOptions): Promise<LoopbackAwaitResult> {\n const trace = o.trace ?? noopTracer;\n return new Promise((resolve, reject) => {\n let settled = false;\n\n function settle(fn: () => void): void {\n if (settled) return;\n settled = true;\n server.close(() => fn());\n }\n\n const server = http.createServer((req, res) => {\n const reqUrl = new URL(req.url ?? '/', `http://127.0.0.1`);\n\n if (reqUrl.pathname !== '/callback') {\n res.writeHead(404, { 'Content-Type': 'text/plain' });\n res.end('Not found');\n return;\n }\n\n const code = reqUrl.searchParams.get('code');\n const state = reqUrl.searchParams.get('state');\n\n if (!state || !timingSafeEqualState(state, o.expectedState)) {\n trace('callback: state mismatch');\n res.writeHead(400, { 'Content-Type': 'text/plain' });\n res.end('State mismatch');\n settle(() =>\n reject(\n new ValidationError('Authorization callback failed a security check.'),\n ),\n );\n return;\n }\n\n if (!code || code.length === 0) {\n trace('callback: missing code');\n res.writeHead(400, { 'Content-Type': 'text/plain' });\n res.end('Missing code');\n settle(() =>\n reject(\n new ValidationError('Authorization callback did not return a code.'),\n ),\n );\n return;\n }\n\n res.writeHead(200, { 'Content-Type': 'text/html' });\n res.end('<html><body><h1>Signed in! You can close this tab.</h1></body></html>');\n\n const addr = server.address();\n const port = typeof addr === 'object' && addr !== null ? addr.port : 0;\n const redirectUri = `http://127.0.0.1:${port}/callback`;\n\n trace(`callback: received on port ${port} (state ok)`);\n settle(() => resolve({ code, redirectUri }));\n });\n\n server.on('error', (err) => {\n settle(() => reject(err));\n });\n\n server.listen(0, '127.0.0.1', () => {\n const boundAddr = server.address();\n const boundPort =\n typeof boundAddr === 'object' && boundAddr !== null ? boundAddr.port : 0;\n trace(`loopback: bound 127.0.0.1:${boundPort}`);\n\n const timer = setTimeout(() => {\n trace(`callback: timeout fired after ${o.timeoutMs}ms`);\n settle(() =>\n reject(\n new NotLoggedInError(\n \"Browser flow timed out. Run 'ratio auth login --manual' to complete without a browser.\",\n ),\n ),\n );\n }, o.timeoutMs);\n\n // Allow process to exit if only this timer remains.\n if (typeof timer.unref === 'function') {\n timer.unref();\n }\n\n if (o.signal) {\n o.signal.addEventListener('abort', () => {\n trace('callback: cancelled');\n clearTimeout(timer);\n settle(() =>\n reject(\n new NotLoggedInError(\n \"Browser flow was cancelled. Run 'ratio auth login --manual' to complete without a browser.\",\n ),\n ),\n );\n });\n }\n });\n });\n}\n\n/**\n * Return the loopback callback URI for a given port.\n */\nexport function buildLoopbackRedirectUri(port: number): string {\n return `http://127.0.0.1:${port}/callback`;\n}\n\nexport interface LoopbackSession {\n /** The OS-assigned port the server is bound to. */\n readonly port: number;\n /** The full redirect URI to send in the authorize URL. */\n readonly redirectUri: string;\n /**\n * Await the single callback. Resolves with the code, rejects on timeout\n * or state mismatch. The server is closed when this promise settles.\n */\n awaitCallback(opts: Omit<LoopbackAwaitOptions, 'timeoutMs'> & { timeoutMs?: number }): Promise<LoopbackAwaitResult>;\n}\n\n/**\n * Two-phase API: start the server first (to get the port for the authorize URL),\n * then await the callback after the browser has been opened.\n *\n * Usage:\n * const session = await startLoopbackSession();\n * const url = buildBrowserAuthorizeUrl({ redirectUri: session.redirectUri, ... });\n * await opener.open(url);\n * const { code } = await session.awaitCallback({ expectedState, timeoutMs: 30_000 });\n */\nexport function startLoopbackSession(trace: VerboseTracer = noopTracer): Promise<LoopbackSession> {\n return new Promise((resolve, reject) => {\n let settled = false;\n\n function settle(fn: () => void): void {\n if (settled) return;\n settled = true;\n fn();\n }\n\n const server = http.createServer();\n server.on('error', reject);\n server.listen(0, '127.0.0.1', () => {\n const addr = server.address();\n const port = typeof addr === 'object' && addr !== null ? addr.port : 0;\n const redirectUri = buildLoopbackRedirectUri(port);\n\n trace(`loopback: bound 127.0.0.1:${port}`);\n\n resolve({\n port,\n redirectUri,\n awaitCallback(\n opts: Omit<LoopbackAwaitOptions, 'timeoutMs'> & { timeoutMs?: number },\n ): Promise<LoopbackAwaitResult> {\n const timeoutMs = opts.timeoutMs ?? 30_000;\n\n return new Promise((res, rej) => {\n server.on('request', (req, response) => {\n const reqUrl = new URL(req.url ?? '/', `http://127.0.0.1`);\n\n if (reqUrl.pathname !== '/callback') {\n response.writeHead(404, { 'Content-Type': 'text/plain' });\n response.end('Not found');\n return;\n }\n\n const code = reqUrl.searchParams.get('code');\n const state = reqUrl.searchParams.get('state');\n\n if (!state || !timingSafeEqualState(state, opts.expectedState)) {\n trace('callback: state mismatch');\n response.writeHead(400, { 'Content-Type': 'text/plain' });\n response.end('State mismatch');\n settle(() => {\n clearTimeout(timer);\n server.close(() =>\n rej(new ValidationError('Authorization callback failed a security check.')),\n );\n });\n return;\n }\n\n if (!code || code.length === 0) {\n trace('callback: missing code');\n response.writeHead(400, { 'Content-Type': 'text/plain' });\n response.end('Missing code');\n settle(() => {\n clearTimeout(timer);\n server.close(() =>\n rej(new ValidationError('Authorization callback did not return a code.')),\n );\n });\n return;\n }\n\n response.writeHead(200, { 'Content-Type': 'text/html' });\n response.end(\n '<html><body><h1>Signed in! You can close this tab.</h1></body></html>',\n );\n\n trace(`callback: received on port ${port} (state ok)`);\n settle(() => {\n clearTimeout(timer);\n server.close(() => res({ code, redirectUri }));\n });\n });\n\n const timer = setTimeout(() => {\n trace(`callback: timeout fired after ${timeoutMs}ms`);\n settle(() => {\n server.close(() =>\n rej(\n new NotLoggedInError(\n \"Browser flow timed out. Run 'ratio auth login --manual' to complete without a browser.\",\n ),\n ),\n );\n });\n }, timeoutMs);\n\n if (typeof timer.unref === 'function') {\n timer.unref();\n }\n\n if (opts.signal) {\n opts.signal.addEventListener('abort', () => {\n trace('callback: cancelled');\n clearTimeout(timer);\n settle(() => {\n server.close(() =>\n rej(\n new NotLoggedInError(\n \"Browser flow was cancelled. Run 'ratio auth login --manual' to complete without a browser.\",\n ),\n ),\n );\n });\n });\n }\n });\n },\n });\n });\n });\n}\n","/**\n * Browser-launch wrapper for the OAuth browser flow.\n *\n * This is the SOLE file that imports from the 'open' npm package.\n * Injectable via the BrowserOpener interface for unit tests.\n */\n\nimport { NotLoggedInError } from '../errors.js';\n\nexport interface BrowserOpener {\n open(url: string): Promise<void>;\n}\n\n/**\n * Create the default browser opener backed by the 'open' package.\n * Throws NotLoggedInError on failure with the --manual fallback hint.\n */\nexport function defaultBrowserOpener(): BrowserOpener {\n return {\n async open(url: string): Promise<void> {\n // Dynamic import is used so the module is loadable in test environments\n // that do not have a display (CI / SSH). The real 'open' call only fires\n // in production use when this opener is not replaced by a test double.\n let openFn: (url: string) => Promise<unknown>;\n try {\n const mod = await import('open');\n openFn = mod.default as (url: string) => Promise<unknown>;\n } catch {\n throw new NotLoggedInError(\n \"Could not open a browser. Run 'ratio auth login --manual' to complete without a browser.\",\n );\n }\n try {\n await openFn(url);\n } catch {\n throw new NotLoggedInError(\n \"Could not open a browser. Run 'ratio auth login --manual' to complete without a browser.\",\n );\n }\n },\n };\n}\n","/**\n * Stdin prompt for the --manual copy-paste OAuth flow.\n *\n * Uses node:readline/promises so it is awaitable and testable with\n * an injectable interface. The defaultStdinPrompt() function is the\n * production implementation; tests inject a fake.\n */\n\nimport { createInterface } from 'node:readline/promises';\nimport { stdin as input, stdout as output } from 'node:process';\n\nexport interface StdinPrompt {\n askForCode(prompt: string): Promise<string>;\n}\n\n/**\n * Create the default stdin prompter backed by node:readline/promises.\n * Trims whitespace from the pasted code.\n */\nexport function defaultStdinPrompt(): StdinPrompt {\n return {\n async askForCode(prompt: string): Promise<string> {\n const rl = createInterface({ input, output });\n try {\n const answer = await rl.question(prompt);\n return answer.trim();\n } finally {\n rl.close();\n }\n },\n };\n}\n","/**\n * Identity helpers for the auth flow.\n *\n * A-29 adjudication: the backend token envelope does not expose developerId/email.\n * Identity is therefore token-derived: {clientId, merchantId, scopes}.\n *\n * This file re-exports the TokenDerivedIdentity type from authorize-code-exchange\n * so consumers have a single import point. It is a null-object for the POST-token\n * identity fetch originally envisioned (no GET /developer/me endpoint\n * exists yet). The appName optional field is added if GET /oauth/app-info returns it.\n */\n\nexport type { TokenDerivedIdentity } from './authorize-code-exchange.js';\n\n/** Rendered display string for the identity in whoami / login success. */\nexport function renderIdentity(identity: {\n clientId: string;\n merchantId: string;\n scopes: readonly string[];\n appName?: string;\n}): string {\n const scopePart = identity.scopes.length > 0\n ? ` scopes=[${identity.scopes.join(', ')}]`\n : '';\n const appPart = identity.appName ? ` app=\"${identity.appName}\"` : '';\n return `clientId=${identity.clientId} merchantId=${identity.merchantId}${appPart}${scopePart}`;\n}\n"],"mappings":";AAOA,OAAO,YAAY;AAaZ,SAAS,qBAAqB,cAA8B;AACjE,SAAO,OAAO,WAAW,QAAQ,EAAE,OAAO,cAAc,OAAO,EAAE,OAAO,WAAW;AACrF;AAMO,SAAS,mBAA6B;AAC3C,QAAM,eAAe,OAAO,YAAY,EAAE,EAAE,SAAS,WAAW;AAChE,QAAM,gBAAgB,qBAAqB,YAAY;AACvD,SAAO,EAAE,cAAc,eAAe,qBAAqB,OAAO;AACpE;;;ACzBA,OAAOA,aAAY;AAMZ,SAAS,gBAAwB;AACtC,SAAOA,QAAO,YAAY,EAAE,EAAE,SAAS,WAAW;AACpD;AAQO,SAAS,qBAAqB,GAAW,GAAoB;AAClE,QAAM,OAAO,OA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