@ohoooho/taoxian-runtime-sdk 0.0.0-stage → 0.1.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/CHANGELOG.md ADDED
@@ -0,0 +1,10 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ - 首个公开 SDK 包结构:`runtime`、`fenshen`、`api-key`、`browser` 四个入口。
6
+ - 增加分身登录中间件 `createFenshenAuth` 和 `runtimeLoginUrl`。
7
+ - 增加浏览器同源 Runtime 客户端 `createRuntimeBrowserClient`。
8
+ - 增加 `resolveFenshenUiUrl`,把 loopback UI 地址转换成手机当前 host。
9
+ - 保留 Runtime 生命周期、手机配对和静态 API Key 校验。
10
+ - 增加 TypeScript 声明和 Node / 浏览器示例。
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ohoooho
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,147 @@
1
- # Temporary Holding Version
1
+ # @ohoooho/taoxian-runtime-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 桃仙 Runtime、分身登录和静态 API Key 的 JS SDK。
4
+
5
+ ```bash
6
+ npm install @ohoooho/taoxian-runtime-sdk
7
+ ```
8
+
9
+ 当前版本:`0.1.0`,license:MIT。Node.js >= 20。浏览器请使用 `@ohoooho/taoxian-runtime-sdk/browser`。
10
+ 包是 **ESM-only**;CommonJS 项目请用动态 `import()` 或先转译。自带 TypeScript 声明。
11
+
12
+ ## 入口
13
+
14
+ | 入口 | 环境 | 用途 |
15
+ |---|---|---|
16
+ | `@ohoooho/taoxian-runtime-sdk/runtime` | Node | Runtime 发现、健康检查、分身注册、本机登录、手机配对、API Key |
17
+ | `@ohoooho/taoxian-runtime-sdk/fenshen` | Node | 分身后端验证浏览器 Runtime session、登录跳转中间件 |
18
+ | `@ohoooho/taoxian-runtime-sdk/api-key` | Node | SaaS/MCP 后端校验 `txk_live_` 静态 API Key |
19
+ | `@ohoooho/taoxian-runtime-sdk/browser` | 浏览器 | 同源 Runtime 客户端、配对、分身 UI 地址解析 |
20
+ | `@ohoooho/taoxian-runtime-sdk` | Node | 上述 Node 入口的合集 |
21
+
22
+ ## Runtime
23
+
24
+ ```js
25
+ import { ensureRuntime, getRuntimeStatus } from '@ohoooho/taoxian-runtime-sdk/runtime';
26
+
27
+ const status = await ensureRuntime({ autoStart: true, minVersion: '0.1.0' });
28
+ console.log(status.version, status.db.ready);
29
+ ```
30
+
31
+ - 读 `TAOXIAN_RUNTIME_URL` / `~/.taoxian/runtime.json`
32
+ - 不会启动第二套 PostgreSQL 或 Runtime
33
+ - 版本不兼容抛 `RuntimeIncompatibleError`
34
+
35
+ ## 分身登录
36
+
37
+ 分身后端拿到浏览器的 Cookie header,服务端转发给 Runtime:
38
+
39
+ ```js
40
+ import { createFenshenAuth } from '@ohoooho/taoxian-runtime-sdk/fenshen';
41
+
42
+ const auth = createFenshenAuth({
43
+ runtimeUrl: process.env.TAOXIAN_RUNTIME_URL || 'http://127.0.0.1:4319',
44
+ });
45
+
46
+ app.use(auth.middleware);
47
+ // 登录后 req.user = { id, username, display_name, ... }
48
+ ```
49
+
50
+ - 未登录时 302 到同一个 host 的 Runtime 登录页
51
+ - Runtime 不可用时返回 503,不会重定向循环
52
+ - 不要自己再实现一套登录页
53
+ - 不要把 Cookie 暴露给浏览器 JS 或日志
54
+
55
+ 完整契约见 [`../docs/FENSHEN-INTEGRATION.md`](../docs/FENSHEN-INTEGRATION.md)。
56
+
57
+ ## 手机配对
58
+
59
+ ```js
60
+ import {
61
+ createMobilePairing,
62
+ getMobileAccess,
63
+ redeemMobilePairing,
64
+ } from '@ohoooho/taoxian-runtime-sdk/runtime';
65
+
66
+ // 电脑端:已登录 session 生成一次性配对码
67
+ const pairing = await createMobilePairing(sessionToken, { label: 'iPhone' });
68
+
69
+ // 手机端:用配对码换本地 session
70
+ const session = await redeemMobilePairing({ code: pairing.code });
71
+
72
+ // 手机端:读取入口和局域网地址
73
+ const access = await getMobileAccess(session.session_token);
74
+ ```
75
+
76
+ - 配对码一次性、默认 5 分钟有效、服务端只存哈希
77
+ - 手机只拿本地 session,不拿 PostgreSQL 密码或完整 DSN
78
+ - 默认只监听 `127.0.0.1`;手机访问用 `taoxian-runtime mobile --lan`
79
+
80
+ ## 静态 API Key
81
+
82
+ ```js
83
+ import { createApiKeyVerifier } from '@ohoooho/taoxian-runtime-sdk/api-key';
84
+
85
+ const verify = createApiKeyVerifier({
86
+ baseUrl: 'https://taoxian.ohoooho.com',
87
+ serviceToken: process.env.TAOXIAN_API_KEY_VERIFY_TOKEN,
88
+ });
89
+ const result = await verify(bearerToken);
90
+ ```
91
+
92
+ - 按 SHA-256 指纹缓存,不缓存明文
93
+ - 并发去重
94
+ - 上游不可用时 fail-closed
95
+ - service token 被拒绝时抛配置错误
96
+
97
+ ## 浏览器
98
+
99
+ ```js
100
+ import {
101
+ createRuntimeBrowserClient,
102
+ resolveFenshenUiUrl,
103
+ } from '@ohoooho/taoxian-runtime-sdk/browser';
104
+
105
+ const client = createRuntimeBrowserClient(); // 默认同源
106
+ const status = await client.getStatus();
107
+ const { fenshens } = await client.listFenshens();
108
+ const url = resolveFenshenUiUrl(fenshens[0]);
109
+ ```
110
+
111
+ - 只用于与 Runtime 同源的页面(如 `/m` 或自定义移动端)
112
+ - 不读文件、不碰 DSN、不使用 `node:*`
113
+ - 默认 `credentials: 'same-origin'`
114
+ - 发布 npm 后可以通过 ESM CDN 加载:
115
+
116
+ ```html
117
+ <script type="module">
118
+ import { createRuntimeBrowserClient } from 'https://cdn.jsdelivr.net/npm/@ohoooho/taoxian-runtime-sdk@0.1.0/browser.mjs';
119
+ const client = createRuntimeBrowserClient();
120
+ console.log(await client.getStatus());
121
+ </script>
122
+ ```
123
+
124
+ ## 直接从仓库使用
125
+
126
+ 还没发布 npm 时,可以在本仓内按相对路径引用:
127
+
128
+ ```js
129
+ import { createFenshenAuth } from './sdk/fenshen.mjs';
130
+ ```
131
+
132
+ ## 可运行示例
133
+
134
+ 仓库内 [`../examples/fenshen-echo`](../examples/fenshen-echo/README.md) 是一个最小分身:
135
+ 它用 `@ohoooho/taoxian-runtime-sdk/fenshen` 验证 Runtime 登录,并出现在 `/m` 手机端。
136
+
137
+ ## 发布
138
+
139
+ 发布前必须确认 npm scope、license、版本号和发布人。准备流程见
140
+ [`../docs/JS-SDK.md`](../docs/JS-SDK.md)。
141
+
142
+ ```bash
143
+ npm test --prefix sdk
144
+ cd sdk
145
+ npm pack --dry-run
146
+ npm publish --access public
147
+ ```
@@ -0,0 +1,166 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ // Client-side helper for SaaS/MCP backends that need to verify a Taoxian
4
+ // static API key. It only knows the verify contract; it never stores the raw
5
+ // key beyond the request and caches by SHA-256 fingerprint.
6
+ export const API_KEY_PATTERN = /^txk_live_[A-Za-z0-9_-]{40,64}$/;
7
+
8
+ export class ApiKeyVerifierConfigError extends Error {
9
+ constructor(message) {
10
+ super(message);
11
+ this.name = 'ApiKeyVerifierConfigError';
12
+ this.code = 'api_key_verifier_config_error';
13
+ }
14
+ }
15
+
16
+ export class ApiKeyVerifyUnavailableError extends Error {
17
+ constructor(message, cause) {
18
+ super(message);
19
+ this.name = 'ApiKeyVerifyUnavailableError';
20
+ this.code = 'api_key_verify_unavailable';
21
+ this.cause = cause;
22
+ }
23
+ }
24
+
25
+ export function isApiKeyFormat(value) {
26
+ const candidate = String(value || '');
27
+ return candidate.length <= 100 && API_KEY_PATTERN.test(candidate);
28
+ }
29
+
30
+ export function createApiKeyVerifier({
31
+ baseUrl,
32
+ serviceToken,
33
+ ttlMs = 30_000,
34
+ negativeTtlMs = 5_000,
35
+ timeoutMs = 3_000,
36
+ maxCacheEntries = 5_000,
37
+ fetchImpl = globalThis.fetch,
38
+ } = {}) {
39
+ if (!baseUrl) throw new ApiKeyVerifierConfigError('baseUrl is required');
40
+ if (!serviceToken) throw new ApiKeyVerifierConfigError('serviceToken is required');
41
+ if (typeof fetchImpl !== 'function') throw new ApiKeyVerifierConfigError('fetchImpl must be a function');
42
+
43
+ const endpoint = `${String(baseUrl).replace(/\/+$/, '')}/api/v1/api-keys/verify`;
44
+ const cache = new Map();
45
+ const inflight = new Map();
46
+
47
+ function fingerprint(key) {
48
+ return createHash('sha256').update(key).digest('hex');
49
+ }
50
+
51
+ function readCache(hash) {
52
+ const hit = cache.get(hash);
53
+ if (!hit) return null;
54
+ if (hit.expiresAt <= Date.now()) {
55
+ cache.delete(hash);
56
+ return null;
57
+ }
58
+ return hit.value;
59
+ }
60
+
61
+ function writeCache(hash, value) {
62
+ const ttl = value.active ? ttlMs : negativeTtlMs;
63
+ if (ttl <= 0) return;
64
+ if (cache.size >= maxCacheEntries) {
65
+ const oldest = cache.keys().next().value;
66
+ if (oldest) cache.delete(oldest);
67
+ }
68
+ cache.set(hash, { value, expiresAt: Date.now() + ttl });
69
+ }
70
+
71
+ async function request(rawKey, signal) {
72
+ const controller = new AbortController();
73
+ const timer = setTimeout(() => controller.abort(new Error('api_key_verify_timeout')), timeoutMs);
74
+ timer.unref?.();
75
+ const onAbort = () => controller.abort(signal?.reason);
76
+ if (signal) {
77
+ if (signal.aborted) controller.abort(signal.reason);
78
+ else signal.addEventListener('abort', onAbort, { once: true });
79
+ }
80
+
81
+ try {
82
+ const response = await fetchImpl(endpoint, {
83
+ method: 'POST',
84
+ headers: {
85
+ 'Content-Type': 'application/json',
86
+ 'X-Taoxian-Service-Token': serviceToken,
87
+ },
88
+ body: JSON.stringify({ key: rawKey }),
89
+ signal: controller.signal,
90
+ });
91
+
92
+ if (response.status === 401 || response.status === 403) {
93
+ throw new ApiKeyVerifierConfigError('Taoxian verify service token was rejected');
94
+ }
95
+ if (!response.ok) {
96
+ throw new ApiKeyVerifyUnavailableError(`taoxian verify returned HTTP ${response.status}`);
97
+ }
98
+
99
+ let data;
100
+ try {
101
+ data = await response.json();
102
+ } catch (error) {
103
+ throw new ApiKeyVerifyUnavailableError('taoxian verify returned invalid JSON', error);
104
+ }
105
+ if (!data || typeof data !== 'object') {
106
+ throw new ApiKeyVerifyUnavailableError('taoxian verify returned an invalid payload');
107
+ }
108
+
109
+ if (data.active !== true) {
110
+ return { active: false, reason: data.reason || 'invalid' };
111
+ }
112
+ if (!data.logto_user_id) {
113
+ throw new ApiKeyVerifyUnavailableError('taoxian verify response is missing logto_user_id');
114
+ }
115
+
116
+ return {
117
+ active: true,
118
+ logtoUserId: data.logto_user_id,
119
+ keyId: data.key_id,
120
+ name: data.name,
121
+ expiresAt: data.expires_at ?? null,
122
+ lastUsedAt: data.last_used_at ?? null,
123
+ };
124
+ } catch (error) {
125
+ if (error instanceof ApiKeyVerifierConfigError || error instanceof ApiKeyVerifyUnavailableError) throw error;
126
+ throw new ApiKeyVerifyUnavailableError('taoxian verify is unavailable', error);
127
+ } finally {
128
+ clearTimeout(timer);
129
+ if (signal) signal.removeEventListener('abort', onAbort);
130
+ }
131
+ }
132
+
133
+ async function verify(rawKey, { signal } = {}) {
134
+ const key = String(rawKey || '').trim();
135
+ if (!isApiKeyFormat(key)) return { active: false, reason: 'invalid' };
136
+
137
+ const hash = fingerprint(key);
138
+ const cached = readCache(hash);
139
+ if (cached) return { ...cached, cached: true };
140
+
141
+ const pending = inflight.get(hash);
142
+ if (pending) return pending;
143
+
144
+ const promise = request(key, signal)
145
+ .then((result) => {
146
+ writeCache(hash, result);
147
+ return result;
148
+ })
149
+ .finally(() => {
150
+ inflight.delete(hash);
151
+ });
152
+ inflight.set(hash, promise);
153
+ return promise;
154
+ }
155
+
156
+ return {
157
+ verify,
158
+ clearCache() {
159
+ cache.clear();
160
+ inflight.clear();
161
+ },
162
+ get cacheSize() {
163
+ return cache.size;
164
+ },
165
+ };
166
+ }
package/browser.mjs ADDED
@@ -0,0 +1,101 @@
1
+ // Browser-safe Runtime client. It intentionally uses relative paths by default
2
+ // and never reads Runtime files, DSNs or API keys. It is meant for custom UIs
3
+ // served from the same origin as Runtime (for example /m or a fenshen page).
4
+ export class RuntimeBrowserError extends Error {
5
+ constructor(message, { status = 0, code = 'runtime_browser_error', body = null } = {}) {
6
+ super(message);
7
+ this.name = 'RuntimeBrowserError';
8
+ this.code = code;
9
+ this.status = status;
10
+ this.body = body;
11
+ }
12
+ }
13
+
14
+ function trimUrl(value) {
15
+ return String(value || '').replace(/\/+$/, '');
16
+ }
17
+
18
+ export function resolveFenshenUiUrl(fenshen, { hostname = globalThis.location?.hostname } = {}) {
19
+ const raw = fenshen?.ui?.mobile_url || fenshen?.ui?.url;
20
+ if (!raw) return null;
21
+ try {
22
+ const url = new URL(raw, globalThis.location?.origin);
23
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return null;
24
+ if (url.username || url.password) return null;
25
+ if (url.hostname === '127.0.0.1' || url.hostname === 'localhost' || url.hostname === '::1') {
26
+ if (!hostname) return null;
27
+ url.hostname = hostname;
28
+ }
29
+ return url.toString();
30
+ } catch {
31
+ return null;
32
+ }
33
+ }
34
+
35
+ export function createRuntimeBrowserClient({
36
+ baseUrl = '',
37
+ fetchImpl = globalThis.fetch,
38
+ credentials = 'same-origin',
39
+ timeoutMs = 3_000,
40
+ } = {}) {
41
+ if (typeof fetchImpl !== 'function') {
42
+ throw new TypeError('fetchImpl must be a function');
43
+ }
44
+ const base = trimUrl(baseUrl);
45
+
46
+ async function request(path, { method = 'GET', body } = {}) {
47
+ const controller = new AbortController();
48
+ const timer = setTimeout(() => controller.abort(new Error('runtime_browser_timeout')), timeoutMs);
49
+ try {
50
+ const response = await fetchImpl(`${base}${path}`, {
51
+ method,
52
+ headers: {
53
+ Accept: 'application/json',
54
+ ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
55
+ },
56
+ body: body === undefined ? undefined : JSON.stringify(body),
57
+ credentials,
58
+ cache: 'no-store',
59
+ signal: controller.signal,
60
+ });
61
+ let data = null;
62
+ try { data = await response.json(); } catch { /* keep status */ }
63
+ if (!response.ok) {
64
+ throw new RuntimeBrowserError(
65
+ data?.message || data?.error || `Taoxian Runtime returned HTTP ${response.status}`,
66
+ { status: response.status, code: data?.error || 'runtime_request_failed', body: data }
67
+ );
68
+ }
69
+ return data;
70
+ } catch (error) {
71
+ if (error instanceof RuntimeBrowserError) throw error;
72
+ throw new RuntimeBrowserError('Taoxian Runtime is not reachable', {
73
+ code: 'runtime_unavailable',
74
+ body: { cause: error?.message },
75
+ });
76
+ } finally {
77
+ clearTimeout(timer);
78
+ }
79
+ }
80
+
81
+ return {
82
+ baseUrl: base,
83
+ getAuthStatus: () => request('/api/v1/runtime/auth/status'),
84
+ getMe: () => request('/api/v1/runtime/auth/me'),
85
+ getStatus: () => request('/api/v1/runtime/status'),
86
+ getMobileAccess: () => request('/api/v1/runtime/mobile/access'),
87
+ listFenshens: () => request('/api/v1/runtime/fenshen'),
88
+ logout: () => request('/api/v1/runtime/auth/logout', { method: 'POST', body: {} }),
89
+ createPairing: ({ label, ttlSeconds } = {}) => request('/api/v1/runtime/mobile/pairing', {
90
+ method: 'POST',
91
+ body: {
92
+ ...(label ? { label } : {}),
93
+ ...(ttlSeconds ? { ttl_seconds: ttlSeconds } : {}),
94
+ },
95
+ }),
96
+ redeemPairing: (code) => request('/api/v1/runtime/mobile/pair', {
97
+ method: 'POST',
98
+ body: { code },
99
+ }),
100
+ };
101
+ }
@@ -0,0 +1,14 @@
1
+ import {
2
+ createRuntimeBrowserClient,
3
+ resolveFenshenUiUrl,
4
+ } from '@ohoooho/taoxian-runtime-sdk/browser';
5
+
6
+ const client = createRuntimeBrowserClient();
7
+ const status = await client.getStatus();
8
+ const fenshens = (await client.listFenshens()).fenshens;
9
+
10
+ console.log('runtime', status.version, 'db', status.db.ready);
11
+ for (const fenshen of fenshens) {
12
+ const url = resolveFenshenUiUrl(fenshen);
13
+ console.log(fenshen.id, url || '(no mobile UI declared)');
14
+ }
@@ -0,0 +1,27 @@
1
+ import express from 'express';
2
+ import { createFenshenAuth } from '@ohoooho/taoxian-runtime-sdk/fenshen';
3
+
4
+ const app = express();
5
+ const port = Number(process.env.PORT || 4173);
6
+ const auth = createFenshenAuth({
7
+ runtimeUrl: process.env.TAOXIAN_RUNTIME_URL || 'http://127.0.0.1:4319',
8
+ });
9
+
10
+ app.get('/health', (req, res) => {
11
+ res.json({ ok: true, schema_version: 1 });
12
+ });
13
+
14
+ // Browser cookie is validated by the fenshen backend, not by browser JS.
15
+ app.use(auth.middleware);
16
+
17
+ app.get('/', (req, res) => {
18
+ const name = req.user.display_name || req.user.username;
19
+ res.type('html').send(`<!doctype html>
20
+ <meta name="viewport" content="width=device-width,initial-scale=1">
21
+ <h1>你好,${name}</h1>
22
+ <p>这是分身自己的业务页面。</p>`);
23
+ });
24
+
25
+ app.listen(port, '0.0.0.0', () => {
26
+ console.log(`fenshen listening on ${port}`);
27
+ });
package/fenshen.mjs ADDED
@@ -0,0 +1,124 @@
1
+ import { getLocalUserFromCookie } from './runtime-client.mjs';
2
+
3
+ export const DEFAULT_RUNTIME_URL = 'http://127.0.0.1:4319';
4
+
5
+ export class FenshenAuthError extends Error {
6
+ constructor(code, message, cause) {
7
+ super(message || code);
8
+ this.name = 'FenshenAuthError';
9
+ this.code = code;
10
+ this.cause = cause;
11
+ }
12
+ }
13
+
14
+ function hostnameFromHostHeader(value) {
15
+ const host = String(value || '').trim();
16
+ if (!host) return '127.0.0.1';
17
+ if (host.startsWith('[')) {
18
+ const end = host.indexOf(']');
19
+ return end > 0 ? host.slice(1, end) : '127.0.0.1';
20
+ }
21
+ return host.split(':')[0] || '127.0.0.1';
22
+ }
23
+
24
+ function hostForUrl(hostname) {
25
+ return hostname.includes(':') ? `[${hostname}]` : hostname;
26
+ }
27
+
28
+ function requestProtocol(req, trustProxy) {
29
+ if (trustProxy) {
30
+ const forwarded = String(req?.headers?.['x-forwarded-proto'] || '').split(',')[0].trim();
31
+ if (forwarded === 'http' || forwarded === 'https') return forwarded;
32
+ }
33
+ return req?.socket?.encrypted || req?.connection?.encrypted ? 'https' : 'http';
34
+ }
35
+
36
+ function runtimeBaseUrl(req, { runtimeUrl, runtimePort, trustProxy } = {}) {
37
+ const hostname = hostnameFromHostHeader(req?.headers?.host);
38
+ const parsedRuntime = new URL(runtimeUrl || DEFAULT_RUNTIME_URL);
39
+ const port = runtimePort || parsedRuntime.port || (parsedRuntime.protocol === 'https:' ? '443' : '4319');
40
+ const protocol = parsedRuntime.protocol === 'https:' ? 'https' : requestProtocol(req, trustProxy);
41
+ return new URL(`${protocol}://${hostForUrl(hostname)}:${port}/`);
42
+ }
43
+
44
+ export function runtimePublicUrl(req, {
45
+ runtimeUrl = process.env.TAOXIAN_RUNTIME_URL || DEFAULT_RUNTIME_URL,
46
+ runtimePort,
47
+ trustProxy = false,
48
+ path = '/',
49
+ } = {}) {
50
+ const url = runtimeBaseUrl(req, { runtimeUrl, runtimePort, trustProxy });
51
+ url.pathname = path.startsWith('/') ? path : `/${path}`;
52
+ url.search = '';
53
+ url.hash = '';
54
+ return url.toString();
55
+ }
56
+
57
+ export function runtimeLoginUrl(req, {
58
+ runtimeUrl = process.env.TAOXIAN_RUNTIME_URL || DEFAULT_RUNTIME_URL,
59
+ runtimePort,
60
+ trustProxy = false,
61
+ nextPath,
62
+ } = {}) {
63
+ const url = runtimeBaseUrl(req, { runtimeUrl, runtimePort, trustProxy });
64
+ const path = nextPath || req?.originalUrl || req?.url;
65
+ if (path && path !== '/') url.searchParams.set('next', path);
66
+ return url.toString();
67
+ }
68
+
69
+ export async function getFenshenUser(req, {
70
+ runtimeUrl = process.env.TAOXIAN_RUNTIME_URL || DEFAULT_RUNTIME_URL,
71
+ timeoutMs = 2_000,
72
+ fetchImpl = globalThis.fetch,
73
+ } = {}) {
74
+ try {
75
+ const result = await getLocalUserFromCookie(req?.headers?.cookie, {
76
+ url: runtimeUrl,
77
+ timeoutMs,
78
+ fetchImpl,
79
+ });
80
+ return result.user;
81
+ } catch (error) {
82
+ if (error?.status === 401) return null;
83
+ throw new FenshenAuthError('runtime_unavailable', 'Taoxian Runtime is unavailable', error);
84
+ }
85
+ }
86
+
87
+ export function createFenshenAuth({
88
+ runtimeUrl = process.env.TAOXIAN_RUNTIME_URL || DEFAULT_RUNTIME_URL,
89
+ timeoutMs = 2_000,
90
+ fetchImpl = globalThis.fetch,
91
+ trustProxy = false,
92
+ onUnauthorized,
93
+ onUnavailable,
94
+ } = {}) {
95
+ async function authenticate(req) {
96
+ return getFenshenUser(req, { runtimeUrl, timeoutMs, fetchImpl });
97
+ }
98
+
99
+ async function middleware(req, res, next) {
100
+ try {
101
+ const user = await authenticate(req);
102
+ if (!user) {
103
+ if (onUnauthorized) return onUnauthorized(req, res);
104
+ res.statusCode = 302;
105
+ res.setHeader('Location', runtimeLoginUrl(req, { runtimeUrl, trustProxy }));
106
+ return res.end();
107
+ }
108
+ req.user = user;
109
+ if (typeof next === 'function') return next();
110
+ return user;
111
+ } catch (error) {
112
+ if (onUnavailable) return onUnavailable(req, res, error);
113
+ res.statusCode = 503;
114
+ res.setHeader('Content-Type', 'text/plain; charset=utf-8');
115
+ return res.end('Taoxian Runtime unavailable');
116
+ }
117
+ }
118
+
119
+ return {
120
+ runtimeUrl,
121
+ authenticate,
122
+ middleware,
123
+ };
124
+ }
package/index.mjs ADDED
@@ -0,0 +1,5 @@
1
+ // Node.js entry point. It includes filesystem discovery, lifecycle commands and
2
+ // crypto helpers, so browser code must import `@ohoooho/taoxian-runtime-sdk/browser` instead.
3
+ export * from './runtime-client.mjs';
4
+ export * from './fenshen.mjs';
5
+ export * from './api-key-verifier.mjs';
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@ohoooho/taoxian-runtime-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Taoxian Runtime, fenshen auth and static API-key helpers for Node.js and browsers",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "private": false,
8
+ "sideEffects": false,
9
+ "engines": {
10
+ "node": ">=20"
11
+ },
12
+ "exports": {
13
+ ".": {
14
+ "types": "./types/index.d.ts",
15
+ "import": "./index.mjs"
16
+ },
17
+ "./runtime": {
18
+ "types": "./types/runtime.d.ts",
19
+ "import": "./runtime-client.mjs"
20
+ },
21
+ "./fenshen": {
22
+ "types": "./types/fenshen.d.ts",
23
+ "import": "./fenshen.mjs"
24
+ },
25
+ "./api-key": {
26
+ "types": "./types/api-key.d.ts",
27
+ "import": "./api-key-verifier.mjs"
28
+ },
29
+ "./browser": {
30
+ "types": "./types/browser.d.ts",
31
+ "import": "./browser.mjs"
32
+ },
33
+ "./package.json": "./package.json"
34
+ },
35
+ "files": [
36
+ "LICENSE",
37
+ "*.mjs",
38
+ "types",
39
+ "examples",
40
+ "README.md",
41
+ "CHANGELOG.md"
42
+ ],
43
+ "scripts": {
44
+ "test": "node --test test/*.test.js",
45
+ "pack:check": "npm pack --dry-run"
46
+ },
47
+ "keywords": [
48
+ "taoxian",
49
+ "runtime",
50
+ "fenshen",
51
+ "api-key",
52
+ "sdk"
53
+ ],
54
+ "publishConfig": {
55
+ "access": "public"
56
+ }
57
+ }