@tulcn/lxz 0.0.0-stage → 0.3.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 +63 -2
- package/dist/application.d.ts +2 -0
- package/dist/application.js +17 -0
- package/dist/auth/client.d.ts +5 -0
- package/dist/auth/client.js +14 -0
- package/dist/auth/gateway.d.ts +1 -0
- package/dist/auth/gateway.js +10 -0
- package/dist/auth/host.d.ts +2 -0
- package/dist/auth/host.js +16 -0
- package/dist/auth/identity.d.ts +45 -0
- package/dist/auth/identity.js +106 -0
- package/dist/auth/index.d.ts +10 -0
- package/dist/auth/index.js +13 -0
- package/dist/auth/inspection.d.ts +14 -0
- package/dist/auth/inspection.js +22 -0
- package/dist/auth/modules.d.ts +12 -0
- package/dist/auth/modules.js +25 -0
- package/dist/auth/platform.d.ts +26 -0
- package/dist/auth/platform.js +102 -0
- package/dist/auth/protocol.d.ts +17 -0
- package/dist/auth/protocol.js +1 -0
- package/dist/auth/provider.d.ts +40 -0
- package/dist/auth/provider.js +174 -0
- package/dist/auth/response.d.ts +2 -0
- package/dist/auth/response.js +17 -0
- package/dist/auth/service.d.ts +5 -0
- package/dist/auth/service.js +72 -0
- package/dist/auth/store.d.ts +26 -0
- package/dist/auth/store.js +171 -0
- package/dist/cli/browser.d.ts +1 -0
- package/dist/cli/browser.js +11 -0
- package/dist/cli/contracts.d.ts +85 -0
- package/dist/cli/contracts.js +51 -0
- package/dist/cli/deployment.d.ts +13 -0
- package/dist/cli/deployment.js +35 -0
- package/dist/cli/device-login.d.ts +29 -0
- package/dist/cli/device-login.js +87 -0
- package/dist/cli/environment.d.ts +9 -0
- package/dist/cli/environment.js +19 -0
- package/dist/cli/errors.d.ts +30 -0
- package/dist/cli/errors.js +22 -0
- package/dist/cli/files.d.ts +6 -0
- package/dist/cli/files.js +71 -0
- package/dist/cli/http.d.ts +6 -0
- package/dist/cli/http.js +38 -0
- package/dist/cli/identity-commands.d.ts +3 -0
- package/dist/cli/identity-commands.js +56 -0
- package/dist/cli/index.d.ts +13 -0
- package/dist/cli/index.js +13 -0
- package/dist/cli/init.d.ts +205 -0
- package/dist/cli/init.js +77 -0
- package/dist/cli/modules.d.ts +6 -0
- package/dist/cli/modules.js +18 -0
- package/dist/cli/output.d.ts +2 -0
- package/dist/cli/output.js +35 -0
- package/dist/cli/prompts.d.ts +34 -0
- package/dist/cli/prompts.js +58 -0
- package/dist/cli/runtime.d.ts +2 -0
- package/dist/cli/runtime.js +137 -0
- package/dist/cli/schemas.d.ts +187 -0
- package/dist/cli/schemas.js +46 -0
- package/dist/doctor.d.ts +2 -0
- package/dist/doctor.js +72 -0
- package/dist/internal/client.d.ts +6 -0
- package/dist/internal/client.js +51 -0
- package/dist/internal/host.d.ts +1 -0
- package/dist/internal/host.js +50 -0
- package/dist/internal/protocol.d.ts +27 -0
- package/dist/internal/protocol.js +1 -0
- package/dist/main.d.ts +2 -0
- package/dist/main.js +12 -0
- package/dist/skills/agents.d.ts +7 -0
- package/dist/skills/agents.js +11 -0
- package/dist/skills/artifacts.d.ts +9 -0
- package/dist/skills/artifacts.js +12 -0
- package/dist/skills/bundle.d.ts +22 -0
- package/dist/skills/bundle.js +77 -0
- package/dist/skills/client.d.ts +5 -0
- package/dist/skills/client.js +9 -0
- package/dist/skills/commands.d.ts +5 -0
- package/dist/skills/commands.js +20 -0
- package/dist/skills/delivery.d.ts +60 -0
- package/dist/skills/delivery.js +89 -0
- package/dist/skills/index.d.ts +7 -0
- package/dist/skills/index.js +7 -0
- package/dist/skills/installer.d.ts +23 -0
- package/dist/skills/installer.js +130 -0
- package/dist/skills/paths.d.ts +2 -0
- package/dist/skills/paths.js +28 -0
- package/package.json +36 -3
- package/scripts/install.mjs +17 -0
- package/skills/SKILL.md +38 -0
- package/skills/bundle.json +7 -0
- package/skills/commands.md +440 -0
- package/skills/features.md +12 -0
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
2
|
+
import { platform } from 'node:os';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { CliError, readJson, request, secureUrl } from '../cli/index.js';
|
|
5
|
+
import { openBrowser } from '../cli/browser.js';
|
|
6
|
+
import { authorizationPrompt } from '../cli/device-login.js';
|
|
7
|
+
import { backendError } from './response.js';
|
|
8
|
+
import { FileSessionStore } from './store.js';
|
|
9
|
+
import { deploymentDefaults } from '../cli/deployment.js';
|
|
10
|
+
import { atRootOf, platformExchange, platformSite } from './platform.js';
|
|
11
|
+
function text(data, name) {
|
|
12
|
+
if (typeof data[name] === 'string' && data[name])
|
|
13
|
+
return data[name];
|
|
14
|
+
throw new CliError('UNAVAILABLE', 'The authorization service returned incomplete data.', 'Retry later; if it still fails, contact the authorization service maintainer.', true);
|
|
15
|
+
}
|
|
16
|
+
function tokenClaims(token) {
|
|
17
|
+
try {
|
|
18
|
+
const parts = token.split('.');
|
|
19
|
+
if (parts.length !== 3)
|
|
20
|
+
return {};
|
|
21
|
+
const claims = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));
|
|
22
|
+
return claims && typeof claims === 'object' && !Array.isArray(claims) ? claims : {};
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return {};
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function tokenExpiration(claims, seconds, now) {
|
|
29
|
+
const expiration = typeof claims.exp === 'number' && Number.isFinite(claims.exp) ? claims.exp * 1000 : now + Number(seconds) * 1000;
|
|
30
|
+
if (!Number.isFinite(expiration))
|
|
31
|
+
throw new CliError('UNAVAILABLE', 'The authorization service returned no usable token expiration.', 'Retry later; if it still fails, contact the authorization service maintainer.');
|
|
32
|
+
return expiration;
|
|
33
|
+
}
|
|
34
|
+
function tokens(data) {
|
|
35
|
+
const accessToken = text(data, 'access_token');
|
|
36
|
+
const refreshToken = text(data, 'refresh_token');
|
|
37
|
+
if (data.token_type !== 'Bearer')
|
|
38
|
+
throw new CliError('UNAVAILABLE', 'The authorization service returned invalid credentials.', 'Retry later; if it still fails, contact the authorization service maintainer.');
|
|
39
|
+
// The gateway validates signatures; decoded claims guide local expiry and display.
|
|
40
|
+
const claims = tokenClaims(accessToken);
|
|
41
|
+
const now = Date.now();
|
|
42
|
+
return { ...(typeof claims.sub === 'string' ? { account: claims.sub } : {}), ...(typeof claims.name === 'string' ? { loginName: claims.name } : {}), ...(typeof claims.displayName === 'string' ? { displayName: claims.displayName } : {}), accessToken, refreshToken, accessExpiresAt: tokenExpiration(claims, data.expires_in, now), refreshExpiresAt: tokenExpiration(tokenClaims(refreshToken), data.refresh_token_expires_in, now) };
|
|
43
|
+
}
|
|
44
|
+
export function authConfig(env = process.env, clientId = env.LXZ_AUTH_CLIENT_ID) {
|
|
45
|
+
const issuer = env.LINKWISE_ISSUER ?? deploymentDefaults.LINKWISE_ISSUER;
|
|
46
|
+
if (!issuer || !clientId)
|
|
47
|
+
throw new CliError('CONFIGURATION', 'Authorization service URL or client ID is missing.', 'Set LINKWISE_ISSUER and, if no default client ID is configured, LXZ_AUTH_CLIENT_ID. Obtain these values from the administrator.');
|
|
48
|
+
const allowHttp = /^http:/i.test(issuer.trim());
|
|
49
|
+
const baseUrl = secureUrl(issuer, 'Authorization service URL', { allowHttp }).href.replace(/\/$/, '');
|
|
50
|
+
return { baseUrl, clientId, allowHttp, stateDirectory: env.LXZ_STATE_DIR, site: platformSite(env), deviceEndpoint: `${baseUrl}/oauth2/device_authorization`, tokenEndpoint: `${baseUrl}/oauth2/token`, revokeEndpoint: `${baseUrl}/oauth2/revoke` };
|
|
51
|
+
}
|
|
52
|
+
export class OAuthProvider {
|
|
53
|
+
config;
|
|
54
|
+
browser;
|
|
55
|
+
constructor(config, browser = openBrowser) {
|
|
56
|
+
this.config = config;
|
|
57
|
+
this.browser = browser;
|
|
58
|
+
}
|
|
59
|
+
exchange(endpoint, values, signal, { replay = true, log } = {}) {
|
|
60
|
+
const init = { method: 'POST', headers: { 'x-request-id': randomUUID() }, body: new URLSearchParams({ client_id: this.config.clientId, ...values }), signal };
|
|
61
|
+
return this.config.site ? platformExchange(endpoint, init, { site: this.config.site, replay, log }) : request(endpoint, init).then(response => ({ response, url: endpoint }));
|
|
62
|
+
}
|
|
63
|
+
async send(endpoint, values, signal, options) {
|
|
64
|
+
return (await this.exchange(endpoint, values, signal, options)).response;
|
|
65
|
+
}
|
|
66
|
+
async post(endpoint, values, signal, options) {
|
|
67
|
+
const { response, url } = await this.exchange(endpoint, values, signal, options);
|
|
68
|
+
const data = await readJson(response);
|
|
69
|
+
return { response, data, url };
|
|
70
|
+
}
|
|
71
|
+
async login(context) {
|
|
72
|
+
if (!context.interactive && !context.allowDeviceLogin)
|
|
73
|
+
throw new CliError('AUTH_REQUIRED', 'Authorize this CLI before continuing.', 'Run init in a terminal; for scripts, use init --device-login --timeout-ms 660000 and ask the user to approve in a browser.');
|
|
74
|
+
const os = { win32: 'Windows', darwin: 'macOS', linux: 'Linux' }[platform()] ?? platform();
|
|
75
|
+
const deviceId = await new FileSessionStore(`${this.config.baseUrl}\n${this.config.clientId}`, this.config.stateDirectory).deviceId(context.signal);
|
|
76
|
+
const device = await this.post(this.config.deviceEndpoint, { client_os: os, device_id: deviceId }, context.signal, { log: context.log });
|
|
77
|
+
if (!device.response.ok)
|
|
78
|
+
throw backendError(device.response, device.data);
|
|
79
|
+
// The whole device login stays at the address that issued the device code.
|
|
80
|
+
const tokenEndpoint = this.config.site ? atRootOf(this.config.tokenEndpoint, device.url, this.config.site) : this.config.tokenEndpoint;
|
|
81
|
+
const verification = text(device.data, 'verification_uri_complete');
|
|
82
|
+
secureUrl(verification, 'Authorization approval URL', { allowHttp: this.config.allowHttp, allowQuery: true });
|
|
83
|
+
const code = text(device.data, 'user_code');
|
|
84
|
+
const deviceCode = text(device.data, 'device_code');
|
|
85
|
+
const expires = device.data.expires_in;
|
|
86
|
+
let interval = Number(device.data.interval ?? 5);
|
|
87
|
+
if (!Number.isInteger(expires) || Number(expires) <= 0 || !Number.isInteger(interval) || interval <= 0)
|
|
88
|
+
throw new CliError('UNAVAILABLE', 'The authorization link has an invalid lifetime.', 'Retry later; if it still fails, contact the authorization service maintainer.');
|
|
89
|
+
const deadline = Date.now() + Number(expires) * 1000;
|
|
90
|
+
context.log(`${authorizationPrompt(verification, code)}\nSign in using a browser, check the user code and approve. This command will wait for authorization.`);
|
|
91
|
+
const deviceExpiry = AbortSignal.timeout(Number(expires) * 1000);
|
|
92
|
+
if (context.browser !== false && !await this.browser(verification, AbortSignal.any([context.signal, deviceExpiry])))
|
|
93
|
+
context.log('Could not open a browser. Open the authorization URL above manually.');
|
|
94
|
+
while (Date.now() < deadline) {
|
|
95
|
+
try {
|
|
96
|
+
await delay(Math.min(interval * 1000, Math.max(0, deadline - Date.now())), undefined, { signal: context.signal });
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
context.signal.throwIfAborted();
|
|
100
|
+
throw error;
|
|
101
|
+
}
|
|
102
|
+
if (Date.now() >= deadline)
|
|
103
|
+
break;
|
|
104
|
+
const remaining = AbortSignal.timeout(Math.max(1, deadline - Date.now()));
|
|
105
|
+
let response;
|
|
106
|
+
try {
|
|
107
|
+
response = await request(tokenEndpoint, { method: 'POST', headers: { 'x-request-id': randomUUID() }, body: new URLSearchParams({ client_id: this.config.clientId, device_code: deviceCode, grant_type: 'urn:ietf:params:oauth:grant-type:device_code' }), signal: AbortSignal.any([context.signal, remaining]) });
|
|
108
|
+
}
|
|
109
|
+
catch (error) {
|
|
110
|
+
context.signal.throwIfAborted();
|
|
111
|
+
if (remaining.aborted)
|
|
112
|
+
break;
|
|
113
|
+
if (!(error instanceof CliError) || !['UNAVAILABLE', 'TIMEOUT'].includes(error.code))
|
|
114
|
+
throw error;
|
|
115
|
+
context.log('Cannot reach the authorization service; waiting while the user code remains valid.');
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
if (response.status === 429) {
|
|
119
|
+
await response.body?.cancel();
|
|
120
|
+
interval += 5;
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
if (response.status >= 500) {
|
|
124
|
+
await response.body?.cancel();
|
|
125
|
+
context.log('Authorization service is temporarily unavailable; waiting while the user code remains valid.');
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
let data;
|
|
129
|
+
try {
|
|
130
|
+
data = await readJson(response);
|
|
131
|
+
}
|
|
132
|
+
catch (error) {
|
|
133
|
+
context.signal.throwIfAborted();
|
|
134
|
+
if (remaining.aborted)
|
|
135
|
+
break;
|
|
136
|
+
if (!(error instanceof CliError) || !(error.cause instanceof Error) || !['TypeError', 'AbortError', 'TimeoutError'].includes(error.cause.name))
|
|
137
|
+
throw error;
|
|
138
|
+
context.log('Authorization response was interrupted; waiting while the user code remains valid.');
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
if (data.error === 'authorization_pending')
|
|
142
|
+
continue;
|
|
143
|
+
if (data.error === 'slow_down') {
|
|
144
|
+
interval += 5;
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
if (!response.ok)
|
|
148
|
+
throw backendError(response, data, [deviceCode]);
|
|
149
|
+
return tokens(data);
|
|
150
|
+
}
|
|
151
|
+
throw new CliError('AUTH_EXPIRED', 'The user code has expired.', 'Run init or login again to request a new user code.');
|
|
152
|
+
}
|
|
153
|
+
async refresh(refreshToken, signal) {
|
|
154
|
+
// A delivered refresh rotates the token, and sending the old one again is treated as replay; move only when nothing was sent.
|
|
155
|
+
const { response, data } = await this.post(this.config.tokenEndpoint, { grant_type: 'refresh_token', refresh_token: refreshToken }, signal, { replay: false });
|
|
156
|
+
if (!response.ok)
|
|
157
|
+
throw backendError(response, data, [refreshToken]);
|
|
158
|
+
return tokens(data);
|
|
159
|
+
}
|
|
160
|
+
async revoke(refreshToken, signal) {
|
|
161
|
+
const response = await this.send(this.config.revokeEndpoint, { token: refreshToken, token_type_hint: 'refresh_token' }, AbortSignal.any([signal, AbortSignal.timeout(10000)]));
|
|
162
|
+
if (response.status !== 200) {
|
|
163
|
+
let data = {};
|
|
164
|
+
try {
|
|
165
|
+
data = await readJson(response);
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
168
|
+
signal.throwIfAborted();
|
|
169
|
+
}
|
|
170
|
+
throw backendError(response, data, [refreshToken]);
|
|
171
|
+
}
|
|
172
|
+
await response.body?.cancel();
|
|
173
|
+
}
|
|
174
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { CliError } from '../cli/index.js';
|
|
2
|
+
export function backendError(response, data, secrets = []) {
|
|
3
|
+
const categories = { invalid_client: 'CONFIGURATION', invalid_request: 'INVALID_INPUT', unsupported_grant_type: 'CONFIGURATION', invalid_grant: 'AUTH_EXPIRED', expired_token: 'AUTH_EXPIRED', access_denied: 'ACCESS_DENIED', temporarily_unavailable: 'UNAVAILABLE', server_error: 'UNAVAILABLE' };
|
|
4
|
+
const statuses = { 400: 'INVALID_INPUT', 401: 'AUTH_EXPIRED', 403: 'ACCESS_DENIED', 404: 'INVALID_INPUT', 409: 'CONFLICT', 413: 'INVALID_INPUT', 422: 'INVALID_INPUT' };
|
|
5
|
+
const code = categories[String(data.error)] ?? statuses[response.status] ?? 'UNAVAILABLE';
|
|
6
|
+
const redact = (value) => secrets.filter(Boolean).reduce((result, secret) => result.replaceAll(secret, '[REDACTED]'), value).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '');
|
|
7
|
+
const message = typeof data.error_description === 'string' ? data.error_description : typeof data.msg === 'string' ? data.msg : 'Service request failed.';
|
|
8
|
+
const requestId = response.headers.get('x-request-id');
|
|
9
|
+
const recovery = {
|
|
10
|
+
AUTH_EXPIRED: 'Run this CLI init command and approve authorization.',
|
|
11
|
+
ACCESS_DENIED: 'Ask the administrator to grant access to this CLI or business service.',
|
|
12
|
+
CONFIGURATION: 'Check the service URL and client ID; if correct, ask the administrator to enable this CLI.',
|
|
13
|
+
INVALID_INPUT: 'Check the request input and the service message, then retry.',
|
|
14
|
+
CONFLICT: 'Check the current target and resolve the conflict before submitting again.',
|
|
15
|
+
};
|
|
16
|
+
return new CliError(code, redact(message), recovery[code] ?? 'Check the network and service status, then retry.', response.status >= 500 || response.status === 429, requestId ? { requestId: redact(requestId) } : undefined);
|
|
17
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { IdentityPort } from '../cli/index.js';
|
|
2
|
+
export declare function serviceJson(identity: IdentityPort, input: string | URL, signal: AbortSignal): Promise<Record<string, unknown>>;
|
|
3
|
+
export declare function serviceRequest(identity: IdentityPort, send: (token: string) => Promise<Response>, signal: AbortSignal, { replay }?: {
|
|
4
|
+
replay?: boolean | undefined;
|
|
5
|
+
}): Promise<Response>;
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
3
|
+
import { CliError, readJson, secureUrl } from '../cli/index.js';
|
|
4
|
+
import { backendError } from './response.js';
|
|
5
|
+
import { platformRequest } from './platform.js';
|
|
6
|
+
export async function serviceJson(identity, input, signal) {
|
|
7
|
+
const url = secureUrl(String(input), 'Business service URL', { allowHttp: true, allowQuery: true });
|
|
8
|
+
return readJson(await serviceRequest(identity, token => platformRequest(url, { headers: { authorization: `Bearer ${token}`, 'x-request-id': randomUUID() }, signal }), signal));
|
|
9
|
+
}
|
|
10
|
+
export async function serviceRequest(identity, send, signal, { replay = true } = {}) {
|
|
11
|
+
let credential = await identity.credential(signal);
|
|
12
|
+
const sendWithRetry = async () => {
|
|
13
|
+
for (let attempt = 0;; attempt++) {
|
|
14
|
+
signal.throwIfAborted();
|
|
15
|
+
try {
|
|
16
|
+
const response = await send(credential.token);
|
|
17
|
+
if (!replay || attempt === 2 || (response.status !== 429 && response.status < 500))
|
|
18
|
+
return response;
|
|
19
|
+
await response.body?.cancel();
|
|
20
|
+
}
|
|
21
|
+
catch (error) {
|
|
22
|
+
signal.throwIfAborted();
|
|
23
|
+
if (!replay || attempt === 2 || !(error instanceof CliError && ['UNAVAILABLE', 'TIMEOUT'].includes(error.code)))
|
|
24
|
+
throw error;
|
|
25
|
+
}
|
|
26
|
+
try {
|
|
27
|
+
await delay(2000, undefined, { signal });
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
signal.throwIfAborted();
|
|
31
|
+
throw error;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
let response = await sendWithRetry();
|
|
36
|
+
if (response.status === 401) {
|
|
37
|
+
const requestId = response.headers.get('x-request-id');
|
|
38
|
+
const rejectedByGateway = /^Bearer\s+error="invalid_token"$/i.test(response.headers.get('www-authenticate') ?? '');
|
|
39
|
+
await response.body?.cancel();
|
|
40
|
+
credential = await identity.credential(signal, { forceRefresh: true, rejectedToken: credential.token });
|
|
41
|
+
if (!replay && !rejectedByGateway)
|
|
42
|
+
throw new CliError('UNAVAILABLE', 'Credentials were renewed; this operation was not replayed.', 'Check the actual outcome before deciding whether to submit again.', false, { status: 401, requestId, credentialRenewed: true, executed: 'unknown' });
|
|
43
|
+
response = await sendWithRetry();
|
|
44
|
+
}
|
|
45
|
+
if (response.status === 401) {
|
|
46
|
+
const requestId = response.headers.get('x-request-id');
|
|
47
|
+
await response.body?.cancel();
|
|
48
|
+
await identity.invalidate?.(signal, credential.token);
|
|
49
|
+
throw new CliError('AUTH_EXPIRED', 'The current session cannot access this business service.', 'Run init to authorize again. If access still fails, ask the administrator to check the CLI gateway route and permissions.', false, requestId ? { requestId } : undefined);
|
|
50
|
+
}
|
|
51
|
+
if (!response.ok) {
|
|
52
|
+
let data = {};
|
|
53
|
+
try {
|
|
54
|
+
data = await readJson(response);
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
signal.throwIfAborted();
|
|
58
|
+
}
|
|
59
|
+
throw typeof data.msg !== 'string' && [502, 503, 504].includes(response.status) ? gatewayFailure(response, replay) : backendError(response, data, [credential.token]);
|
|
60
|
+
}
|
|
61
|
+
return response;
|
|
62
|
+
}
|
|
63
|
+
// Without the backend's msg, these statuses come from the gateway: the backend is down, unreachable or too slow.
|
|
64
|
+
// details.executed records what is known about the outcome; next already tells the caller what to do about it.
|
|
65
|
+
function gatewayFailure(response, replay) {
|
|
66
|
+
const requestId = response.headers.get('x-request-id');
|
|
67
|
+
const details = { status: response.status, ...(requestId ? { requestId } : {}) };
|
|
68
|
+
if (response.status === 504) {
|
|
69
|
+
return new CliError('UNAVAILABLE', 'The business service did not answer in time (HTTP 504); the request may still have completed.', replay ? 'Retry later.' : 'Check the actual outcome first, for example with a query, before submitting again, so the operation is not repeated.', replay, { ...details, executed: 'unknown' });
|
|
70
|
+
}
|
|
71
|
+
return new CliError('UNAVAILABLE', `The business service is not reachable (HTTP ${response.status}). This is a server problem, not a problem with the input.`, 'Nothing was changed. Retry later; if it keeps failing, tell the CLI maintainer that the business backend is down or unreachable.', true, { ...details, executed: false });
|
|
72
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { TokenSet } from './provider.js';
|
|
2
|
+
export interface Session extends TokenSet {
|
|
3
|
+
version: 2;
|
|
4
|
+
baseUrl: string;
|
|
5
|
+
clientId: string;
|
|
6
|
+
}
|
|
7
|
+
export interface SessionStore {
|
|
8
|
+
transaction<T>(signal: AbortSignal, action: (store: SessionAccess) => Promise<T>): Promise<T>;
|
|
9
|
+
}
|
|
10
|
+
export interface SessionAccess {
|
|
11
|
+
read(): Promise<Session | null>;
|
|
12
|
+
/** Completes an atomic commit even if cancellation arrives after token rotation. */
|
|
13
|
+
write(session: Session): Promise<void>;
|
|
14
|
+
clear(): Promise<void>;
|
|
15
|
+
}
|
|
16
|
+
export declare const stateDirectory: (directory?: string | undefined) => string;
|
|
17
|
+
export declare class FileSessionStore implements SessionStore {
|
|
18
|
+
readonly directory: string;
|
|
19
|
+
readonly file: string;
|
|
20
|
+
constructor(context: string, directory?: string);
|
|
21
|
+
deviceId(signal: AbortSignal): Promise<string>;
|
|
22
|
+
transaction<T>(signal: AbortSignal, action: (store: SessionAccess) => Promise<T>): Promise<T>;
|
|
23
|
+
private recoverLock;
|
|
24
|
+
private read;
|
|
25
|
+
private write;
|
|
26
|
+
}
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { mkdir, readFile, writeFile, rename, rm, lstat } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
5
|
+
import { spawn } from 'node:child_process';
|
|
6
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
7
|
+
import { CliError } from '../cli/index.js';
|
|
8
|
+
function protect(input, decrypt, signal) {
|
|
9
|
+
const operation = decrypt ? 'Unprotect' : 'Protect';
|
|
10
|
+
const script = `Add-Type -AssemblyName System.Security; $data=[Convert]::FromBase64String([Console]::In.ReadToEnd()); $result=[Security.Cryptography.ProtectedData]::${operation}($data,$null,[Security.Cryptography.DataProtectionScope]::CurrentUser); [Console]::Out.Write([Convert]::ToBase64String($result))`;
|
|
11
|
+
return new Promise((resolve, reject) => {
|
|
12
|
+
const child = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { windowsHide: true, stdio: ['pipe', 'pipe', 'ignore'], timeout: 15000, signal });
|
|
13
|
+
let output = '';
|
|
14
|
+
child.stdout.setEncoding('utf8').on('data', (chunk) => { output += chunk; });
|
|
15
|
+
child.on('error', () => reject(signal?.aborted ? signal.reason : new CliError('IO_ERROR', 'System credential protection is unavailable.', 'Check Windows PowerShell and DPAPI.')));
|
|
16
|
+
child.on('close', (code) => code === 0 ? resolve(output.trim()) : reject(new CliError('IO_ERROR', 'Cannot protect or read local credentials.', 'Use the original OS account; authorize again if needed.')));
|
|
17
|
+
child.stdin.on('error', () => { });
|
|
18
|
+
child.stdin.end(input);
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
export const stateDirectory = (directory = process.env.LXZ_STATE_DIR) => directory ?? join(homedir(), '.lianxz', 'identity');
|
|
22
|
+
export class FileSessionStore {
|
|
23
|
+
directory;
|
|
24
|
+
file;
|
|
25
|
+
constructor(context, directory = stateDirectory()) {
|
|
26
|
+
this.directory = directory;
|
|
27
|
+
this.file = join(directory, `${createHash('sha256').update(context).digest('hex')}.json`);
|
|
28
|
+
}
|
|
29
|
+
deviceId(signal) {
|
|
30
|
+
return this.transaction(signal, async () => {
|
|
31
|
+
const file = this.file.replace(/\.json$/, '.device-id');
|
|
32
|
+
try {
|
|
33
|
+
return await readFile(file, 'utf8');
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
if (error.code !== 'ENOENT')
|
|
37
|
+
throw error;
|
|
38
|
+
}
|
|
39
|
+
const id = randomUUID();
|
|
40
|
+
await writeFile(file, id, { mode: 0o600, flag: 'wx' });
|
|
41
|
+
return id;
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
async transaction(signal, action) {
|
|
45
|
+
await mkdir(this.directory, { recursive: true, mode: 0o700 });
|
|
46
|
+
const stat = await lstat(this.directory);
|
|
47
|
+
if (stat.isSymbolicLink() || (process.platform !== 'win32' && (stat.mode & 0o077) !== 0))
|
|
48
|
+
throw new CliError('IO_ERROR', 'Session directory permissions are unsafe.', 'Use a private session directory owned by the current user with mode 0700.');
|
|
49
|
+
const lock = `${this.file}.lock`;
|
|
50
|
+
const deadline = Date.now() + 20000;
|
|
51
|
+
while (true) {
|
|
52
|
+
signal.throwIfAborted();
|
|
53
|
+
try {
|
|
54
|
+
await mkdir(lock, { mode: 0o700 });
|
|
55
|
+
break;
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
if (error.code !== 'EEXIST')
|
|
59
|
+
throw new CliError('IO_ERROR', 'Cannot lock the session directory.', 'Check write permissions for the session directory.');
|
|
60
|
+
await this.recoverLock(lock);
|
|
61
|
+
if (Date.now() > deadline)
|
|
62
|
+
throw new CliError('UNAVAILABLE', 'Another process is using this CLI session.', 'Retry later. If the process crashed and the lock has no pid, ensure no CLI is running before removing its .lock directory.', true);
|
|
63
|
+
await delay(50, undefined, { signal });
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
try {
|
|
67
|
+
await writeFile(join(lock, 'pid'), String(process.pid), { mode: 0o600 });
|
|
68
|
+
signal.throwIfAborted();
|
|
69
|
+
return await action({
|
|
70
|
+
read: async () => { signal.throwIfAborted(); const session = await this.read(signal); signal.throwIfAborted(); return session; },
|
|
71
|
+
write: (session) => this.write(session),
|
|
72
|
+
clear: async () => { await rm(this.file, { force: true }); },
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
finally {
|
|
76
|
+
await rm(lock, { recursive: true, force: true });
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
async recoverLock(lock) {
|
|
80
|
+
const recovery = `${lock}.recovery`;
|
|
81
|
+
try {
|
|
82
|
+
await mkdir(recovery);
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
try {
|
|
88
|
+
let pid = 0;
|
|
89
|
+
try {
|
|
90
|
+
pid = Number(await readFile(join(lock, 'pid'), 'utf8'));
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
if (error.code === 'ENOENT') {
|
|
94
|
+
try {
|
|
95
|
+
if (Date.now() - (await lstat(lock)).mtimeMs > 30000)
|
|
96
|
+
await rm(lock, { recursive: true, force: true });
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
if (error.code !== 'ENOENT')
|
|
100
|
+
throw error;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
if (!Number.isSafeInteger(pid) || pid <= 0)
|
|
106
|
+
return;
|
|
107
|
+
try {
|
|
108
|
+
process.kill(pid, 0);
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
if (error.code === 'ESRCH')
|
|
112
|
+
await rm(lock, { recursive: true, force: true });
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
finally {
|
|
116
|
+
await rm(recovery, { recursive: true, force: true });
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
async read(signal) {
|
|
120
|
+
let raw;
|
|
121
|
+
try {
|
|
122
|
+
const stat = await lstat(this.file);
|
|
123
|
+
if (stat.isSymbolicLink() || (process.platform !== 'win32' && (stat.mode & 0o077) !== 0))
|
|
124
|
+
throw new CliError('IO_ERROR', 'Session file permissions are unsafe.', 'Set session file permissions to 0600.');
|
|
125
|
+
raw = await readFile(this.file, 'utf8');
|
|
126
|
+
}
|
|
127
|
+
catch (error) {
|
|
128
|
+
if (error.code === 'ENOENT')
|
|
129
|
+
return null;
|
|
130
|
+
throw error;
|
|
131
|
+
}
|
|
132
|
+
try {
|
|
133
|
+
const record = JSON.parse(raw);
|
|
134
|
+
if (record.version !== 2)
|
|
135
|
+
throw new CliError('INCOMPATIBLE', 'Unsupported local session format.', 'Run this CLI logout command to clear the session, then authorize again.');
|
|
136
|
+
if (record.protection === 'dpapi')
|
|
137
|
+
raw = Buffer.from(await protect(record.data, true, signal), 'base64').toString('utf8');
|
|
138
|
+
else if (record.protection === 'user-file' && process.platform !== 'win32')
|
|
139
|
+
raw = record.data;
|
|
140
|
+
else
|
|
141
|
+
throw new Error('protection');
|
|
142
|
+
const session = JSON.parse(raw);
|
|
143
|
+
session.accessExpiresAt = session.accessTokenExpiresAt;
|
|
144
|
+
session.refreshExpiresAt = session.refreshTokenExpiresAt;
|
|
145
|
+
delete session.accessTokenExpiresAt;
|
|
146
|
+
delete session.refreshTokenExpiresAt;
|
|
147
|
+
if (session.version !== 2 || ['refreshToken', 'accessToken', 'baseUrl', 'clientId'].some((key) => typeof session[key] !== 'string') || (session.account !== undefined && typeof session.account !== 'string') || !Number.isFinite(session.accessExpiresAt) || !Number.isFinite(session.refreshExpiresAt))
|
|
148
|
+
throw new Error('session');
|
|
149
|
+
return session;
|
|
150
|
+
}
|
|
151
|
+
catch (error) {
|
|
152
|
+
signal.throwIfAborted();
|
|
153
|
+
if (error instanceof CliError)
|
|
154
|
+
throw error;
|
|
155
|
+
throw new CliError('IO_ERROR', 'Local session is damaged or cannot be decrypted.', 'Run this CLI logout command to clear local tokens, then authorize again.');
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
async write(session) {
|
|
159
|
+
const { accessExpiresAt, refreshExpiresAt, ...rest } = session;
|
|
160
|
+
const plain = JSON.stringify({ ...rest, accessTokenExpiresAt: accessExpiresAt, refreshTokenExpiresAt: refreshExpiresAt });
|
|
161
|
+
const data = process.platform === 'win32' ? await protect(Buffer.from(plain).toString('base64'), false) : plain;
|
|
162
|
+
const temporary = `${this.file}.${randomUUID()}.tmp`;
|
|
163
|
+
try {
|
|
164
|
+
await writeFile(temporary, JSON.stringify({ version: 2, protection: process.platform === 'win32' ? 'dpapi' : 'user-file', data }), { mode: 0o600, flag: 'wx' });
|
|
165
|
+
await rename(temporary, this.file);
|
|
166
|
+
}
|
|
167
|
+
finally {
|
|
168
|
+
await rm(temporary, { force: true });
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function openBrowser(url: string, signal: AbortSignal): Promise<boolean>;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
export async function openBrowser(url, signal) {
|
|
3
|
+
signal.throwIfAborted();
|
|
4
|
+
const [command, args] = process.platform === 'win32' ? ['rundll32.exe', ['url.dll,FileProtocolHandler', url]]
|
|
5
|
+
: process.platform === 'darwin' ? ['open', [url]] : ['xdg-open', [url]];
|
|
6
|
+
return new Promise((resolve) => {
|
|
7
|
+
const child = spawn(command, args, { windowsHide: true, stdio: 'ignore', timeout: 10000, signal });
|
|
8
|
+
child.on('error', () => resolve(false));
|
|
9
|
+
child.on('close', (code) => resolve(code === 0));
|
|
10
|
+
});
|
|
11
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type { ArgDef } from 'citty';
|
|
2
|
+
export declare const contractVersion = "1.0.0";
|
|
3
|
+
export interface Parameter {
|
|
4
|
+
type: 'string' | 'boolean';
|
|
5
|
+
description: string;
|
|
6
|
+
required?: boolean;
|
|
7
|
+
default?: string | boolean;
|
|
8
|
+
choices?: string[];
|
|
9
|
+
pattern?: string;
|
|
10
|
+
}
|
|
11
|
+
export interface Command {
|
|
12
|
+
module?: string;
|
|
13
|
+
description: string;
|
|
14
|
+
parameters?: Record<string, Parameter>;
|
|
15
|
+
result: Record<string, unknown>;
|
|
16
|
+
examples: string[];
|
|
17
|
+
effects: 'none' | 'local' | 'remote';
|
|
18
|
+
preview?: boolean;
|
|
19
|
+
timeoutMs?: number;
|
|
20
|
+
interactiveTimeout?: 'idle' | 'total';
|
|
21
|
+
format?: (result: unknown) => string;
|
|
22
|
+
run: (input: Record<string, string | boolean>, context: Context) => unknown | Promise<unknown>;
|
|
23
|
+
}
|
|
24
|
+
export interface Context {
|
|
25
|
+
interactive: boolean;
|
|
26
|
+
allowDeviceLogin?: boolean;
|
|
27
|
+
browser?: boolean;
|
|
28
|
+
/** Arguments of this invocation, used to continue it in a background process. */
|
|
29
|
+
argv?: string[];
|
|
30
|
+
signal: AbortSignal;
|
|
31
|
+
log: (message: string) => void;
|
|
32
|
+
}
|
|
33
|
+
export interface Application {
|
|
34
|
+
name: string;
|
|
35
|
+
packageName: string;
|
|
36
|
+
version: string;
|
|
37
|
+
description: string;
|
|
38
|
+
defaultCommand?: string;
|
|
39
|
+
commands: Record<string, Command>;
|
|
40
|
+
}
|
|
41
|
+
export declare const commonParameters: Record<string, Parameter>;
|
|
42
|
+
export declare function commandParameters(command?: Command): {
|
|
43
|
+
'timeout-ms'?: {
|
|
44
|
+
description: string;
|
|
45
|
+
default?: string | boolean;
|
|
46
|
+
type: "string" | "boolean";
|
|
47
|
+
required?: boolean;
|
|
48
|
+
choices?: string[];
|
|
49
|
+
pattern?: string;
|
|
50
|
+
} | undefined;
|
|
51
|
+
};
|
|
52
|
+
export declare function argumentDefinitions(parameters: Record<string, Parameter>): Record<string, ArgDef>;
|
|
53
|
+
export declare function describe(app: Application, scope?: string): {
|
|
54
|
+
contractVersion: string;
|
|
55
|
+
name: string;
|
|
56
|
+
packageName: string;
|
|
57
|
+
version: string;
|
|
58
|
+
description: string;
|
|
59
|
+
commands: {
|
|
60
|
+
[k: string]: {
|
|
61
|
+
description: string;
|
|
62
|
+
effects: "none" | "local" | "remote";
|
|
63
|
+
preview: boolean;
|
|
64
|
+
examples: string[];
|
|
65
|
+
input: {
|
|
66
|
+
type: string;
|
|
67
|
+
additionalProperties: boolean;
|
|
68
|
+
properties: {
|
|
69
|
+
[k: string]: {
|
|
70
|
+
pattern?: string | undefined;
|
|
71
|
+
enum?: string[] | undefined;
|
|
72
|
+
default?: string | boolean | undefined;
|
|
73
|
+
type: "string" | "boolean";
|
|
74
|
+
description: string;
|
|
75
|
+
};
|
|
76
|
+
};
|
|
77
|
+
required: string[];
|
|
78
|
+
};
|
|
79
|
+
result: Record<string, unknown>;
|
|
80
|
+
module?: string | undefined;
|
|
81
|
+
};
|
|
82
|
+
};
|
|
83
|
+
};
|
|
84
|
+
export declare function commandReference(app: Application): string;
|
|
85
|
+
export declare function shellCommandExamples(pwsh: string, bash?: string): string;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
export const contractVersion = '1.0.0';
|
|
2
|
+
export const commonParameters = {
|
|
3
|
+
json: { type: 'boolean', description: 'Return a JSON receipt instead of compact rows; use for programmatic parsing', default: false },
|
|
4
|
+
'non-interactive': { type: 'boolean', description: 'Use command parameters without interactive prompts', default: false },
|
|
5
|
+
'timeout-ms': { type: 'string', description: 'Non-interactive deadline in ms (1-3600000); interactive prompts exit after 60 seconds without input', default: '120000', pattern: '^(?:[1-9][0-9]{0,5}|[12][0-9]{6}|3[0-5][0-9]{5}|3600000)$' },
|
|
6
|
+
help: { type: 'boolean', description: 'Show help for this command or group; same as -h' },
|
|
7
|
+
version: { type: 'boolean', description: 'Show version' },
|
|
8
|
+
schema: { type: 'boolean', description: 'Show command, input and result schemas' },
|
|
9
|
+
};
|
|
10
|
+
export function commandParameters(command) {
|
|
11
|
+
return { ...commonParameters, ...(command?.timeoutMs || command?.interactiveTimeout === 'total' ? { 'timeout-ms': {
|
|
12
|
+
...commonParameters['timeout-ms'],
|
|
13
|
+
...(command.timeoutMs ? { default: String(command.timeoutMs) } : {}),
|
|
14
|
+
...(command.interactiveTimeout === 'total' ? { description: 'Total deadline in ms (1-3600000), including approval waits; keyboard inactivity does not end authorization' } : {}),
|
|
15
|
+
} } : {}), ...command?.parameters };
|
|
16
|
+
}
|
|
17
|
+
export function argumentDefinitions(parameters) {
|
|
18
|
+
return Object.fromEntries(Object.entries(parameters).map(([key, { choices, pattern, ...definition }]) => [key, definition]));
|
|
19
|
+
}
|
|
20
|
+
export function describe(app, scope) {
|
|
21
|
+
return {
|
|
22
|
+
contractVersion, name: app.name, packageName: app.packageName, version: app.version,
|
|
23
|
+
description: app.description,
|
|
24
|
+
commands: Object.fromEntries(Object.entries(app.commands).filter(([name]) => !scope || name === scope || name.startsWith(scope + ' ')).map(([name, command]) => [name, {
|
|
25
|
+
...(command.module ? { module: command.module } : {}),
|
|
26
|
+
description: command.description, effects: command.effects, preview: command.preview ?? false,
|
|
27
|
+
examples: command.examples,
|
|
28
|
+
input: {
|
|
29
|
+
type: 'object', additionalProperties: false,
|
|
30
|
+
properties: Object.fromEntries(Object.entries(commandParameters(command)).map(([name, { description, type, default: value, choices, pattern }]) => [name, {
|
|
31
|
+
type, description, ...(value === undefined ? {} : { default: value }), ...(choices ? { enum: choices } : {}), ...(pattern ? { pattern } : {}),
|
|
32
|
+
}])),
|
|
33
|
+
required: Object.entries(command.parameters ?? {}).filter(([, p]) => p.required).map(([name]) => name),
|
|
34
|
+
},
|
|
35
|
+
result: command.result,
|
|
36
|
+
}])),
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
export function commandReference(app) {
|
|
40
|
+
return Object.entries(describe(app).commands).map(([name, command]) => [
|
|
41
|
+
`### ${app.name} ${name}`, command.description, `Effects: ${command.effects}; Preview: ${command.preview}.`,
|
|
42
|
+
...Object.entries(command.input.properties).map(([key, value]) => `- --${key} (${value.type}): ${value.description}${'default' in value ? `; default ${JSON.stringify(value.default)}` : ''}${command.input.required.includes(key) ? '; required' : ''}${'enum' in value ? `; choices ${JSON.stringify(value.enum)}` : ''}`),
|
|
43
|
+
`Result schema:\n\n\`\`\`json\n${JSON.stringify(command.result, null, 2)}\n\`\`\``,
|
|
44
|
+
...command.examples.map((example) => shellCommandExamples(example)),
|
|
45
|
+
].join('\n\n')).join('\n\n');
|
|
46
|
+
}
|
|
47
|
+
export function shellCommandExamples(pwsh, bash = pwsh) {
|
|
48
|
+
if (pwsh === bash)
|
|
49
|
+
return `**pwsh / bash**\n\n\`\`\`sh\n${pwsh}\n\`\`\``;
|
|
50
|
+
return `**pwsh**\n\n\`\`\`pwsh\n${pwsh}\n\`\`\`\n\n**bash**\n\n\`\`\`bash\n${bash}\n\`\`\``;
|
|
51
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export declare const deploymentDefaults: {
|
|
2
|
+
LINKWISE_ISSUER: string;
|
|
3
|
+
};
|
|
4
|
+
/**
|
|
5
|
+
* Roots serving the same paths as an issuer origin, used while that origin cannot be reached.
|
|
6
|
+
* LINKWISE_FALLBACK_URL overrides (an empty value disables); a test build ships its own in linkwise.env.json.
|
|
7
|
+
*/
|
|
8
|
+
export declare const deploymentFallbacks: Readonly<Record<string, string>>;
|
|
9
|
+
/**
|
|
10
|
+
* Fixes the authorization server for this process and the lxz processes it starts: environment, then the file a test build ships with, then production.
|
|
11
|
+
* The packaged fallback address goes with the packaged issuer only.
|
|
12
|
+
*/
|
|
13
|
+
export declare function applyDeployment(packageRoot: URL, env?: NodeJS.ProcessEnv): void;
|