@tulcn/lxz 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/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 +9 -0
- package/dist/auth/index.js +12 -0
- package/dist/auth/inspection.d.ts +14 -0
- package/dist/auth/inspection.js +20 -0
- package/dist/auth/modules.d.ts +12 -0
- package/dist/auth/modules.js +25 -0
- package/dist/auth/protocol.d.ts +17 -0
- package/dist/auth/protocol.js +1 -0
- package/dist/auth/provider.d.ts +36 -0
- package/dist/auth/provider.js +166 -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 +71 -0
- package/dist/auth/store.d.ts +25 -0
- package/dist/auth/store.js +170 -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 +5 -0
- package/dist/cli/deployment.js +23 -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` 设为管理员提供的地址;各环境的登记、授权和令牌互不通用。
|
|
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,9 @@
|
|
|
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 './modules.js';
|
|
7
|
+
export * from './inspection.js';
|
|
8
|
+
export * from './client.js';
|
|
9
|
+
export declare function defaultIdentity(clientId?: string): import("../cli/init.js").IdentityPort;
|
|
@@ -0,0 +1,12 @@
|
|
|
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 './modules.js';
|
|
8
|
+
export * from './inspection.js';
|
|
9
|
+
export * from './client.js';
|
|
10
|
+
export function defaultIdentity(clientId) {
|
|
11
|
+
return createAuthorization()(clientId);
|
|
12
|
+
}
|
|
@@ -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,20 @@
|
|
|
1
|
+
import { CliError, readJson, request } from '../cli/index.js';
|
|
2
|
+
import { gatewayAddress } from './gateway.js';
|
|
3
|
+
export async function inspectAuthorization(config, signal) {
|
|
4
|
+
const business = gatewayAddress(config.clientId, { LINKWISE_ISSUER: config.baseUrl });
|
|
5
|
+
const response = await request(business + '/', { signal });
|
|
6
|
+
const requestId = response.headers.get('x-request-id');
|
|
7
|
+
const details = { status: response.status, ...(requestId ? { requestId } : {}) };
|
|
8
|
+
let data = {};
|
|
9
|
+
try {
|
|
10
|
+
data = await readJson(response);
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
signal.throwIfAborted();
|
|
14
|
+
}
|
|
15
|
+
if (response.status !== 401 || data.error !== 'invalid_token' || response.headers.get('www-authenticate') !== 'Bearer error="invalid_token"') {
|
|
16
|
+
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);
|
|
17
|
+
}
|
|
18
|
+
return { reachable: true, gatewayProtected: true, clientId: config.clientId, authenticated: false,
|
|
19
|
+
endpoints: { issuer: config.baseUrl, deviceAuthorization: config.deviceEndpoint, token: config.tokenEndpoint, revocation: config.revokeEndpoint, business } };
|
|
20
|
+
}
|
|
@@ -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,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,36 @@
|
|
|
1
|
+
import type { Context } from '../cli/index.js';
|
|
2
|
+
import { openBrowser } from '../cli/browser.js';
|
|
3
|
+
export interface AuthConfig {
|
|
4
|
+
baseUrl: string;
|
|
5
|
+
clientId: string;
|
|
6
|
+
deviceEndpoint: string;
|
|
7
|
+
tokenEndpoint: string;
|
|
8
|
+
revokeEndpoint: string;
|
|
9
|
+
allowHttp: boolean;
|
|
10
|
+
stateDirectory?: string;
|
|
11
|
+
}
|
|
12
|
+
export interface TokenSet {
|
|
13
|
+
account?: string;
|
|
14
|
+
loginName?: string;
|
|
15
|
+
displayName?: string;
|
|
16
|
+
accessToken: string;
|
|
17
|
+
accessExpiresAt: number;
|
|
18
|
+
refreshToken: string;
|
|
19
|
+
refreshExpiresAt: number;
|
|
20
|
+
}
|
|
21
|
+
export interface AuthProvider {
|
|
22
|
+
login(context: Context): Promise<TokenSet>;
|
|
23
|
+
refresh(refreshToken: string, signal: AbortSignal): Promise<TokenSet>;
|
|
24
|
+
revoke(refreshToken: string, signal: AbortSignal): Promise<void>;
|
|
25
|
+
}
|
|
26
|
+
export declare function authConfig(env?: NodeJS.ProcessEnv, clientId?: string | undefined): AuthConfig;
|
|
27
|
+
export declare class OAuthProvider implements AuthProvider {
|
|
28
|
+
readonly config: AuthConfig;
|
|
29
|
+
private readonly browser;
|
|
30
|
+
constructor(config: AuthConfig, browser?: typeof openBrowser);
|
|
31
|
+
private send;
|
|
32
|
+
private post;
|
|
33
|
+
login(context: Context): Promise<TokenSet>;
|
|
34
|
+
refresh(refreshToken: string, signal: AbortSignal): Promise<TokenSet>;
|
|
35
|
+
revoke(refreshToken: string, signal: AbortSignal): Promise<void>;
|
|
36
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
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
|
+
function text(data, name) {
|
|
11
|
+
if (typeof data[name] === 'string' && data[name])
|
|
12
|
+
return data[name];
|
|
13
|
+
throw new CliError('UNAVAILABLE', 'The authorization service returned incomplete data.', 'Retry later; if it still fails, contact the authorization service maintainer.', true);
|
|
14
|
+
}
|
|
15
|
+
function tokenClaims(token) {
|
|
16
|
+
try {
|
|
17
|
+
const parts = token.split('.');
|
|
18
|
+
if (parts.length !== 3)
|
|
19
|
+
return {};
|
|
20
|
+
const claims = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));
|
|
21
|
+
return claims && typeof claims === 'object' && !Array.isArray(claims) ? claims : {};
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return {};
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function tokenExpiration(claims, seconds, now) {
|
|
28
|
+
const expiration = typeof claims.exp === 'number' && Number.isFinite(claims.exp) ? claims.exp * 1000 : now + Number(seconds) * 1000;
|
|
29
|
+
if (!Number.isFinite(expiration))
|
|
30
|
+
throw new CliError('UNAVAILABLE', 'The authorization service returned no usable token expiration.', 'Retry later; if it still fails, contact the authorization service maintainer.');
|
|
31
|
+
return expiration;
|
|
32
|
+
}
|
|
33
|
+
function tokens(data) {
|
|
34
|
+
const accessToken = text(data, 'access_token');
|
|
35
|
+
const refreshToken = text(data, 'refresh_token');
|
|
36
|
+
if (data.token_type !== 'Bearer')
|
|
37
|
+
throw new CliError('UNAVAILABLE', 'The authorization service returned invalid credentials.', 'Retry later; if it still fails, contact the authorization service maintainer.');
|
|
38
|
+
// The gateway validates signatures; decoded claims guide local expiry and display.
|
|
39
|
+
const claims = tokenClaims(accessToken);
|
|
40
|
+
const now = Date.now();
|
|
41
|
+
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) };
|
|
42
|
+
}
|
|
43
|
+
export function authConfig(env = process.env, clientId = env.LXZ_AUTH_CLIENT_ID) {
|
|
44
|
+
const issuer = env.LINKWISE_ISSUER ?? deploymentDefaults.LINKWISE_ISSUER;
|
|
45
|
+
if (!issuer || !clientId)
|
|
46
|
+
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.');
|
|
47
|
+
const allowHttp = /^http:/i.test(issuer.trim());
|
|
48
|
+
const baseUrl = secureUrl(issuer, 'Authorization service URL', { allowHttp }).href.replace(/\/$/, '');
|
|
49
|
+
return { baseUrl, clientId, allowHttp, stateDirectory: env.LXZ_STATE_DIR, deviceEndpoint: `${baseUrl}/oauth2/device_authorization`, tokenEndpoint: `${baseUrl}/oauth2/token`, revokeEndpoint: `${baseUrl}/oauth2/revoke` };
|
|
50
|
+
}
|
|
51
|
+
export class OAuthProvider {
|
|
52
|
+
config;
|
|
53
|
+
browser;
|
|
54
|
+
constructor(config, browser = openBrowser) {
|
|
55
|
+
this.config = config;
|
|
56
|
+
this.browser = browser;
|
|
57
|
+
}
|
|
58
|
+
send(endpoint, values, signal) {
|
|
59
|
+
return request(endpoint, { method: 'POST', headers: { 'x-request-id': randomUUID() }, body: new URLSearchParams({ client_id: this.config.clientId, ...values }), signal });
|
|
60
|
+
}
|
|
61
|
+
async post(endpoint, values, signal) {
|
|
62
|
+
const response = await this.send(endpoint, values, signal);
|
|
63
|
+
const data = await readJson(response);
|
|
64
|
+
return { response, data };
|
|
65
|
+
}
|
|
66
|
+
async login(context) {
|
|
67
|
+
if (!context.interactive && !context.allowDeviceLogin)
|
|
68
|
+
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.');
|
|
69
|
+
const os = { win32: 'Windows', darwin: 'macOS', linux: 'Linux' }[platform()] ?? platform();
|
|
70
|
+
const deviceId = await new FileSessionStore(`${this.config.baseUrl}\n${this.config.clientId}`, this.config.stateDirectory).deviceId(context.signal);
|
|
71
|
+
const device = await this.post(this.config.deviceEndpoint, { client_os: os, device_id: deviceId }, context.signal);
|
|
72
|
+
if (!device.response.ok)
|
|
73
|
+
throw backendError(device.response, device.data);
|
|
74
|
+
const verification = text(device.data, 'verification_uri_complete');
|
|
75
|
+
secureUrl(verification, 'Authorization approval URL', { allowHttp: this.config.allowHttp, allowQuery: true });
|
|
76
|
+
const code = text(device.data, 'user_code');
|
|
77
|
+
const deviceCode = text(device.data, 'device_code');
|
|
78
|
+
const expires = device.data.expires_in;
|
|
79
|
+
let interval = Number(device.data.interval ?? 5);
|
|
80
|
+
if (!Number.isInteger(expires) || Number(expires) <= 0 || !Number.isInteger(interval) || interval <= 0)
|
|
81
|
+
throw new CliError('UNAVAILABLE', 'The authorization link has an invalid lifetime.', 'Retry later; if it still fails, contact the authorization service maintainer.');
|
|
82
|
+
const deadline = Date.now() + Number(expires) * 1000;
|
|
83
|
+
context.log(`${authorizationPrompt(verification, code)}\nSign in using a browser, check the user code and approve. This command will wait for authorization.`);
|
|
84
|
+
const deviceExpiry = AbortSignal.timeout(Number(expires) * 1000);
|
|
85
|
+
if (context.browser !== false && !await this.browser(verification, AbortSignal.any([context.signal, deviceExpiry])))
|
|
86
|
+
context.log('Could not open a browser. Open the authorization URL above manually.');
|
|
87
|
+
while (Date.now() < deadline) {
|
|
88
|
+
try {
|
|
89
|
+
await delay(Math.min(interval * 1000, Math.max(0, deadline - Date.now())), undefined, { signal: context.signal });
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
context.signal.throwIfAborted();
|
|
93
|
+
throw error;
|
|
94
|
+
}
|
|
95
|
+
if (Date.now() >= deadline)
|
|
96
|
+
break;
|
|
97
|
+
const remaining = AbortSignal.timeout(Math.max(1, deadline - Date.now()));
|
|
98
|
+
let response;
|
|
99
|
+
try {
|
|
100
|
+
response = await this.send(this.config.tokenEndpoint, { device_code: deviceCode, grant_type: 'urn:ietf:params:oauth:grant-type:device_code' }, AbortSignal.any([context.signal, remaining]));
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
context.signal.throwIfAborted();
|
|
104
|
+
if (remaining.aborted)
|
|
105
|
+
break;
|
|
106
|
+
if (!(error instanceof CliError) || !['UNAVAILABLE', 'TIMEOUT'].includes(error.code))
|
|
107
|
+
throw error;
|
|
108
|
+
context.log('Cannot reach the authorization service; waiting while the user code remains valid.');
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
if (response.status === 429) {
|
|
112
|
+
await response.body?.cancel();
|
|
113
|
+
interval += 5;
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
if (response.status >= 500) {
|
|
117
|
+
await response.body?.cancel();
|
|
118
|
+
context.log('Authorization service is temporarily unavailable; waiting while the user code remains valid.');
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
let data;
|
|
122
|
+
try {
|
|
123
|
+
data = await readJson(response);
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
context.signal.throwIfAborted();
|
|
127
|
+
if (remaining.aborted)
|
|
128
|
+
break;
|
|
129
|
+
if (!(error instanceof CliError) || !(error.cause instanceof Error) || !['TypeError', 'AbortError', 'TimeoutError'].includes(error.cause.name))
|
|
130
|
+
throw error;
|
|
131
|
+
context.log('Authorization response was interrupted; waiting while the user code remains valid.');
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
if (data.error === 'authorization_pending')
|
|
135
|
+
continue;
|
|
136
|
+
if (data.error === 'slow_down') {
|
|
137
|
+
interval += 5;
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
if (!response.ok)
|
|
141
|
+
throw backendError(response, data, [deviceCode]);
|
|
142
|
+
return tokens(data);
|
|
143
|
+
}
|
|
144
|
+
throw new CliError('AUTH_EXPIRED', 'The user code has expired.', 'Run init or login again to request a new user code.');
|
|
145
|
+
}
|
|
146
|
+
async refresh(refreshToken, signal) {
|
|
147
|
+
const { response, data } = await this.post(this.config.tokenEndpoint, { grant_type: 'refresh_token', refresh_token: refreshToken }, signal);
|
|
148
|
+
if (!response.ok)
|
|
149
|
+
throw backendError(response, data, [refreshToken]);
|
|
150
|
+
return tokens(data);
|
|
151
|
+
}
|
|
152
|
+
async revoke(refreshToken, signal) {
|
|
153
|
+
const response = await this.send(this.config.revokeEndpoint, { token: refreshToken, token_type_hint: 'refresh_token' }, AbortSignal.any([signal, AbortSignal.timeout(10000)]));
|
|
154
|
+
if (response.status !== 200) {
|
|
155
|
+
let data = {};
|
|
156
|
+
try {
|
|
157
|
+
data = await readJson(response);
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
signal.throwIfAborted();
|
|
161
|
+
}
|
|
162
|
+
throw backendError(response, data, [refreshToken]);
|
|
163
|
+
}
|
|
164
|
+
await response.body?.cancel();
|
|
165
|
+
}
|
|
166
|
+
}
|