35 lines
2.0 KiB
TypeScript
35 lines
2.0 KiB
TypeScript
|
|
import {ApiClient,internalUrl} from './network.ts';
|
||
|
|
|
||
|
|
export const developmentServerKey='cmvr.dev.server';
|
||
|
|
|
||
|
|
export function developmentServer(value:string):string {
|
||
|
|
const text=value.trim();
|
||
|
|
if(!text||text.length>240)throw new Error('请填写开发电脑的内网 IP 和端口,例如 192.168.28.20:8080。');
|
||
|
|
try {
|
||
|
|
if(/[\\%]|\.\./.test(text))throw new Error('invalid address');
|
||
|
|
const result=internalUrl(/^[a-z][a-z\d+.-]*:\/\//i.test(text)?text:`http://${text}`,true);
|
||
|
|
const url=new URL(result);
|
||
|
|
if(!/^\/[a-z\d/_-]*$/i.test(url.pathname))throw new Error('invalid path');
|
||
|
|
return result.replace(/\/+$/,'');
|
||
|
|
}catch{throw new Error('请使用内网 HTTP/HTTPS 地址,可包含端口和接口前缀;不要填写公网地址、账号或查询参数。');}
|
||
|
|
}
|
||
|
|
|
||
|
|
/** No credentials are reused between development servers. SecureStore-safe, collision-free key. */
|
||
|
|
export function serverTokenKey(environment:string,address:string):string {
|
||
|
|
return environment==='dev'?`cmvr.dev.token.${Array.from(developmentServer(address)).map(c=>c.charCodeAt(0).toString(16).padStart(2,'0')).join('')}`:`cmvr.${environment}.token`;
|
||
|
|
}
|
||
|
|
|
||
|
|
export function connectionClient(address:string,expired:()=>void,previewOrigin?:string,transport?:typeof fetch):ApiClient {
|
||
|
|
return new ApiClient(previewOrigin?`${previewOrigin}/native-api`:address,expired,transport,
|
||
|
|
previewOrigin?developmentServer(address):undefined);
|
||
|
|
}
|
||
|
|
|
||
|
|
/** Read-only handshake. A failed probe must never replace the working saved address. */
|
||
|
|
export async function checkDevelopmentServer(value:string,previewOrigin?:string,transport?:typeof fetch):Promise<string> {
|
||
|
|
const address=developmentServer(value);
|
||
|
|
const api=connectionClient(address,()=>{},previewOrigin,transport);
|
||
|
|
const result=await api.request<{captchaEnabled?:boolean}>('/captchaImage',{anonymous:true,timeout:8000});
|
||
|
|
if(typeof result.captchaEnabled!=='boolean')throw new Error('这个地址没有返回系统登录信息,请检查端口或接口前缀。');
|
||
|
|
return address;
|
||
|
|
}
|