@seavideo/cli 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.
Files changed (110) hide show
  1. package/LICENSE +12 -0
  2. package/README.md +528 -2
  3. package/dist/bin/seavideo.js +11 -0
  4. package/dist/src/atomic-write.js +14 -0
  5. package/dist/src/canvas/api.js +172 -0
  6. package/dist/src/canvas/browser.js +40 -0
  7. package/dist/src/canvas/chrome-binary.js +109 -0
  8. package/dist/src/canvas/daemon.js +264 -0
  9. package/dist/src/canvas/engine-install.js +46 -0
  10. package/dist/src/canvas/engine-log.js +9 -0
  11. package/dist/src/canvas/engine.js +99 -0
  12. package/dist/src/canvas/entry.js +16 -0
  13. package/dist/src/canvas/env-lock.js +164 -0
  14. package/dist/src/canvas/launch.js +97 -0
  15. package/dist/src/canvas/lifecycle.js +65 -0
  16. package/dist/src/canvas/names.js +61 -0
  17. package/dist/src/canvas/params.js +38 -0
  18. package/dist/src/canvas/puppeteer.js +153 -0
  19. package/dist/src/canvas/screenshot.js +23 -0
  20. package/dist/src/canvas/session-record.js +77 -0
  21. package/dist/src/canvas/team.js +97 -0
  22. package/dist/src/canvas/tool-args.js +47 -0
  23. package/dist/src/canvas/tool-session.js +165 -0
  24. package/dist/src/canvas/tool-specs.js +54 -0
  25. package/dist/src/canvas/url.js +38 -0
  26. package/dist/src/cli/args.js +16 -0
  27. package/dist/src/cli/commands/auth.js +51 -0
  28. package/dist/src/cli/commands/canvas/common.js +31 -0
  29. package/dist/src/cli/commands/canvas/engine-choice.js +41 -0
  30. package/dist/src/cli/commands/canvas/index.js +5 -0
  31. package/dist/src/cli/commands/canvas/item.js +233 -0
  32. package/dist/src/cli/commands/canvas/list.js +168 -0
  33. package/dist/src/cli/commands/canvas/register.js +106 -0
  34. package/dist/src/cli/commands/canvas/render.js +229 -0
  35. package/dist/src/cli/commands/canvas/screenshot.js +52 -0
  36. package/dist/src/cli/commands/canvas/session.js +249 -0
  37. package/dist/src/cli/commands/canvas/teams.js +142 -0
  38. package/dist/src/cli/commands/config.js +74 -0
  39. package/dist/src/cli/commands/doctor.js +261 -0
  40. package/dist/src/cli/commands/engine.js +96 -0
  41. package/dist/src/cli/commands/env/create.js +160 -0
  42. package/dist/src/cli/commands/env/fields.js +26 -0
  43. package/dist/src/cli/commands/env/index.js +4 -0
  44. package/dist/src/cli/commands/env/list.js +44 -0
  45. package/dist/src/cli/commands/env/mutate.js +118 -0
  46. package/dist/src/cli/commands/login/flow-token.js +41 -0
  47. package/dist/src/cli/commands/login/index.js +12 -0
  48. package/dist/src/cli/commands/login/oauth.js +69 -0
  49. package/dist/src/cli/commands/login/save.js +26 -0
  50. package/dist/src/cli/commands/logout.js +92 -0
  51. package/dist/src/cli/commands/skill.js +185 -0
  52. package/dist/src/cli/commands/tool.js +279 -0
  53. package/dist/src/cli/commands/update.js +117 -0
  54. package/dist/src/cli/commands/wallet.js +69 -0
  55. package/dist/src/cli/commands/whoami.js +147 -0
  56. package/dist/src/cli/context.js +41 -0
  57. package/dist/src/cli/credential.js +93 -0
  58. package/dist/src/cli/elapsed.js +25 -0
  59. package/dist/src/cli/failure-screenshot.js +24 -0
  60. package/dist/src/cli/flags.js +1 -0
  61. package/dist/src/cli/hints.js +7 -0
  62. package/dist/src/cli/main.js +44 -0
  63. package/dist/src/cli/output-error.js +23 -0
  64. package/dist/src/cli/output.js +47 -0
  65. package/dist/src/cli/program.js +261 -0
  66. package/dist/src/cli/run.js +11 -0
  67. package/dist/src/cli/session.js +63 -0
  68. package/dist/src/config/base-url.js +26 -0
  69. package/dist/src/config/credential-vault.js +115 -0
  70. package/dist/src/config/dotenv.js +59 -0
  71. package/dist/src/config/envname.js +41 -0
  72. package/dist/src/config/paths.js +22 -0
  73. package/dist/src/config/preset-schema.js +67 -0
  74. package/dist/src/config/presets.js +132 -0
  75. package/dist/src/config/resolve.js +41 -0
  76. package/dist/src/config/secret-key.js +63 -0
  77. package/dist/src/config/store-schema.js +143 -0
  78. package/dist/src/config/store.js +273 -0
  79. package/dist/src/config/vault-crypto.js +44 -0
  80. package/dist/src/deps.js +191 -0
  81. package/dist/src/deps.types.js +1 -0
  82. package/dist/src/errors.js +24 -0
  83. package/dist/src/fs-retry.js +34 -0
  84. package/dist/src/i18n.js +1214 -0
  85. package/dist/src/loopback.js +134 -0
  86. package/dist/src/sdk/auth.js +20 -0
  87. package/dist/src/sdk/credential-expiry.js +67 -0
  88. package/dist/src/sdk/discovery.js +90 -0
  89. package/dist/src/sdk/http.js +98 -0
  90. package/dist/src/sdk/identity.js +17 -0
  91. package/dist/src/sdk/jwks.js +119 -0
  92. package/dist/src/sdk/oauth-protocol.js +226 -0
  93. package/dist/src/sdk/oauth.js +179 -0
  94. package/dist/src/sdk/provider/cn.js +34 -0
  95. package/dist/src/sdk/provider/index.js +16 -0
  96. package/dist/src/sdk/provider/oversea.js +41 -0
  97. package/dist/src/sdk/provider/types.js +1 -0
  98. package/dist/src/sdk/refresh.js +66 -0
  99. package/dist/src/semver.js +89 -0
  100. package/dist/src/skill/api.js +176 -0
  101. package/dist/src/text.js +3 -0
  102. package/dist/src/types.js +1 -0
  103. package/dist/src/update/check-cache.js +56 -0
  104. package/dist/src/update/install-layout.js +79 -0
  105. package/dist/src/update/notify.js +15 -0
  106. package/dist/src/update/npm-install.js +64 -0
  107. package/dist/src/update/passive.js +53 -0
  108. package/dist/src/update/registry.js +59 -0
  109. package/dist/src/wallet/api.js +107 -0
  110. package/package.json +67 -4
@@ -0,0 +1,226 @@
1
+ import { CliError } from "../errors.js";
2
+ import { t } from "../i18n.js";
3
+ import { safeErrorText } from "./http.js";
4
+ export const CALLBACK_PATH = '/oauth2/callback';
5
+ export const COMPLETION_PATH = '/oauth2/desktop/success';
6
+ export const DEFAULT_LOGIN_TIMEOUT_MS = 300_000;
7
+ function base64url(raw) {
8
+ return raw.toString('base64url');
9
+ }
10
+ export async function createPkce(randomBytes) {
11
+ const verifier = base64url(randomBytes(32));
12
+ const digest = await digestSha256(verifier);
13
+ return { verifier, challenge: base64url(digest) };
14
+ }
15
+ async function digestSha256(text) {
16
+ const data = new TextEncoder().encode(text);
17
+ const hash = await globalThis.crypto.subtle.digest('SHA-256', data);
18
+ return Buffer.from(hash);
19
+ }
20
+ export function buildAuthorizeUrl(input) {
21
+ const query = [
22
+ ['client_id', input.clientId],
23
+ ['response_type', 'code'],
24
+ ['scope', 'openid offline_access'],
25
+ ['redirect_uri', input.redirectUri],
26
+ ['state', input.state],
27
+ ['nonce', input.nonce],
28
+ ['code_challenge', input.challenge],
29
+ ['code_challenge_method', 'S256'],
30
+ ];
31
+ if (input.promptLogin)
32
+ query.push(['prompt', 'login']);
33
+ else {
34
+ }
35
+ const encoded = query.map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join('&');
36
+ const base = input.authorizationEndpoint ?? `${trimSlash(input.issuer)}/oauth2/authorize`;
37
+ const sep = base.includes('?') ? '&' : '?';
38
+ return `${base}${sep}${encoded}`;
39
+ }
40
+ function trimSlash(value) {
41
+ return value.replace(/\/+$/, '');
42
+ }
43
+ export function parseIssuer(value, kind, envMap = process.env) {
44
+ let url;
45
+ try {
46
+ url = new URL(value);
47
+ }
48
+ catch {
49
+ throw new CliError(kind, t('oauth.badIssuer', { value }, envMap), {
50
+ detail: t('oauth.badIssuerDetail', {}, envMap),
51
+ });
52
+ }
53
+ if (url.protocol !== 'https:') {
54
+ throw new CliError(kind, t('oauth.badIssuer', { value }, envMap), {
55
+ detail: t('oauth.badIssuerDetail', {}, envMap),
56
+ });
57
+ }
58
+ if (url.search !== '' || url.hash !== '' || url.username !== '' || url.password !== '') {
59
+ throw new CliError(kind, t('oauth.badIssuer', { value }, envMap), {
60
+ detail: t('oauth.badIssuerDetail', {}, envMap),
61
+ });
62
+ }
63
+ return trimSlash(url.href);
64
+ }
65
+ export function assertClientId(value, envMap = process.env) {
66
+ if (value === '' || /\s/.test(value)) {
67
+ throw new CliError('config', t('oauth.badClientId', {}, envMap));
68
+ }
69
+ return value;
70
+ }
71
+ export function decodeIdToken(token) {
72
+ const parts = token.split('.');
73
+ let result;
74
+ if (parts.length !== 3) {
75
+ result = null;
76
+ }
77
+ else {
78
+ let parsed;
79
+ try {
80
+ parsed = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));
81
+ }
82
+ catch {
83
+ parsed = null;
84
+ }
85
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
86
+ result = null;
87
+ }
88
+ else {
89
+ result = parsed;
90
+ }
91
+ }
92
+ return result;
93
+ }
94
+ export function checkIdTokenClaims(claims, expected) {
95
+ let result;
96
+ if (typeof claims.iss !== 'string' || typeof claims.exp !== 'number') {
97
+ result = { ok: false, reason: 'shape' };
98
+ }
99
+ else if (typeof claims.sub !== 'string' || claims.sub === '') {
100
+ result = { ok: false, reason: 'subject' };
101
+ }
102
+ else if (trimSlash(claims.iss) !== expected.issuer) {
103
+ result = { ok: false, reason: 'issuer' };
104
+ }
105
+ else if (!(Array.isArray(claims.aud) ? claims.aud : [claims.aud]).includes(expected.clientId)) {
106
+ result = { ok: false, reason: 'audience' };
107
+ }
108
+ else if (claims.exp <=
109
+ expected.nowSeconds - 30) {
110
+ result = { ok: false, reason: 'expired' };
111
+ }
112
+ else if (claims.nonce !== expected.nonce) {
113
+ result = { ok: false, reason: 'nonce' };
114
+ }
115
+ else {
116
+ result = { ok: true };
117
+ }
118
+ return result;
119
+ }
120
+ export function checkCompletionUri(raw, issuer) {
121
+ let result;
122
+ if (typeof raw !== 'string') {
123
+ result = null;
124
+ }
125
+ else {
126
+ let url;
127
+ try {
128
+ url = new URL(raw);
129
+ }
130
+ catch {
131
+ url = null;
132
+ }
133
+ if (url === null) {
134
+ result = null;
135
+ }
136
+ else {
137
+ const base = new URL(issuer);
138
+ const receipt = url.searchParams.get('receipt');
139
+ if (url.protocol !== 'https:' ||
140
+ url.hostname !== base.hostname ||
141
+ url.port !== base.port ||
142
+ url.pathname !== COMPLETION_PATH ||
143
+ url.hash !== '' ||
144
+ url.username !== '' ||
145
+ url.password !== '' ||
146
+ receipt === null ||
147
+ receipt === '') {
148
+ result = null;
149
+ }
150
+ else {
151
+ result = url.href;
152
+ }
153
+ }
154
+ }
155
+ return result;
156
+ }
157
+ export async function exchangeCode(deps, input) {
158
+ const url = input.tokenEndpoint;
159
+ const form = new URLSearchParams({
160
+ client_id: input.clientId,
161
+ grant_type: 'authorization_code',
162
+ code: input.code,
163
+ redirect_uri: input.redirectUri,
164
+ code_verifier: input.verifier,
165
+ });
166
+ let response;
167
+ try {
168
+ response = await deps.fetch(url, {
169
+ method: 'POST',
170
+ headers: {
171
+ accept: 'application/json',
172
+ 'content-type': 'application/x-www-form-urlencoded',
173
+ },
174
+ body: form.toString(),
175
+ });
176
+ }
177
+ catch (err) {
178
+ throw new CliError('network', t('oauth.tokenNetwork', { url }, deps.env), {
179
+ detail: safeErrorText(err),
180
+ });
181
+ }
182
+ let text;
183
+ try {
184
+ text = await response.text();
185
+ }
186
+ catch (err) {
187
+ throw new CliError('network', t('oauth.tokenReadFailed', {}, deps.env), {
188
+ detail: safeErrorText(err),
189
+ });
190
+ }
191
+ let payload;
192
+ try {
193
+ payload = text === '' ? undefined : JSON.parse(text);
194
+ }
195
+ catch {
196
+ throw new CliError('server', t('oauth.tokenNotJson', { status: response.status }, deps.env));
197
+ }
198
+ if (payload === null || typeof payload !== 'object' || Array.isArray(payload)) {
199
+ throw new CliError('server', t('oauth.tokenNotObject', { status: response.status }, deps.env));
200
+ }
201
+ const body = payload;
202
+ if (!response.ok) {
203
+ const code = typeof body['error'] === 'string' ? body['error'] : `HTTP ${response.status}`;
204
+ const description = body['error_description'];
205
+ throw new CliError(code === 'invalid_grant' ? 'auth' : 'server', t('oauth.tokenRejected', { error: code }, deps.env), { detail: typeof description === 'string' ? description : undefined });
206
+ }
207
+ else {
208
+ }
209
+ const accessToken = body['access_token'];
210
+ if (typeof accessToken !== 'string' || accessToken === '') {
211
+ throw new CliError('server', t('oauth.tokenNoAccessToken', {}, deps.env));
212
+ }
213
+ const idToken = body['id_token'];
214
+ if (typeof idToken !== 'string' || idToken === '') {
215
+ throw new CliError('server', t('oauth.tokenNoIdToken', {}, deps.env));
216
+ }
217
+ const refreshToken = body['refresh_token'];
218
+ const expiresIn = body['expires_in'];
219
+ return {
220
+ accessToken,
221
+ idToken,
222
+ refreshToken: typeof refreshToken === 'string' && refreshToken !== '' ? refreshToken : null,
223
+ expiresIn: typeof expiresIn === 'number' ? expiresIn : null,
224
+ completionUri: checkCompletionUri(body['desktop_completion_uri'], input.issuer),
225
+ };
226
+ }
@@ -0,0 +1,179 @@
1
+ import { CliError } from "../errors.js";
2
+ import { t } from "../i18n.js";
3
+ import { LOOPBACK_TIMEOUT } from "../loopback.js";
4
+ import { fetchDiscovery } from "./discovery.js";
5
+ import { fetchJwks, signatureErrorReason, verifyIdTokenSignature } from "./jwks.js";
6
+ import { CALLBACK_PATH, assertClientId, buildAuthorizeUrl, checkIdTokenClaims, createPkce, decodeIdToken, exchangeCode, parseIssuer, } from "./oauth-protocol.js";
7
+ export { CALLBACK_PATH, COMPLETION_PATH, DEFAULT_LOGIN_TIMEOUT_MS, assertClientId, buildAuthorizeUrl, checkCompletionUri, checkIdTokenClaims, createPkce, decodeIdToken, parseIssuer, } from "./oauth-protocol.js";
8
+ function base64url(raw) {
9
+ return raw.toString('base64url');
10
+ }
11
+ export async function oauthLogin(deps, options, notify) {
12
+ const issuer = parseIssuer(options.issuer, 'config', deps.env);
13
+ const clientId = assertClientId(options.clientId, deps.env);
14
+ const discovery = await fetchDiscovery(deps, issuer);
15
+ const server = await deps.startLoopback({
16
+ path: CALLBACK_PATH,
17
+ timeoutMs: options.timeoutMs,
18
+ });
19
+ try {
20
+ return await runTransaction(deps, server, { issuer, clientId, discovery, options, notify });
21
+ }
22
+ finally {
23
+ await server.close();
24
+ }
25
+ }
26
+ async function runTransaction(deps, server, ctx) {
27
+ const { issuer, clientId, discovery, options, notify } = ctx;
28
+ const pkce = await createPkce(deps.randomBytes);
29
+ const state = base64url(deps.randomBytes(32));
30
+ const nonce = base64url(deps.randomBytes(32));
31
+ const authorizeUrl = buildAuthorizeUrl({
32
+ issuer,
33
+ authorizationEndpoint: discovery.authorizationEndpoint,
34
+ clientId,
35
+ redirectUri: server.redirectUri,
36
+ state,
37
+ nonce,
38
+ challenge: pkce.challenge,
39
+ promptLogin: options.promptLogin,
40
+ });
41
+ notify.waiting(server.redirectUri);
42
+ notify.authorize(authorizeUrl);
43
+ const opened = deps.openBrowser(authorizeUrl);
44
+ if (!opened)
45
+ notify.manual(authorizeUrl);
46
+ else {
47
+ }
48
+ const callback = await server.next().catch((err) => {
49
+ throw mapLoopbackError(err, options.timeoutMs, deps.env);
50
+ });
51
+ return completeTransaction(deps, callback, {
52
+ issuer,
53
+ clientId,
54
+ tokenEndpoint: discovery.tokenEndpoint,
55
+ jwksUri: discovery.jwksUri,
56
+ redirectUri: server.redirectUri,
57
+ state,
58
+ nonce,
59
+ verifier: pkce.verifier,
60
+ });
61
+ }
62
+ function mapLoopbackError(err, timeoutMs, envMap) {
63
+ let result;
64
+ if (err.code === LOOPBACK_TIMEOUT) {
65
+ result = new CliError('timeout', t('oauth.callbackTimeout', { seconds: timeoutMs / 1000 }, envMap), {
66
+ detail: t('oauth.callbackTimeoutDetail', {}, envMap),
67
+ });
68
+ }
69
+ else {
70
+ result = new CliError('network', t('oauth.callbackFailed', {}, envMap), {
71
+ detail: err instanceof Error ? err.message : String(err),
72
+ });
73
+ }
74
+ return result;
75
+ }
76
+ async function completeTransaction(deps, callback, tx) {
77
+ const failure = await failureOfCallback(callback.query, tx.state, deps.env);
78
+ if (failure !== null) {
79
+ respondSafely(callback, {
80
+ status: 400,
81
+ body: '<!doctype html><meta charset=utf-8><p>Login failed. Return to the terminal.</p>',
82
+ });
83
+ throw failure;
84
+ }
85
+ else {
86
+ }
87
+ try {
88
+ const tokens = await exchangeCode(deps, {
89
+ issuer: tx.issuer,
90
+ tokenEndpoint: tx.tokenEndpoint,
91
+ clientId: tx.clientId,
92
+ redirectUri: tx.redirectUri,
93
+ code: callback.query['code'],
94
+ verifier: tx.verifier,
95
+ });
96
+ await assertSignature(deps, tokens.idToken, tx.jwksUri);
97
+ assertIdToken(deps, tokens, { issuer: tx.issuer, clientId: tx.clientId, nonce: tx.nonce });
98
+ respondSafely(callback, tokens.completionUri === null
99
+ ? {
100
+ status: 200,
101
+ body: '<!doctype html><meta charset=utf-8><p>Login succeeded. Return to the terminal.</p>',
102
+ }
103
+ : { status: 303, location: tokens.completionUri });
104
+ return {
105
+ accessToken: tokens.accessToken,
106
+ refreshToken: tokens.refreshToken,
107
+ expiresIn: tokens.expiresIn,
108
+ };
109
+ }
110
+ catch (err) {
111
+ respondSafely(callback, {
112
+ status: 400,
113
+ body: '<!doctype html><meta charset=utf-8><p>Login failed. Return to the terminal.</p>',
114
+ });
115
+ throw err;
116
+ }
117
+ }
118
+ async function assertSignature(deps, idToken, jwksUri) {
119
+ const keys = await fetchJwks(deps, jwksUri);
120
+ const verdict = await verifyIdTokenSignature(idToken, keys);
121
+ if (verdict.ok)
122
+ return;
123
+ throw new CliError('auth', t('jwks.signatureInvalid', {}, deps.env), {
124
+ detail: signatureErrorReason(verdict.reason, deps.env),
125
+ });
126
+ }
127
+ async function failureOfCallback(query, expectedState, envMap) {
128
+ let result;
129
+ if (query['state'] !== expectedState) {
130
+ result = new CliError('auth', t('oauth.stateMismatch', {}, envMap), {
131
+ detail: t('oauth.stateMismatchDetail', {}, envMap),
132
+ });
133
+ }
134
+ else {
135
+ const error = query['error'];
136
+ if (error !== undefined) {
137
+ const description = query['error_description'];
138
+ result = new CliError('auth', t('oauth.authorizeError', { error }, envMap), {
139
+ detail: description,
140
+ });
141
+ }
142
+ else {
143
+ const code = query['code'];
144
+ if (code === undefined || code === '') {
145
+ result = new CliError('auth', t('oauth.noCode', {}, envMap));
146
+ }
147
+ else {
148
+ result = null;
149
+ }
150
+ }
151
+ }
152
+ return result;
153
+ }
154
+ function respondSafely(callback, answer) {
155
+ try {
156
+ callback.respond(answer);
157
+ }
158
+ catch {
159
+ }
160
+ }
161
+ function assertIdToken(deps, tokens, expected) {
162
+ const claims = decodeIdToken(tokens.idToken);
163
+ if (claims === null) {
164
+ throw new CliError('auth', t('oauth.idTokenUnreadable', {}, deps.env), {
165
+ detail: t('oauth.idTokenUnreadableDetail', {}, deps.env),
166
+ });
167
+ }
168
+ const verdict = checkIdTokenClaims(claims, {
169
+ issuer: expected.issuer,
170
+ clientId: expected.clientId,
171
+ nonce: expected.nonce,
172
+ nowSeconds: Math.floor(deps.clock().getTime() / 1000),
173
+ });
174
+ if (verdict.ok)
175
+ return;
176
+ throw new CliError('auth', t(`oauth.idToken.${verdict.reason}`, {}, deps.env), {
177
+ detail: t('oauth.idTokenHint', {}, deps.env),
178
+ });
179
+ }
@@ -0,0 +1,34 @@
1
+ import { CliError } from "../../errors.js";
2
+ import { t } from "../../i18n.js";
3
+ const CN_TOKEN_LENGTH = 43;
4
+ const PRINTABLE_ASCII = /^[\x21-\x7e]+$/;
5
+ function isRecord(v) {
6
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
7
+ }
8
+ function requireString(source, key) {
9
+ const v = source[key];
10
+ if (typeof v !== 'string' || v === '') {
11
+ throw new CliError('server', t('provider.missingField', { key }));
12
+ }
13
+ return v;
14
+ }
15
+ export const cnProvider = {
16
+ platform: 'cn',
17
+ authHeaders(credential) {
18
+ return { cookie: `seacraft_session=${credential.value}` };
19
+ },
20
+ normalizeProfile(raw) {
21
+ if (!isRecord(raw))
22
+ throw new CliError('server', t('provider.notObject'));
23
+ return {
24
+ id: requireString(raw, 'id'),
25
+ displayName: requireString(raw, 'displayName'),
26
+ username: requireString(raw, 'username'),
27
+ name: requireString(raw, 'name'),
28
+ raw,
29
+ };
30
+ },
31
+ looksLike(value) {
32
+ return value.length === CN_TOKEN_LENGTH && PRINTABLE_ASCII.test(value) && !value.includes('.');
33
+ },
34
+ };
@@ -0,0 +1,16 @@
1
+ import { CliError } from "../../errors.js";
2
+ import { cnProvider } from "./cn.js";
3
+ import { overseaProvider } from "./oversea.js";
4
+ import { t } from "../../i18n.js";
5
+ const REGISTRY = {
6
+ oversea: overseaProvider,
7
+ cn: cnProvider,
8
+ };
9
+ export function getProvider(platform) {
10
+ const provider = REGISTRY[platform];
11
+ if (provider === undefined) {
12
+ throw new CliError('config', t('error.unknownPlatform', { value: String(platform) }));
13
+ }
14
+ return provider;
15
+ }
16
+ export { cnProvider, overseaProvider };
@@ -0,0 +1,41 @@
1
+ import { CliError } from "../../errors.js";
2
+ import { t } from "../../i18n.js";
3
+ const JWT_SEGMENTS = 3;
4
+ function isRecord(v) {
5
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
6
+ }
7
+ function requireString(source, key) {
8
+ const v = source[key];
9
+ if (typeof v !== 'string' || v === '') {
10
+ throw new CliError('server', t('provider.missingField', { key }));
11
+ }
12
+ return v;
13
+ }
14
+ export const overseaProvider = {
15
+ platform: 'oversea',
16
+ authHeaders(credential) {
17
+ return { authorization: `Bearer ${credential.value}` };
18
+ },
19
+ normalizeProfile(raw) {
20
+ if (!isRecord(raw))
21
+ throw new CliError('server', t('provider.notObject'));
22
+ return {
23
+ id: requireString(raw, 'id'),
24
+ displayName: requireString(raw, 'displayName'),
25
+ username: requireString(raw, 'username'),
26
+ name: requireString(raw, 'name'),
27
+ raw,
28
+ };
29
+ },
30
+ looksLike(value) {
31
+ const parts = value.split('.');
32
+ let result;
33
+ if (parts.length !== JWT_SEGMENTS) {
34
+ result = false;
35
+ }
36
+ else {
37
+ result = parts.every((p) => p.length > 0);
38
+ }
39
+ return result;
40
+ },
41
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,66 @@
1
+ import { CliError } from "../errors.js";
2
+ import { t } from "../i18n.js";
3
+ import { safeErrorText } from "./http.js";
4
+ export async function refreshAccessToken(deps, input) {
5
+ const form = new URLSearchParams({
6
+ grant_type: 'refresh_token',
7
+ client_id: input.clientId,
8
+ refresh_token: input.refreshToken,
9
+ });
10
+ let response;
11
+ try {
12
+ response = await deps.fetch(input.tokenEndpoint, {
13
+ method: 'POST',
14
+ headers: {
15
+ accept: 'application/json',
16
+ 'content-type': 'application/x-www-form-urlencoded',
17
+ },
18
+ body: form.toString(),
19
+ });
20
+ }
21
+ catch (err) {
22
+ throw new CliError('network', t('oauth.refreshNetwork', {}, deps.env), {
23
+ detail: safeErrorText(err),
24
+ });
25
+ }
26
+ let text;
27
+ try {
28
+ text = await response.text();
29
+ }
30
+ catch (err) {
31
+ throw new CliError('network', t('oauth.refreshReadFailed', {}, deps.env), {
32
+ detail: safeErrorText(err),
33
+ });
34
+ }
35
+ let payload;
36
+ try {
37
+ payload = text === '' ? undefined : JSON.parse(text);
38
+ }
39
+ catch {
40
+ throw new CliError('server', t('oauth.refreshNotJson', { status: response.status }, deps.env));
41
+ }
42
+ if (payload === null || typeof payload !== 'object' || Array.isArray(payload)) {
43
+ throw new CliError('server', t('oauth.refreshNotObject', { status: response.status }, deps.env));
44
+ }
45
+ const body = payload;
46
+ if (!response.ok) {
47
+ throw rejectionOf(body, response.status, deps.env);
48
+ }
49
+ const accessToken = body['access_token'];
50
+ if (typeof accessToken !== 'string' || accessToken === '') {
51
+ throw new CliError('server', t('oauth.tokenNoAccessToken', {}, deps.env));
52
+ }
53
+ const refreshToken = body['refresh_token'];
54
+ const expiresIn = body['expires_in'];
55
+ return {
56
+ accessToken,
57
+ refreshToken: typeof refreshToken === 'string' && refreshToken !== '' ? refreshToken : null,
58
+ expiresIn: typeof expiresIn === 'number' ? expiresIn : null,
59
+ };
60
+ }
61
+ function rejectionOf(body, status, envMap) {
62
+ const code = typeof body['error'] === 'string' ? body['error'] : `HTTP ${status}`;
63
+ return new CliError(code === 'invalid_grant' ? 'auth' : 'server', t('oauth.refreshRejected', { error: code }, envMap), {
64
+ detail: typeof body['error_description'] === 'string' ? body['error_description'] : undefined,
65
+ });
66
+ }
@@ -0,0 +1,89 @@
1
+ export function parseVersion(input) {
2
+ const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/u.exec(input);
3
+ let result;
4
+ if (match === null) {
5
+ result = null;
6
+ }
7
+ else {
8
+ result = {
9
+ core: [Number(match[1]), Number(match[2]), Number(match[3])],
10
+ pre: match[4] === undefined ? [] : match[4].split('.'),
11
+ };
12
+ }
13
+ return result;
14
+ }
15
+ export function isPrerelease(input) {
16
+ return (parseVersion(input)?.pre.length ?? 0) > 0;
17
+ }
18
+ export function compareVersions(a, b) {
19
+ const left = parseVersion(a);
20
+ const right = parseVersion(b);
21
+ let result;
22
+ if (left === null || right === null) {
23
+ result = null;
24
+ }
25
+ else {
26
+ result = compareCore(left, right) ?? comparePre(left.pre, right.pre);
27
+ }
28
+ return result;
29
+ }
30
+ function compareCore(a, b) {
31
+ let result = null;
32
+ for (let i = 0; i < 3; i += 1) {
33
+ if (result === null) {
34
+ const diff = a.core[i] - b.core[i];
35
+ result = diff === 0 ? null : diff < 0 ? -1 : 1;
36
+ }
37
+ else {
38
+ }
39
+ }
40
+ return result;
41
+ }
42
+ function comparePre(a, b) {
43
+ let result;
44
+ if (a.length === 0 && b.length === 0) {
45
+ result = 0;
46
+ }
47
+ else if (a.length === 0) {
48
+ result = 1;
49
+ }
50
+ else if (b.length === 0) {
51
+ result = -1;
52
+ }
53
+ else {
54
+ result = comparePreParts(a, b);
55
+ }
56
+ return result;
57
+ }
58
+ function comparePreParts(a, b) {
59
+ const length = Math.min(a.length, b.length);
60
+ let result = null;
61
+ for (let i = 0; i < length; i += 1) {
62
+ if (result === null) {
63
+ const part = comparePart(a[i], b[i]);
64
+ result = part === 0 ? null : part;
65
+ }
66
+ else {
67
+ }
68
+ }
69
+ return result ?? (a.length === b.length ? 0 : a.length < b.length ? -1 : 1);
70
+ }
71
+ function comparePart(a, b) {
72
+ const aNum = /^\d+$/u.test(a);
73
+ const bNum = /^\d+$/u.test(b);
74
+ let result;
75
+ if (aNum && bNum) {
76
+ const diff = Number(a) - Number(b);
77
+ result = diff === 0 ? 0 : diff < 0 ? -1 : 1;
78
+ }
79
+ else if (aNum) {
80
+ result = -1;
81
+ }
82
+ else if (bNum) {
83
+ result = 1;
84
+ }
85
+ else {
86
+ result = a === b ? 0 : a < b ? -1 : 1;
87
+ }
88
+ return result;
89
+ }