@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
package/README.md
CHANGED
|
@@ -1,3 +1,64 @@
|
|
|
1
|
-
#
|
|
1
|
+
# lxz
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
管理业务 CLI 的登录、状态查询和退出,检查运行环境与授权服务。日常业务操作使用业务 CLI 自己的命令,授权由其依赖中的 lxz 办理。
|
|
4
|
+
|
|
5
|
+
## 运行
|
|
6
|
+
|
|
7
|
+
准备 Node.js >=22.12 和 pnpm 12。从 npm 官方源直接运行推荐版(`latest`),以下命令适用于 pwsh 和 bash:
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
pnpm dlx @tulcn/lxz --version --json
|
|
11
|
+
pnpm dlx @tulcn/lxz --help
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
也可以全局安装。pnpm 默认不运行依赖包的安装脚本,`--allow-build=@tulcn/lxz` 只允许本包的 postinstall 运行,用来同时安装内置 Skill:
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
pnpm add --global @tulcn/lxz --allow-build=@tulcn/lxz
|
|
18
|
+
lxz --version
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
安装输出提示 `Ignored build scripts`,或使用 `--ignore-scripts` 等不运行安装脚本的方式安装时,按下文“Agent 接入”运行 `install skill` 补装。
|
|
22
|
+
|
|
23
|
+
默认输出行数据;Agent 使用 `--non-interactive`,需要程序解析时加 `--json`,先解析 JSON 再读取字段。命令说明、帮助、提示和程序日志使用英文 ASCII;业务数据、用户输入及路径按 UTF-8 保留原文。`--json` 回执为纯 ASCII,中文等字符以 `\uXXXX` 转义,解析后与原文一致,PowerShell 可直接用 `ConvertFrom-Json` 解析。行数据按 UTF-8 解码;PowerShell 捕获行数据时,在当前会话先执行:
|
|
24
|
+
|
|
25
|
+
```powershell
|
|
26
|
+
[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## 登录与退出
|
|
30
|
+
|
|
31
|
+
命令和分组都支持 `-h`(同 `--help`)。使用上面的调用前缀加 `auth -h`,列出授权子命令;加 `auth login -h`,查看登录参数与示例。通过帮助逐级查看当前版本的命令与参数。
|
|
32
|
+
|
|
33
|
+
默认使用正式授权中心 `https://ai-cli.tul.cn/linkwise-api`。先向管理员确认该环境中已登记且获准使用的 CLI 标识,把下面的 `<CLI 标识>` 替换为管理员分配的值。管理员要求连接其他授权环境时,在当前终端把 `LINKWISE_ISSUER` 设为管理员提供的地址;各环境的登记、授权和令牌互不通用。授权中心域名连不上时,CLI 自动改用备用地址(正式为 `https://linkwise.tul.cn/cli`),并在命令行提示一行。
|
|
34
|
+
|
|
35
|
+
登录时在浏览器核对验证码并允许授权;退出命令会撤销本次授权并删除本机登录信息。
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
pnpm dlx @tulcn/lxz auth login --client-id '<CLI 标识>'
|
|
39
|
+
pnpm dlx @tulcn/lxz auth status --client-id '<CLI 标识>' --json
|
|
40
|
+
pnpm dlx @tulcn/lxz doctor --client-id '<CLI 标识>' --json
|
|
41
|
+
pnpm dlx @tulcn/lxz auth logout --client-id '<CLI 标识>'
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
每个 CLI 分别授权。其他设备和 CLI 的会话不受本次退出影响。撤销最多等待 10 秒;失败仍删除本机令牌,并提示服务端授权可能仍有效,需要时联系管理员撤销。
|
|
45
|
+
|
|
46
|
+
Agent 或脚本登录时加 `--device-login --non-interactive`,默认仍打开浏览器。命令拿到授权链接和用户码后立即返回 `status: pending`,由后台进程继续等待;把链接和用户码交给用户,再运行 `auth status --wait-seconds 170`(带同样的 `--client-id`),批准后立即返回。再加 `--no-browser` 时不打开浏览器,可在另一设备打开链接;需要原命令一直等到批准时加 `--wait`,默认最多 660 秒。
|
|
47
|
+
|
|
48
|
+
`pnpm dlx @tulcn/lxz auth whoami --client-id '<CLI 标识>' --json` 显示本机保存的人员编号 `account`、登录名 `loginName`、显示名 `displayName` 及授权有效期。`clientId` 是 CLI 标识;后端未提供的身份字段不会补齐。本机有登录记录不代表已实时确认服务端权限。
|
|
49
|
+
|
|
50
|
+
`doctor` 检查 Node.js 与 pnpm 版本、pnpm 为 `@tulcn` 包配置的源(未单独配置时为默认源)能否取到 `@tulcn/lxz`、授权服务和本机登录状态,不发起登录。
|
|
51
|
+
|
|
52
|
+
## Agent 接入
|
|
53
|
+
|
|
54
|
+
首次接入 Agent 或更新程序后,运行以下命令安装最新版内置的 Skill:
|
|
55
|
+
|
|
56
|
+
```sh
|
|
57
|
+
pnpm dlx @tulcn/lxz install skill --skills-dir '<Agent 的 Skills 根目录>'
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Skill 写入该目录下的 `lxz/`。安装目录优先使用 `--skills-dir`,其次为 `LXZ_SKILLS_DIR`,首次默认同时安装到 `~/.agents/skills` 和 `~/.linkwise/skills`。安装位置会登记,后续未指定目录时同步已登记的位置;`LXZ_SKILLS_STATE_DIR` 可指定登记记录的目录。
|
|
61
|
+
|
|
62
|
+
全局安装时,postinstall 在获准运行后自动安装 Skill;pnpm 默认会跳过它,其他包管理器或公司策略也可能跳过,请显式运行上述命令确认安装(已安装同一版本时不会重复写入)。本地修改引起冲突时先备份,再使用 `--skill-conflict replace` 替换。
|
|
63
|
+
|
|
64
|
+
升级或回滚后,显式同步所用版本的 Skill。需要回滚时,安装指定的精确版本(如 `@tulcn/lxz@<版本>`),再运行该程序的 `install skill`。回滚切换 CLI 程序及其 Skill,授权会话按各自有效期管理。
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { defaultIdentity } from './auth/index.js';
|
|
3
|
+
import { identityCommands, registerCommandModules } from './cli/index.js';
|
|
4
|
+
import { BundledSkill, skillCommands } from './skills/index.js';
|
|
5
|
+
import { doctor } from './doctor.js';
|
|
6
|
+
const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
7
|
+
const commands = identityCommands((input) => defaultIdentity(typeof input['client-id'] === 'string' ? input['client-id'] : undefined), 'pnpm dlx @tulcn/lxz auth');
|
|
8
|
+
for (const command of Object.values(commands))
|
|
9
|
+
command.parameters = { ...command.parameters, 'client-id': { type: 'string', description: 'Client ID to manage; defaults to LXZ_AUTH_CLIENT_ID' } };
|
|
10
|
+
export const application = {
|
|
11
|
+
name: 'lxz', packageName: pkg.name, version: pkg.version, description: 'Linkwise CLI authorization and diagnostics',
|
|
12
|
+
commands: registerCommandModules([
|
|
13
|
+
{ id: 'authorization', commands: { ...Object.fromEntries(Object.entries(commands).map(([name, command]) => ['auth ' + name, command])), 'auth whoami': { ...commands.status, description: 'Show the local account authorized for this CLI' } } },
|
|
14
|
+
{ id: 'diagnostics', commands: { doctor } },
|
|
15
|
+
{ id: 'skill', commands: skillCommands(new BundledSkill(new URL('../', import.meta.url), 'lxz'), 'pnpm dlx @tulcn/lxz') },
|
|
16
|
+
]),
|
|
17
|
+
};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { callMain } from '../internal/client.js';
|
|
2
|
+
export function createLxzAuthorization({ defaults = {}, env = process.env } = {}) {
|
|
3
|
+
return (clientId) => {
|
|
4
|
+
const call = (request, signal, log) => callMain({ ...request, clientId }, { signal, env: { ...defaults, ...env }, log });
|
|
5
|
+
return {
|
|
6
|
+
status: (signal) => call({ operation: 'status' }, signal),
|
|
7
|
+
login: ({ signal, log, interactive, allowDeviceLogin, browser }) => call({ operation: 'login', interactive, allowDeviceLogin, browser }, signal, log),
|
|
8
|
+
credential: (signal, options) => call({ operation: 'credential', options }, signal),
|
|
9
|
+
invalidate: (signal, rejectedToken) => call({ operation: 'invalidate', rejectedToken }, signal),
|
|
10
|
+
logout: (signal) => call({ operation: 'logout' }, signal),
|
|
11
|
+
inspect: (signal) => call({ operation: 'inspect' }, signal),
|
|
12
|
+
};
|
|
13
|
+
};
|
|
14
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function gatewayAddress(clientId: string, env?: NodeJS.ProcessEnv): string;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { CliError } from '../cli/index.js';
|
|
2
|
+
import { authConfig } from './provider.js';
|
|
3
|
+
export function gatewayAddress(clientId, env = process.env) {
|
|
4
|
+
const config = authConfig(env, clientId);
|
|
5
|
+
if (['.', '..'].includes(config.clientId))
|
|
6
|
+
throw new CliError('CONFIGURATION', 'Client ID cannot be a relative path segment.', 'Use the CLI identifier assigned by the administrator.');
|
|
7
|
+
const url = new URL(config.baseUrl);
|
|
8
|
+
url.pathname = '/biz/' + encodeURIComponent(config.clientId);
|
|
9
|
+
return url.href;
|
|
10
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { CliError } from '../cli/errors.js';
|
|
2
|
+
import { createAuthorization } from './modules.js';
|
|
3
|
+
export async function executeAuthorization(request, signal, log) {
|
|
4
|
+
const identity = createAuthorization()(request.clientId);
|
|
5
|
+
switch (request.operation) {
|
|
6
|
+
case 'status': return identity.status(signal);
|
|
7
|
+
case 'login': return identity.login({ ...request, signal, log });
|
|
8
|
+
case 'credential': return identity.credential(signal, request.options);
|
|
9
|
+
case 'invalidate': return identity.invalidate?.(signal, request.rejectedToken);
|
|
10
|
+
case 'logout': return identity.logout(signal);
|
|
11
|
+
case 'inspect':
|
|
12
|
+
if (!identity.inspect)
|
|
13
|
+
throw new CliError('CONFIGURATION', 'The selected authorization module has no service diagnostics.', 'Ask the lxz maintainer to add authorization diagnostics.');
|
|
14
|
+
return identity.inspect(signal);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { Context, IdentityPort } from '../cli/index.js';
|
|
2
|
+
import type { AuthProvider } from './provider.js';
|
|
3
|
+
import type { SessionStore } from './store.js';
|
|
4
|
+
export declare class Identity implements IdentityPort {
|
|
5
|
+
readonly provider: AuthProvider;
|
|
6
|
+
readonly store: SessionStore;
|
|
7
|
+
readonly baseUrl: string;
|
|
8
|
+
readonly clientId: string;
|
|
9
|
+
constructor(provider: AuthProvider, store: SessionStore, baseUrl: string, clientId: string);
|
|
10
|
+
status(signal: AbortSignal): Promise<{
|
|
11
|
+
accessExpiresAt: number;
|
|
12
|
+
refreshExpiresAt: number;
|
|
13
|
+
displayName?: string | undefined;
|
|
14
|
+
loginName?: string | undefined;
|
|
15
|
+
authorized: boolean;
|
|
16
|
+
clientId: string;
|
|
17
|
+
account: string | undefined;
|
|
18
|
+
} | null>;
|
|
19
|
+
login(context: Context): Promise<{
|
|
20
|
+
account: string | undefined;
|
|
21
|
+
}>;
|
|
22
|
+
credential(signal: AbortSignal, options?: {
|
|
23
|
+
forceRefresh?: boolean;
|
|
24
|
+
rejectedToken?: string;
|
|
25
|
+
}): Promise<{
|
|
26
|
+
token: string;
|
|
27
|
+
expiresAt: number;
|
|
28
|
+
}>;
|
|
29
|
+
invalidate(signal: AbortSignal, rejectedToken: string): Promise<void>;
|
|
30
|
+
logout(signal: AbortSignal): Promise<{
|
|
31
|
+
warning?: string | undefined;
|
|
32
|
+
revocationError?: {
|
|
33
|
+
details?: {} | null | undefined;
|
|
34
|
+
code: "INVALID_INPUT" | "AUTH_REQUIRED" | "AUTH_EXPIRED" | "ACCESS_DENIED" | "UNAVAILABLE" | "CONFLICT" | "IO_ERROR" | "CANCELLED" | "TIMEOUT" | "CONFIGURATION" | "INCOMPATIBLE" | "INIT_INCOMPLETE" | "INTERNAL";
|
|
35
|
+
message: string;
|
|
36
|
+
retryable: boolean;
|
|
37
|
+
next: string;
|
|
38
|
+
} | undefined;
|
|
39
|
+
loggedOut: boolean;
|
|
40
|
+
clientId: string;
|
|
41
|
+
revocation: "failed" | "revoked" | "not-needed";
|
|
42
|
+
impact: string;
|
|
43
|
+
}>;
|
|
44
|
+
private checkContext;
|
|
45
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { CliError, failure } from '../cli/index.js';
|
|
2
|
+
export class Identity {
|
|
3
|
+
provider;
|
|
4
|
+
store;
|
|
5
|
+
baseUrl;
|
|
6
|
+
clientId;
|
|
7
|
+
constructor(provider, store, baseUrl, clientId) {
|
|
8
|
+
this.provider = provider;
|
|
9
|
+
this.store = store;
|
|
10
|
+
this.baseUrl = baseUrl;
|
|
11
|
+
this.clientId = clientId;
|
|
12
|
+
}
|
|
13
|
+
status(signal) {
|
|
14
|
+
return this.store.transaction(signal, async (store) => {
|
|
15
|
+
const session = await store.read();
|
|
16
|
+
this.checkContext(session);
|
|
17
|
+
if (!session)
|
|
18
|
+
return null;
|
|
19
|
+
if (session.refreshExpiresAt <= Date.now()) {
|
|
20
|
+
await store.clear();
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
return { authorized: true, clientId: this.clientId, account: session.account, ...(session.loginName ? { loginName: session.loginName } : {}), ...(session.displayName ? { displayName: session.displayName } : {}), accessExpiresAt: session.accessExpiresAt, refreshExpiresAt: session.refreshExpiresAt };
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
async login(context) {
|
|
27
|
+
const existing = await this.status(context.signal);
|
|
28
|
+
if (existing)
|
|
29
|
+
return existing;
|
|
30
|
+
const token = await this.provider.login(context);
|
|
31
|
+
return this.store.transaction(context.signal, async (store) => {
|
|
32
|
+
const current = await store.read();
|
|
33
|
+
this.checkContext(current);
|
|
34
|
+
if (current && current.refreshExpiresAt > Date.now())
|
|
35
|
+
return { account: current.account };
|
|
36
|
+
await store.write({ ...token, version: 2, baseUrl: this.baseUrl, clientId: this.clientId });
|
|
37
|
+
return { account: token.account };
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
credential(signal, options = {}) {
|
|
41
|
+
return this.store.transaction(signal, async (store) => {
|
|
42
|
+
const session = await store.read();
|
|
43
|
+
this.checkContext(session);
|
|
44
|
+
if (!session)
|
|
45
|
+
throw new CliError('AUTH_REQUIRED', 'Authorize before using this CLI.', 'Run this CLI init command and follow the browser instructions to authorize.');
|
|
46
|
+
if (session.refreshExpiresAt <= Date.now()) {
|
|
47
|
+
await store.clear();
|
|
48
|
+
throw new CliError('AUTH_EXPIRED', 'Authorization has expired.', 'Run this CLI init command again and authorize in the browser.');
|
|
49
|
+
}
|
|
50
|
+
const reusable = session.accessExpiresAt > Date.now() + 10 * 60 * 1000;
|
|
51
|
+
const replaced = options.rejectedToken && options.rejectedToken !== session.accessToken;
|
|
52
|
+
if (reusable && (!options.forceRefresh || replaced))
|
|
53
|
+
return { token: session.accessToken, expiresAt: session.accessExpiresAt };
|
|
54
|
+
try {
|
|
55
|
+
const token = await this.provider.refresh(session.refreshToken, signal);
|
|
56
|
+
await store.write({ ...token, version: 2, baseUrl: this.baseUrl, clientId: this.clientId });
|
|
57
|
+
signal.throwIfAborted();
|
|
58
|
+
return { token: token.accessToken, expiresAt: token.accessExpiresAt };
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
if (error instanceof CliError && error.code === 'AUTH_EXPIRED')
|
|
62
|
+
await store.clear();
|
|
63
|
+
throw error;
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
invalidate(signal, rejectedToken) {
|
|
68
|
+
return this.store.transaction(signal, async (store) => {
|
|
69
|
+
const session = await store.read();
|
|
70
|
+
this.checkContext(session);
|
|
71
|
+
if (session?.accessToken === rejectedToken)
|
|
72
|
+
await store.clear();
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
logout(signal) {
|
|
76
|
+
return this.store.transaction(signal, async (store) => {
|
|
77
|
+
let revocation = 'not-needed';
|
|
78
|
+
let revocationError;
|
|
79
|
+
try {
|
|
80
|
+
const session = await store.read();
|
|
81
|
+
this.checkContext(session);
|
|
82
|
+
if (session) {
|
|
83
|
+
await this.provider.revoke(session.refreshToken, signal);
|
|
84
|
+
revocation = 'revoked';
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
revocation = 'failed';
|
|
89
|
+
revocationError = failure(error);
|
|
90
|
+
}
|
|
91
|
+
finally {
|
|
92
|
+
await store.clear();
|
|
93
|
+
}
|
|
94
|
+
const warning = 'Server authorization could not be revoked and may remain valid until expiry. Ask an administrator to revoke it if immediate removal is required.';
|
|
95
|
+
return { loggedOut: true, clientId: this.clientId, revocation,
|
|
96
|
+
impact: revocation === 'revoked' ? 'Revoked this server grant and deleted local tokens; other devices and CLIs are unaffected.'
|
|
97
|
+
: revocation === 'failed' ? 'Deleted local tokens for this CLI. ' + warning : 'No local session exists for this CLI; no revocation was needed.',
|
|
98
|
+
...(revocation === 'failed' ? { warning, revocationError } : {}),
|
|
99
|
+
};
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
checkContext(session) {
|
|
103
|
+
if (session && (session.baseUrl !== this.baseUrl || session.clientId !== this.clientId))
|
|
104
|
+
throw new CliError('INCOMPATIBLE', 'The saved session does not match the current CLI configuration.', 'Check the service URL and client ID; after changing configuration, run logout and authorize again.');
|
|
105
|
+
}
|
|
106
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export * from './provider.js';
|
|
2
|
+
export * from './store.js';
|
|
3
|
+
export * from './identity.js';
|
|
4
|
+
export * from './service.js';
|
|
5
|
+
export * from './gateway.js';
|
|
6
|
+
export * from './platform.js';
|
|
7
|
+
export * from './modules.js';
|
|
8
|
+
export * from './inspection.js';
|
|
9
|
+
export * from './client.js';
|
|
10
|
+
export declare function defaultIdentity(clientId?: string): import("../cli/init.js").IdentityPort;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { createAuthorization } from './modules.js';
|
|
2
|
+
export * from './provider.js';
|
|
3
|
+
export * from './store.js';
|
|
4
|
+
export * from './identity.js';
|
|
5
|
+
export * from './service.js';
|
|
6
|
+
export * from './gateway.js';
|
|
7
|
+
export * from './platform.js';
|
|
8
|
+
export * from './modules.js';
|
|
9
|
+
export * from './inspection.js';
|
|
10
|
+
export * from './client.js';
|
|
11
|
+
export function defaultIdentity(clientId) {
|
|
12
|
+
return createAuthorization()(clientId);
|
|
13
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { AuthConfig } from './provider.js';
|
|
2
|
+
export declare function inspectAuthorization(config: AuthConfig, signal: AbortSignal): Promise<{
|
|
3
|
+
reachable: boolean;
|
|
4
|
+
gatewayProtected: boolean;
|
|
5
|
+
clientId: string;
|
|
6
|
+
authenticated: boolean;
|
|
7
|
+
endpoints: {
|
|
8
|
+
issuer: string;
|
|
9
|
+
deviceAuthorization: string;
|
|
10
|
+
token: string;
|
|
11
|
+
revocation: string;
|
|
12
|
+
business: string;
|
|
13
|
+
};
|
|
14
|
+
}>;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { CliError, readJson, request } from '../cli/index.js';
|
|
2
|
+
import { gatewayAddress } from './gateway.js';
|
|
3
|
+
import { platformExchange } from './platform.js';
|
|
4
|
+
export async function inspectAuthorization(config, signal) {
|
|
5
|
+
const primary = gatewayAddress(config.clientId, { LINKWISE_ISSUER: config.baseUrl }) + '/';
|
|
6
|
+
const { response, url } = config.site ? await platformExchange(primary, { signal }, { site: config.site }) : { response: await request(primary, { signal }), url: primary };
|
|
7
|
+
const business = url.replace(/\/$/, '');
|
|
8
|
+
const requestId = response.headers.get('x-request-id');
|
|
9
|
+
const details = { status: response.status, ...(requestId ? { requestId } : {}) };
|
|
10
|
+
let data = {};
|
|
11
|
+
try {
|
|
12
|
+
data = await readJson(response);
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
signal.throwIfAborted();
|
|
16
|
+
}
|
|
17
|
+
if (response.status !== 401 || data.error !== 'invalid_token' || response.headers.get('www-authenticate') !== 'Bearer error="invalid_token"') {
|
|
18
|
+
throw new CliError('UNAVAILABLE', 'The platform gateway did not return the expected token rejection.', 'Check LINKWISE_ISSUER and ask the platform administrator to check this CLI gateway route.', response.status >= 500 || response.status === 429, details);
|
|
19
|
+
}
|
|
20
|
+
return { reachable: true, gatewayProtected: true, clientId: config.clientId, authenticated: false,
|
|
21
|
+
endpoints: { issuer: config.baseUrl, deviceAuthorization: config.deviceEndpoint, token: config.tokenEndpoint, revocation: config.revokeEndpoint, business } };
|
|
22
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { IdentityPort } from '../cli/index.js';
|
|
2
|
+
export interface AuthorizationModule {
|
|
3
|
+
id: string;
|
|
4
|
+
create(clientId: string | undefined, env: NodeJS.ProcessEnv): IdentityPort;
|
|
5
|
+
}
|
|
6
|
+
export declare const cliAuthorization: AuthorizationModule;
|
|
7
|
+
export declare function createAuthorization({ modules, active, defaults, env }?: {
|
|
8
|
+
modules?: readonly AuthorizationModule[];
|
|
9
|
+
active?: string;
|
|
10
|
+
defaults?: NodeJS.ProcessEnv;
|
|
11
|
+
env?: NodeJS.ProcessEnv;
|
|
12
|
+
}): (clientId?: string) => IdentityPort;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { CliError } from '../cli/index.js';
|
|
2
|
+
import { Identity } from './identity.js';
|
|
3
|
+
import { authConfig, OAuthProvider } from './provider.js';
|
|
4
|
+
import { FileSessionStore } from './store.js';
|
|
5
|
+
import { inspectAuthorization } from './inspection.js';
|
|
6
|
+
import { deploymentDefaults } from '../cli/deployment.js';
|
|
7
|
+
export const cliAuthorization = {
|
|
8
|
+
id: 'cli',
|
|
9
|
+
create(clientId, env) {
|
|
10
|
+
const config = authConfig(env, clientId ?? env.LXZ_AUTH_CLIENT_ID);
|
|
11
|
+
const store = new FileSessionStore(`${config.baseUrl}\n${config.clientId}`, env.LXZ_STATE_DIR);
|
|
12
|
+
return Object.assign(new Identity(new OAuthProvider(config), store, config.baseUrl, config.clientId), {
|
|
13
|
+
inspect: (signal) => inspectAuthorization(config, signal),
|
|
14
|
+
});
|
|
15
|
+
},
|
|
16
|
+
};
|
|
17
|
+
export function createAuthorization({ modules = [cliAuthorization], active, defaults = {}, env = process.env } = {}) {
|
|
18
|
+
const selected = active ?? env.LXZ_AUTH_MODULE ?? defaults.LXZ_AUTH_MODULE ?? 'cli';
|
|
19
|
+
const matches = modules.filter((module) => module.id === selected);
|
|
20
|
+
return (clientId) => {
|
|
21
|
+
if (matches.length !== 1)
|
|
22
|
+
throw new CliError('CONFIGURATION', 'The authorization module is not configured correctly.', 'Ask the CLI maintainer to check enabled authorization modules.');
|
|
23
|
+
return matches[0].create(clientId, { ...deploymentDefaults, ...defaults, ...env });
|
|
24
|
+
};
|
|
25
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** Where the platform is reachable: the issuer origin first, then a fallback root serving the same paths. */
|
|
2
|
+
export interface PlatformSite {
|
|
3
|
+
roots: readonly string[];
|
|
4
|
+
stateDirectory?: string;
|
|
5
|
+
}
|
|
6
|
+
export declare function platformSite(env?: NodeJS.ProcessEnv): PlatformSite;
|
|
7
|
+
/** The path of target under the root that reference was sent to. */
|
|
8
|
+
export declare function atRootOf(target: string, reference: string, site: PlatformSite): string;
|
|
9
|
+
/**
|
|
10
|
+
* Sends a request to the platform. When a root cannot be reached (no connection, or HTTP 502/504 from a proxy) the request is sent
|
|
11
|
+
* at the other root; a request that may already have been delivered (lost connection, 504) only when replay is allowed.
|
|
12
|
+
* Once the fallback answers for an unreachable primary, it goes first for 10 minutes and log is told. URLs outside the platform are sent as they are.
|
|
13
|
+
*/
|
|
14
|
+
export declare function platformExchange(url: string | URL, init: RequestInit, { site, replay, log }: {
|
|
15
|
+
site: PlatformSite;
|
|
16
|
+
replay?: boolean;
|
|
17
|
+
log?: (message: string) => void;
|
|
18
|
+
}): Promise<{
|
|
19
|
+
response: Response;
|
|
20
|
+
url: string;
|
|
21
|
+
}>;
|
|
22
|
+
/** Sends a request to the platform of env (LINKWISE_ISSUER), using the fallback address while the primary cannot be reached. */
|
|
23
|
+
export declare function platformRequest(url: string | URL, init?: RequestInit, { env, replay }?: {
|
|
24
|
+
env?: NodeJS.ProcessEnv;
|
|
25
|
+
replay?: boolean;
|
|
26
|
+
}): Promise<Response>;
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
import { CliError, request, secureUrl } from '../cli/index.js';
|
|
5
|
+
import { deploymentDefaults, deploymentFallbacks } from '../cli/deployment.js';
|
|
6
|
+
import { stateDirectory } from './store.js';
|
|
7
|
+
const FALLBACK_FIRST_MS = 10 * 60 * 1000;
|
|
8
|
+
/** Failures before anything is sent: name resolution, refused or timed-out connections, TLS. */
|
|
9
|
+
const NOT_CONNECTED = new Set(['ENOTFOUND', 'EAI_AGAIN', 'ECONNREFUSED', 'EHOSTUNREACH', 'ENETUNREACH', 'UND_ERR_CONNECT_TIMEOUT',
|
|
10
|
+
'CERT_HAS_EXPIRED', 'ERR_TLS_CERT_ALTNAME_INVALID', 'UNABLE_TO_VERIFY_LEAF_SIGNATURE', 'DEPTH_ZERO_SELF_SIGNED_CERT', 'SELF_SIGNED_CERT_IN_CHAIN', 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY']);
|
|
11
|
+
/** Connections lost after the request may have been delivered. */
|
|
12
|
+
const DISCONNECTED = new Set(['ECONNRESET', 'EPIPE', 'UND_ERR_SOCKET']);
|
|
13
|
+
export function platformSite(env = process.env) {
|
|
14
|
+
const issuer = env.LINKWISE_ISSUER ?? deploymentDefaults.LINKWISE_ISSUER;
|
|
15
|
+
const allowHttp = /^http:/i.test(issuer.trim());
|
|
16
|
+
const origin = secureUrl(issuer, 'Authorization service URL', { allowHttp }).origin;
|
|
17
|
+
const fallback = env.LINKWISE_FALLBACK_URL ?? deploymentFallbacks[origin];
|
|
18
|
+
const roots = fallback ? [origin, secureUrl(fallback, 'Fallback service URL', { allowHttp }).href.replace(/\/+$/, '')] : [origin];
|
|
19
|
+
return { roots, stateDirectory: env.LXZ_STATE_DIR };
|
|
20
|
+
}
|
|
21
|
+
/** The path of target under the root that reference was sent to. */
|
|
22
|
+
export function atRootOf(target, reference, site) {
|
|
23
|
+
const from = rootOf(target, site);
|
|
24
|
+
const to = rootOf(reference, site);
|
|
25
|
+
return from === undefined || to === undefined ? target : to + target.slice(from.length);
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Sends a request to the platform. When a root cannot be reached (no connection, or HTTP 502/504 from a proxy) the request is sent
|
|
29
|
+
* at the other root; a request that may already have been delivered (lost connection, 504) only when replay is allowed.
|
|
30
|
+
* Once the fallback answers for an unreachable primary, it goes first for 10 minutes and log is told. URLs outside the platform are sent as they are.
|
|
31
|
+
*/
|
|
32
|
+
export async function platformExchange(url, init, { site, replay = true, log = notice }) {
|
|
33
|
+
const target = String(url);
|
|
34
|
+
const root = rootOf(target, site);
|
|
35
|
+
if (root === undefined || site.roots.length < 2)
|
|
36
|
+
return { response: await request(target, init), url: target };
|
|
37
|
+
const [primary, fallback] = site.roots;
|
|
38
|
+
const marker = join(stateDirectory(site.stateDirectory), `platform-${createHash('sha256').update(primary).digest('hex').slice(0, 16)}.json`);
|
|
39
|
+
const order = await fallbackFirst(marker) ? [fallback, primary] : [primary, fallback];
|
|
40
|
+
for (const [index, base] of order.entries()) {
|
|
41
|
+
const attempt = base + target.slice(root.length);
|
|
42
|
+
const last = index === order.length - 1;
|
|
43
|
+
let response;
|
|
44
|
+
try {
|
|
45
|
+
response = await request(attempt, init);
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
init.signal?.throwIfAborted();
|
|
49
|
+
if (last || !unreachable(error, replay))
|
|
50
|
+
throw error;
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
if (!last && unreachable(response.status, replay)) {
|
|
54
|
+
await response.body?.cancel();
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
if (index > 0 && !unreachable(response.status, replay)) {
|
|
58
|
+
await setFallbackFirst(marker, base === fallback ? Date.now() + FALLBACK_FIRST_MS : 0);
|
|
59
|
+
if (base === fallback)
|
|
60
|
+
log(`The primary platform address is unreachable; using the fallback address ${fallback} for the next 10 minutes.`);
|
|
61
|
+
}
|
|
62
|
+
return { response, url: attempt };
|
|
63
|
+
}
|
|
64
|
+
throw new CliError('INTERNAL', 'No platform address was tried.', 'Contact the lxz maintainer.');
|
|
65
|
+
}
|
|
66
|
+
/** Sends a request to the platform of env (LINKWISE_ISSUER), using the fallback address while the primary cannot be reached. */
|
|
67
|
+
export async function platformRequest(url, init = {}, { env, replay } = {}) {
|
|
68
|
+
return (await platformExchange(url, init, { site: platformSite(env), replay })).response;
|
|
69
|
+
}
|
|
70
|
+
function rootOf(url, site) {
|
|
71
|
+
return [...site.roots].sort((a, b) => b.length - a.length).find(root => url === root || url.startsWith(root + '/') || url.startsWith(root + '?'));
|
|
72
|
+
}
|
|
73
|
+
function unreachable(outcome, replay) {
|
|
74
|
+
if (typeof outcome === 'number')
|
|
75
|
+
return outcome === 502 || (replay && outcome === 504);
|
|
76
|
+
if (!(outcome instanceof CliError) || outcome.code !== 'UNAVAILABLE')
|
|
77
|
+
return false;
|
|
78
|
+
let cause = outcome.cause;
|
|
79
|
+
while (cause && typeof cause.code !== 'string')
|
|
80
|
+
cause = cause.cause;
|
|
81
|
+
const code = cause?.code;
|
|
82
|
+
return code !== undefined && (NOT_CONNECTED.has(code) || (replay && DISCONNECTED.has(code)));
|
|
83
|
+
}
|
|
84
|
+
async function fallbackFirst(marker) {
|
|
85
|
+
try {
|
|
86
|
+
return Number(JSON.parse(await readFile(marker, 'utf8')).until) > Date.now();
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
async function setFallbackFirst(marker, until) {
|
|
93
|
+
// The marker only saves waiting for an unreachable primary; when it cannot be written, the next request tries the primary again.
|
|
94
|
+
try {
|
|
95
|
+
await mkdir(dirname(marker), { recursive: true, mode: 0o700 });
|
|
96
|
+
await writeFile(marker, JSON.stringify({ until }), { mode: 0o600 });
|
|
97
|
+
}
|
|
98
|
+
catch { /* ignored */ }
|
|
99
|
+
}
|
|
100
|
+
function notice(message) {
|
|
101
|
+
process.stderr.write(message + '\n');
|
|
102
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { IdentityPort } from '../cli/index.js';
|
|
2
|
+
export type AuthorizationRequest = {
|
|
3
|
+
clientId?: string;
|
|
4
|
+
} & ({
|
|
5
|
+
operation: 'status' | 'logout' | 'inspect';
|
|
6
|
+
} | {
|
|
7
|
+
operation: 'login';
|
|
8
|
+
interactive: boolean;
|
|
9
|
+
allowDeviceLogin?: boolean;
|
|
10
|
+
browser?: boolean;
|
|
11
|
+
} | {
|
|
12
|
+
operation: 'credential';
|
|
13
|
+
options?: Parameters<IdentityPort['credential']>[1];
|
|
14
|
+
} | {
|
|
15
|
+
operation: 'invalidate';
|
|
16
|
+
rejectedToken: string;
|
|
17
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { Context } from '../cli/index.js';
|
|
2
|
+
import { openBrowser } from '../cli/browser.js';
|
|
3
|
+
import type { PlatformSite } from './platform.js';
|
|
4
|
+
export interface AuthConfig {
|
|
5
|
+
baseUrl: string;
|
|
6
|
+
clientId: string;
|
|
7
|
+
deviceEndpoint: string;
|
|
8
|
+
tokenEndpoint: string;
|
|
9
|
+
revokeEndpoint: string;
|
|
10
|
+
allowHttp: boolean;
|
|
11
|
+
stateDirectory?: string;
|
|
12
|
+
/** Addresses the endpoints are also served at; without it requests go only to baseUrl. */
|
|
13
|
+
site?: PlatformSite;
|
|
14
|
+
}
|
|
15
|
+
export interface TokenSet {
|
|
16
|
+
account?: string;
|
|
17
|
+
loginName?: string;
|
|
18
|
+
displayName?: string;
|
|
19
|
+
accessToken: string;
|
|
20
|
+
accessExpiresAt: number;
|
|
21
|
+
refreshToken: string;
|
|
22
|
+
refreshExpiresAt: number;
|
|
23
|
+
}
|
|
24
|
+
export interface AuthProvider {
|
|
25
|
+
login(context: Context): Promise<TokenSet>;
|
|
26
|
+
refresh(refreshToken: string, signal: AbortSignal): Promise<TokenSet>;
|
|
27
|
+
revoke(refreshToken: string, signal: AbortSignal): Promise<void>;
|
|
28
|
+
}
|
|
29
|
+
export declare function authConfig(env?: NodeJS.ProcessEnv, clientId?: string | undefined): AuthConfig;
|
|
30
|
+
export declare class OAuthProvider implements AuthProvider {
|
|
31
|
+
readonly config: AuthConfig;
|
|
32
|
+
private readonly browser;
|
|
33
|
+
constructor(config: AuthConfig, browser?: typeof openBrowser);
|
|
34
|
+
private exchange;
|
|
35
|
+
private send;
|
|
36
|
+
private post;
|
|
37
|
+
login(context: Context): Promise<TokenSet>;
|
|
38
|
+
refresh(refreshToken: string, signal: AbortSignal): Promise<TokenSet>;
|
|
39
|
+
revoke(refreshToken: string, signal: AbortSignal): Promise<void>;
|
|
40
|
+
}
|