@microi.net/cli 4.6.2
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/LICENSE +21 -0
- package/README.md +66 -0
- package/dist/mcp-codex-stdio-adapter.js +189 -0
- package/dist/mcp-server.js +972 -0
- package/dist/mcp-trae-windows-launcher.cmd +21 -0
- package/dist/microi-cli-mcp.js +7 -0
- package/dist/microi-cli.js +1645 -0
- package/dist/microi-skills.meta.json +335 -0
- package/dist/microi.skills/.microi-skills-version.json +6 -0
- package/dist/microi.skills/README.md +276 -0
- package/dist/microi.skills/ai-engine/SKILL.md +140 -0
- package/dist/microi.skills/ai-engine/agents/openai.yaml +4 -0
- package/dist/microi.skills/app-store/SKILL.md +105 -0
- package/dist/microi.skills/app-store/agents/openai.yaml +4 -0
- package/dist/microi.skills/business-blueprint/SKILL.md +184 -0
- package/dist/microi.skills/datasource-engine/SKILL.md +89 -0
- package/dist/microi.skills/datasource-engine/agents/openai.yaml +4 -0
- package/dist/microi.skills/dos-orm/SKILL.md +76 -0
- package/dist/microi.skills/dos-orm/references/api-reference.md +229 -0
- package/dist/microi.skills/job-engine/SKILL.md +141 -0
- package/dist/microi.skills/job-engine/agents/openai.yaml +4 -0
- package/dist/microi.skills/message-notification/SKILL.md +113 -0
- package/dist/microi.skills/message-notification/agents/openai.yaml +6 -0
- package/dist/microi.skills/message-notification/references/contracts.md +99 -0
- package/dist/microi.skills/microi-ai-app-auth.js +651 -0
- package/dist/microi.skills/microi-ai-application/SKILL.md +80 -0
- package/dist/microi.skills/microi-ai-application/agents/openai.yaml +4 -0
- package/dist/microi.skills/microi-ai-application/references/frontend-baseline.md +164 -0
- package/dist/microi.skills/microi-client-frontend/SKILL.md +562 -0
- package/dist/microi.skills/microi-datasource-mapping/SKILL.md +108 -0
- package/dist/microi.skills/microi-db-schema/SKILL.md +170 -0
- package/dist/microi.skills/microi-db-schema/agents/openai.yaml +4 -0
- package/dist/microi.skills/microi-db-schema/references/core-tables.md +695 -0
- package/dist/microi.skills/microi-db-schema/references/form-component-options.md +256 -0
- package/dist/microi.skills/microi-db-schema/references/schema-overview.md +203 -0
- package/dist/microi.skills/microi-db-schema/references/schema.md +647 -0
- package/dist/microi.skills/microi-db-schema/references/table-catalog.md +1607 -0
- package/dist/microi.skills/microi-deployment/SKILL.md +117 -0
- package/dist/microi.skills/microi-deployment/references/deployment-matrix.md +94 -0
- package/dist/microi.skills/microi-docs-coverage/SKILL.md +91 -0
- package/dist/microi.skills/microi-docs-coverage/references/capability-map.md +65 -0
- package/dist/microi.skills/microi-docs-coverage/scripts/audit-doc-skill-coverage.mjs +887 -0
- package/dist/microi.skills/microi-form-engine/SKILL.md +159 -0
- package/dist/microi.skills/microi-form-engine/references/component-catalog.md +116 -0
- package/dist/microi.skills/microi-form-engine/references/data-source-events.md +117 -0
- package/dist/microi.skills/microi-form-layout/SKILL.md +373 -0
- package/dist/microi.skills/microi-frontend-sdk/SKILL.md +304 -0
- package/dist/microi.skills/microi-left-right-layout/SKILL.md +132 -0
- package/dist/microi.skills/microi-microservice/SKILL.md +115 -0
- package/dist/microi.skills/microi-microservice/references/runtime-delivery.md +145 -0
- package/dist/microi.skills/microi-mobile-app-quality/SKILL.md +436 -0
- package/dist/microi.skills/microi-solution-quotation/SKILL.md +76 -0
- package/dist/microi.skills/microi-solution-quotation/agents/openai.yaml +4 -0
- package/dist/microi.skills/microi-solution-quotation/scripts/build_solution_quote.py +296 -0
- package/dist/microi.skills/microi-system-delivery/SKILL.md +446 -0
- package/dist/microi.skills/microi-ui/SKILL.md +321 -0
- package/dist/microi.skills/microi-uniapp-frontend/SKILL.md +483 -0
- package/dist/microi.skills/microi.v8.js +1758 -0
- package/dist/microi.skills/module-engine/SKILL.md +131 -0
- package/dist/microi.skills/module-engine/references/module-config.md +174 -0
- package/dist/microi.skills/page-engine/SKILL.md +397 -0
- package/dist/microi.skills/performance-testing/SKILL.md +207 -0
- package/dist/microi.skills/playwright-e2e/SKILL.md +769 -0
- package/dist/microi.skills/print-engine/SKILL.md +237 -0
- package/dist/microi.skills/production-readonly-audit/SKILL.md +39 -0
- package/dist/microi.skills/report-engine/SKILL.md +69 -0
- package/dist/microi.skills/report-engine/agents/openai.yaml +4 -0
- package/dist/microi.skills/search-engine/SKILL.md +73 -0
- package/dist/microi.skills/search-engine/agents/openai.yaml +4 -0
- package/dist/microi.skills/spider-engine/SKILL.md +188 -0
- package/dist/microi.skills/translate-engine/SKILL.md +91 -0
- package/dist/microi.skills/translate-engine/agents/openai.yaml +4 -0
- package/dist/microi.skills/ui-design/SKILL.md +1575 -0
- package/dist/microi.skills/ui-design/assets/pattern-showcase/app.js +54 -0
- package/dist/microi.skills/ui-design/assets/pattern-showcase/index.html +163 -0
- package/dist/microi.skills/ui-design/assets/pattern-showcase/styles.css +311 -0
- package/dist/microi.skills/ui-design/assets/templates/MCI-DESIGN.md +98 -0
- package/dist/microi.skills/ui-design/references/design-pattern-library.md +171 -0
- package/dist/microi.skills/ui-design/references/mci-design-contract.md +84 -0
- package/dist/microi.skills/ui-design/references/motion-and-media.md +71 -0
- package/dist/microi.skills/ui-design/references/product-flow-recipes.md +94 -0
- package/dist/microi.skills/uniapp-mall-assets/SKILL.md +105 -0
- package/dist/microi.skills/v8-api-config/SKILL.md +272 -0
- package/dist/microi.skills/v8-cache-pattern/SKILL.md +286 -0
- package/dist/microi.skills/v8-crud-api/SKILL.md +398 -0
- package/dist/microi.skills/v8-debugging/SKILL.md +279 -0
- package/dist/microi.skills/v8-explorer-tree/SKILL.md +224 -0
- package/dist/microi.skills/v8-export-import/SKILL.md +590 -0
- package/dist/microi.skills/v8-file-upload/SKILL.md +497 -0
- package/dist/microi.skills/v8-formengine-http/SKILL.md +218 -0
- package/dist/microi.skills/v8-frontend-events/SKILL.md +349 -0
- package/dist/microi.skills/v8-frontend-events/references/bluetooth-print-api.md +107 -0
- package/dist/microi.skills/v8-frontend-events/references/bluetooth-print.md +185 -0
- package/dist/microi.skills/v8-http-integration/SKILL.md +379 -0
- package/dist/microi.skills/v8-image-processing/SKILL.md +187 -0
- package/dist/microi.skills/v8-image-processing/agents/openai.yaml +4 -0
- package/dist/microi.skills/v8-image-processing/references/api-reference.md +620 -0
- package/dist/microi.skills/v8-menu-buttons/SKILL.md +661 -0
- package/dist/microi.skills/v8-mongodb/SKILL.md +149 -0
- package/dist/microi.skills/v8-mq-mqtt/SKILL.md +227 -0
- package/dist/microi.skills/v8-saas-multi-tenant/SKILL.md +193 -0
- package/dist/microi.skills/v8-security/SKILL.md +417 -0
- package/dist/microi.skills/v8-sql-query/SKILL.md +290 -0
- package/dist/microi.skills/v8-table-event/SKILL.md +385 -0
- package/dist/microi.skills/v8-template-engine/SKILL.md +165 -0
- package/dist/microi.skills/v8-utilities/SKILL.md +79 -0
- package/dist/microi.skills/v8-utilities/references/client-api-index.md +136 -0
- package/dist/microi.skills/v8-utilities/references/platform-http-routes.md +80 -0
- package/dist/microi.skills/v8-utilities/references/server-api-index.md +129 -0
- package/dist/microi.skills/v8-workflow/SKILL.md +322 -0
- package/dist/microi.skills/workspace-conventions/SKILL.md +479 -0
- package/package.json +40 -0
|
@@ -0,0 +1,651 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Microi AI Application authentication bridge.
|
|
3
|
+
*
|
|
4
|
+
* Anonymous users may browse an application's UI and use explicitly anonymous,
|
|
5
|
+
* server-scoped app_* operations. Requests are sent to ApiEngine first; only an
|
|
6
|
+
* authoritative authentication response opens the shared login dialog and
|
|
7
|
+
* retries once. Server-side ApiEngine remains the authority for persistence and
|
|
8
|
+
* UserId isolation.
|
|
9
|
+
*/
|
|
10
|
+
import V8 from './microi.v8.js';
|
|
11
|
+
import JSEncrypt from '../Microi.Client/node_modules/jsencrypt/bin/jsencrypt.min.js';
|
|
12
|
+
|
|
13
|
+
const nativeFetch = typeof window !== 'undefined' && window.fetch
|
|
14
|
+
? window.fetch.bind(window)
|
|
15
|
+
: null;
|
|
16
|
+
const NativeXHR = typeof window !== 'undefined' ? window.XMLHttpRequest : null;
|
|
17
|
+
const AUTH_CODES = new Set([401, -1, 1001, 1002]);
|
|
18
|
+
// Stop before Microi's `--OsClient--tenant--` suffix. Interface-engine keys
|
|
19
|
+
// created for AI applications use the shared app_ prefix and underscore words.
|
|
20
|
+
const APP_ENGINE_PATH = /\/apiengine\/(app_[a-z0-9_]+)/i;
|
|
21
|
+
// This is intentionally a positive write list. A naming heuristic must never
|
|
22
|
+
// block an anonymous first screen merely because a read-only engine uses a
|
|
23
|
+
// domain verb such as `calculate`, `convert`, `trend` or `status`. Unknown
|
|
24
|
+
// operations are sent anonymously first; the server-side user guard remains
|
|
25
|
+
// authoritative and returns Code=1001 for a persistent write, at which point
|
|
26
|
+
// the bridge opens the login dialog and retries once.
|
|
27
|
+
const WRITE_ENGINE_KEY = /(?:^|_)(accept|ack|activate|add|adjust|allocate|append|apply|approve|archive|arrive|assign|attach|bind|book|cancel|certify|change|checkin|checkout|claim|clear|clock|close|collect|complete|confirm|consume|create|decide|decline|delete|depart|detach|dispatch|drop|end|event|execute|expire|finalize|finish|handover|hide|hold|import|ingest|initialize|insert|invite|issue|join|leave|lock|mark|move|occupy|open|order|pack|pass|pause|pay|pick|post|prepare|process|propose|publish|quarantine|raise|rebuild|receive|recall|reconcile|record|redeem|refund|register|reject|release|remove|reopen|reorder|replace|request|reschedule|reset|resolve|restore|resume|retire|retry|return|reverse|review|revoke|rollback|rotate|run|save|schedule|scrap|seal|seat|send|serve|set|settle|ship|simulate|skip|snapshot|start|submit|suspend|take|toggle|transfer|transition|unassign|update|upt|vacate|verify|vote|watched|withdraw)(?:_|$)/i;
|
|
28
|
+
const OSCLIENT_SUFFIX = /--OsClient--[^/]*--$/i;
|
|
29
|
+
const DEFAULT_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
|
|
30
|
+
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC7q21EG3HiSFNO9XFUJoMeyz2R
|
|
31
|
+
XaFX8UgCFE4d4pvK6IvQsWunm+WfYqgrSzBMS1LH1fstmZB0wnVUX1uGROaZTKGZ
|
|
32
|
+
1rS/MVn4i6CsPgP9Q7nFV6dZvbxro1byH/E3CV/Q1CgCDeue9FzQUlWQ+UZld8Jg
|
|
33
|
+
1DsI9VJ7gTHGL3R7sQIDAQAB
|
|
34
|
+
-----END PUBLIC KEY-----`;
|
|
35
|
+
|
|
36
|
+
let loginPromise = null;
|
|
37
|
+
let modal = null;
|
|
38
|
+
let sysConfig = {};
|
|
39
|
+
let captchaId = '';
|
|
40
|
+
let captchaObjectUrl = '';
|
|
41
|
+
let lastUserIntentAt = 0;
|
|
42
|
+
let validatedSessionToken = '';
|
|
43
|
+
const USER_INTENT_WINDOW_MS = 30000;
|
|
44
|
+
|
|
45
|
+
function installUserIntentTracking() {
|
|
46
|
+
if (document.documentElement.dataset.microiAiUserIntentTracking === 'true') return;
|
|
47
|
+
document.documentElement.dataset.microiAiUserIntentTracking = 'true';
|
|
48
|
+
const mark = event => {
|
|
49
|
+
if (event && event.isTrusted === false) return;
|
|
50
|
+
lastUserIntentAt = Date.now();
|
|
51
|
+
};
|
|
52
|
+
['pointerdown', 'keydown', 'input', 'change', 'submit'].forEach(type => {
|
|
53
|
+
document.addEventListener(type, mark, true);
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function hasRecentUserIntent() {
|
|
58
|
+
const active = typeof navigator !== 'undefined' && navigator.userActivation
|
|
59
|
+
? navigator.userActivation.isActive
|
|
60
|
+
: false;
|
|
61
|
+
return active || Date.now() - lastUserIntentAt <= USER_INTENT_WINDOW_MS;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function flag(value) {
|
|
65
|
+
if (value === true || value === 1) return true;
|
|
66
|
+
const text = String(value == null ? '' : value).trim().toLowerCase();
|
|
67
|
+
return text === '1' || text === 'true' || text === 'yes' || text === 'on';
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function normalizeBase(value) {
|
|
71
|
+
return String(value || '').trim().replace(/\/+$/, '');
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function contextValue() {
|
|
75
|
+
let microData = {};
|
|
76
|
+
try {
|
|
77
|
+
microData = window.microApp && typeof window.microApp.getData === 'function'
|
|
78
|
+
? (window.microApp.getData() || {})
|
|
79
|
+
: {};
|
|
80
|
+
} catch (error) {}
|
|
81
|
+
return { ...window.__MICROI_APP_CONTEXT__, ...microData };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function runtime() {
|
|
85
|
+
const query = new URLSearchParams(window.location.search);
|
|
86
|
+
const context = contextValue();
|
|
87
|
+
let apiBase = context.apiBase || context.ApiBase || window.MicroiApiBase
|
|
88
|
+
|| query.get('apiBase') || query.get('ApiBase') || '';
|
|
89
|
+
let osClient = context.osClient || context.OsClient || window.MicroiOsClient
|
|
90
|
+
|| query.get('OsClient') || query.get('osClient') || '';
|
|
91
|
+
if (!apiBase && /(^|\.)static\.itdos\.com$/i.test(window.location.hostname)) {
|
|
92
|
+
apiBase = 'https://api.itdos.com';
|
|
93
|
+
}
|
|
94
|
+
if (!osClient && /(^|\.)static\.itdos\.com$/i.test(window.location.hostname)) {
|
|
95
|
+
osClient = 'iTdos';
|
|
96
|
+
}
|
|
97
|
+
if (!apiBase) apiBase = window.location.origin;
|
|
98
|
+
if (!osClient) osClient = localStorage.getItem('OsClient') || 'iTdos';
|
|
99
|
+
apiBase = normalizeBase(apiBase);
|
|
100
|
+
window.__MICROI_APP_CONTEXT__ = {
|
|
101
|
+
...context,
|
|
102
|
+
apiBase,
|
|
103
|
+
ApiBase: apiBase,
|
|
104
|
+
osClient: String(osClient),
|
|
105
|
+
OsClient: String(osClient)
|
|
106
|
+
};
|
|
107
|
+
window.MicroiApiBase = apiBase;
|
|
108
|
+
window.MicroiOsClient = String(osClient);
|
|
109
|
+
document.documentElement.dataset.microiAiAuthReady = 'true';
|
|
110
|
+
document.documentElement.dataset.microiOsClient = String(osClient);
|
|
111
|
+
try {
|
|
112
|
+
// Many generated applications read `window.microApp.getData()` first and
|
|
113
|
+
// use `{}` as the fallback. In a standalone HDFS page that empty object is
|
|
114
|
+
// truthy and masks `__MICROI_APP_CONTEXT__`, so expose the same context
|
|
115
|
+
// through a tiny compatible microApp facade. A real host-provided getData
|
|
116
|
+
// function is preserved and merged with the portable runtime defaults.
|
|
117
|
+
const microApp = window.microApp || (window.microApp = {});
|
|
118
|
+
if (typeof microApp.getData !== 'function') {
|
|
119
|
+
const getData = function () { return { ...(window.__MICROI_APP_CONTEXT__ || {}) }; };
|
|
120
|
+
getData.__microiRuntimeFallback = true;
|
|
121
|
+
microApp.getData = getData;
|
|
122
|
+
} else if (!microApp.getData.__microiRuntimeFallback) {
|
|
123
|
+
const originalGetData = microApp.getData.bind(microApp);
|
|
124
|
+
const getData = function () {
|
|
125
|
+
let current = {};
|
|
126
|
+
try { current = originalGetData() || {}; } catch (error) {}
|
|
127
|
+
return { ...(window.__MICROI_APP_CONTEXT__ || {}), ...current };
|
|
128
|
+
};
|
|
129
|
+
getData.__microiRuntimeFallback = true;
|
|
130
|
+
microApp.getData = getData;
|
|
131
|
+
}
|
|
132
|
+
} catch (error) {}
|
|
133
|
+
V8.configure({
|
|
134
|
+
apiBase,
|
|
135
|
+
osClient: String(osClient),
|
|
136
|
+
clientType: /Mobi|Android|iPhone|iPad/i.test(navigator.userAgent) ? 'Mobile' : 'PC'
|
|
137
|
+
});
|
|
138
|
+
return { apiBase, osClient: String(osClient) };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function normalizeToken(value) {
|
|
142
|
+
return String(value || '').replace(/^Bearer\s+/i, '').trim();
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function isAppEngineUrl(value) {
|
|
146
|
+
return APP_ENGINE_PATH.test(String(value || ''));
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function appEngineKey(value) {
|
|
150
|
+
const match = String(value || '').match(APP_ENGINE_PATH);
|
|
151
|
+
return match ? match[1] : '';
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function isLikelyWrite(value) {
|
|
155
|
+
const key = appEngineKey(value);
|
|
156
|
+
return Boolean(key) && WRITE_ENGINE_KEY.test(key);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function rewriteApiUrl(value) {
|
|
160
|
+
const raw = String(value || '');
|
|
161
|
+
if (!isAppEngineUrl(raw)) return raw;
|
|
162
|
+
try {
|
|
163
|
+
const target = new URL(raw, window.location.href);
|
|
164
|
+
const current = new URL(window.location.href);
|
|
165
|
+
const resolved = runtime();
|
|
166
|
+
target.pathname = target.pathname.replace(OSCLIENT_SUFFIX, '');
|
|
167
|
+
if (target.origin === current.origin && resolved.apiBase !== current.origin) {
|
|
168
|
+
return resolved.apiBase + target.pathname + target.search + target.hash;
|
|
169
|
+
}
|
|
170
|
+
return target.toString();
|
|
171
|
+
} catch (error) {}
|
|
172
|
+
return raw;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function setRequestHeaders(headers) {
|
|
176
|
+
const resolved = runtime();
|
|
177
|
+
const next = new Headers(headers || {});
|
|
178
|
+
next.delete('OsClient');
|
|
179
|
+
next.set('osclient', resolved.osClient);
|
|
180
|
+
next.set('did', V8.getDid());
|
|
181
|
+
const token = normalizeToken(V8.getToken());
|
|
182
|
+
if (token) {
|
|
183
|
+
next.set('Token', token);
|
|
184
|
+
next.set('Authorization', `Bearer ${token}`);
|
|
185
|
+
} else {
|
|
186
|
+
next.delete('Token');
|
|
187
|
+
next.delete('Authorization');
|
|
188
|
+
}
|
|
189
|
+
return next;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function authenticatedIdentity() {
|
|
193
|
+
const user = V8.getUser() || {};
|
|
194
|
+
const id = String(user.Id || user.id || user.UserId || '').trim();
|
|
195
|
+
const name = String(user.Name || user.name || user.Account || user.account || '').trim();
|
|
196
|
+
return id ? { id, name } : null;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function requestIdentity() {
|
|
200
|
+
const authenticated = authenticatedIdentity();
|
|
201
|
+
if (authenticated) return authenticated;
|
|
202
|
+
const deviceId = String(V8.getDid() || 'browser')
|
|
203
|
+
.replace(/[^a-z0-9_-]/gi, '')
|
|
204
|
+
.slice(0, 80) || 'browser';
|
|
205
|
+
return { id: `anon_${deviceId}`, name: '访客' };
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function applyIdentityToObject(value) {
|
|
209
|
+
const identity = requestIdentity();
|
|
210
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return value;
|
|
211
|
+
return {
|
|
212
|
+
...value,
|
|
213
|
+
ClientKey: identity.id,
|
|
214
|
+
ActorKey: identity.id,
|
|
215
|
+
UserId: identity.id,
|
|
216
|
+
UserName: identity.name
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function applyIdentityToBody(body, headers) {
|
|
221
|
+
if (!body) return body;
|
|
222
|
+
if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) {
|
|
223
|
+
const identity = requestIdentity();
|
|
224
|
+
const next = new URLSearchParams(body);
|
|
225
|
+
next.set('ClientKey', identity.id);
|
|
226
|
+
next.set('ActorKey', identity.id);
|
|
227
|
+
next.set('UserId', identity.id);
|
|
228
|
+
next.set('UserName', identity.name);
|
|
229
|
+
return next;
|
|
230
|
+
}
|
|
231
|
+
if (typeof FormData !== 'undefined' && body instanceof FormData) {
|
|
232
|
+
const identity = requestIdentity();
|
|
233
|
+
const next = new FormData();
|
|
234
|
+
for (const pair of body.entries()) next.append(pair[0], pair[1]);
|
|
235
|
+
next.set('ClientKey', identity.id);
|
|
236
|
+
next.set('ActorKey', identity.id);
|
|
237
|
+
next.set('UserId', identity.id);
|
|
238
|
+
next.set('UserName', identity.name);
|
|
239
|
+
return next;
|
|
240
|
+
}
|
|
241
|
+
if (typeof body !== 'string') return body;
|
|
242
|
+
const contentType = String(new Headers(headers || {}).get('content-type') || '').toLowerCase();
|
|
243
|
+
if (contentType.includes('application/x-www-form-urlencoded')) {
|
|
244
|
+
return applyIdentityToBody(new URLSearchParams(body), headers).toString();
|
|
245
|
+
}
|
|
246
|
+
if (contentType.includes('application/json') || /^[\s]*[\[{]/.test(body)) {
|
|
247
|
+
try { return JSON.stringify(applyIdentityToObject(JSON.parse(body))); } catch (error) {}
|
|
248
|
+
}
|
|
249
|
+
return body;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function bodyAuthExpired(body, status) {
|
|
253
|
+
if (Number(status) === 401 || AUTH_CODES.has(Number(body && body.Code))) return true;
|
|
254
|
+
const message = String(body && (body.Msg || body.Message || body.message) || '');
|
|
255
|
+
if (/(?:请先|需要|尚未|未)登录|登录后|Token.*(?:失效|缺失|过期)/i.test(message)) return true;
|
|
256
|
+
if (V8.getToken()) return false;
|
|
257
|
+
return /没有权限|无权限|身份验证/i.test(message);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function bodyAction(body, headers) {
|
|
261
|
+
let value = body;
|
|
262
|
+
if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) {
|
|
263
|
+
value = Object.fromEntries(body.entries());
|
|
264
|
+
} else if (typeof FormData !== 'undefined' && body instanceof FormData) {
|
|
265
|
+
value = Object.fromEntries(body.entries());
|
|
266
|
+
} else if (typeof body === 'string') {
|
|
267
|
+
const contentType = String(new Headers(headers || {}).get('content-type') || '').toLowerCase();
|
|
268
|
+
try {
|
|
269
|
+
value = contentType.includes('application/x-www-form-urlencoded')
|
|
270
|
+
? Object.fromEntries(new URLSearchParams(body).entries())
|
|
271
|
+
: JSON.parse(body);
|
|
272
|
+
} catch (error) { value = null; }
|
|
273
|
+
}
|
|
274
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return '';
|
|
275
|
+
return String(value.Action || value.action || value.Command || value.command || value.Operation || value.operation || '');
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function bodyLikelyWrites(body, headers) {
|
|
279
|
+
const action = bodyAction(body, headers);
|
|
280
|
+
return Boolean(action) && WRITE_ENGINE_KEY.test(`_${action}_`);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function registerUrl(path) {
|
|
284
|
+
const local = /^(localhost|127\.0\.0\.1)$/i.test(window.location.hostname);
|
|
285
|
+
return `${local ? 'http://localhost:2015' : 'https://microi.net'}/${path}`;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
function injectStyles() {
|
|
289
|
+
if (document.getElementById('microi-ai-auth-style')) return;
|
|
290
|
+
const style = document.createElement('style');
|
|
291
|
+
style.id = 'microi-ai-auth-style';
|
|
292
|
+
style.textContent = `
|
|
293
|
+
.mci-auth-mask{position:fixed;inset:0;z-index:2147483646;background:rgba(15,23,42,.52);backdrop-filter:blur(7px);display:flex;align-items:center;justify-content:center;padding:20px;font-family:Inter,"PingFang SC","Microsoft YaHei",sans-serif}
|
|
294
|
+
.mci-auth-mask[hidden]{display:none!important}
|
|
295
|
+
.mci-auth-card{width:min(420px,100%);background:#fff;border:1px solid rgba(148,163,184,.24);border-radius:20px;box-shadow:0 28px 80px rgba(15,23,42,.28);padding:30px;color:#172033;position:relative}
|
|
296
|
+
.mci-auth-close{position:absolute;right:18px;top:16px;border:0;background:transparent;color:#64748b;font-size:24px;cursor:pointer}
|
|
297
|
+
.mci-auth-brand{display:flex;align-items:center;gap:10px;color:#135ee8;font-weight:800;font-size:15px;letter-spacing:.04em}.mci-auth-logo{width:32px;height:32px;border-radius:10px;background:linear-gradient(135deg,#1769ff,#05a8bf);display:grid;place-items:center;color:#fff;font-size:18px}
|
|
298
|
+
.mci-auth-title{font-size:25px;line-height:1.25;margin:22px 0 6px;font-weight:760}.mci-auth-sub{font-size:14px;color:#64748b;margin:0 0 22px}
|
|
299
|
+
.mci-auth-field{display:block;margin:0 0 14px}.mci-auth-field span{display:block;font-size:13px;font-weight:650;margin:0 0 7px}.mci-auth-field input{box-sizing:border-box;width:100%;height:46px;border:1px solid #dbe3ef;border-radius:11px;padding:0 13px;font-size:15px;outline:0;background:#f8fafc;color:#172033}.mci-auth-field input:focus{border-color:#1769ff;box-shadow:0 0 0 3px rgba(23,105,255,.12);background:#fff}
|
|
300
|
+
.mci-auth-captcha{display:grid;grid-template-columns:1fr 120px;gap:10px}.mci-auth-captcha img{width:120px;height:46px;object-fit:cover;border-radius:10px;border:1px solid #dbe3ef;cursor:pointer}
|
|
301
|
+
.mci-auth-captcha-field[hidden],.mci-auth-privacy[hidden]{display:none!important}
|
|
302
|
+
.mci-auth-privacy{display:flex;gap:8px;align-items:flex-start;color:#64748b;font-size:13px;margin:2px 0 14px}.mci-auth-privacy input{margin-top:2px}.mci-auth-message{min-height:20px;margin:0 0 8px;color:#dc2626;font-size:13px}.mci-auth-submit{width:100%;height:46px;border:0;border-radius:11px;background:linear-gradient(135deg,#1769ff,#0e88d8);color:#fff;font-size:15px;font-weight:700;cursor:pointer;box-shadow:0 10px 26px rgba(23,105,255,.25)}.mci-auth-submit:disabled{opacity:.65;cursor:wait}
|
|
303
|
+
.mci-auth-links{display:flex;justify-content:space-between;margin-top:16px;font-size:13px}.mci-auth-links a{color:#1769ff;text-decoration:none}.mci-auth-note{margin:18px 0 0;padding:12px 14px;border-radius:11px;background:#eff6ff;color:#475569;font-size:12px;line-height:1.65}
|
|
304
|
+
@media(prefers-color-scheme:dark){.mci-auth-card{background:#111827;color:#f8fafc;border-color:#334155}.mci-auth-field input{background:#0f172a;border-color:#334155;color:#f8fafc}.mci-auth-sub,.mci-auth-privacy,.mci-auth-note{color:#aab6c8}.mci-auth-note{background:#172554}}
|
|
305
|
+
`;
|
|
306
|
+
document.head.appendChild(style);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function ensureModal() {
|
|
310
|
+
if (modal) return modal;
|
|
311
|
+
injectStyles();
|
|
312
|
+
const mask = document.createElement('div');
|
|
313
|
+
mask.className = 'mci-auth-mask';
|
|
314
|
+
mask.hidden = true;
|
|
315
|
+
mask.innerHTML = `
|
|
316
|
+
<form class="mci-auth-card" autocomplete="on">
|
|
317
|
+
<button class="mci-auth-close" type="button" aria-label="关闭">×</button>
|
|
318
|
+
<div class="mci-auth-brand"><span class="mci-auth-logo">M</span><span>Microi 吾码</span></div>
|
|
319
|
+
<h2 class="mci-auth-title">登录后继续操作</h2>
|
|
320
|
+
<p class="mci-auth-sub">应用可以匿名浏览,保存的业务数据将安全归属到您的账号。</p>
|
|
321
|
+
<label class="mci-auth-field"><span>账号</span><input name="account" autocomplete="username" required placeholder="手机号或账号"></label>
|
|
322
|
+
<label class="mci-auth-field"><span>密码</span><input name="password" type="password" autocomplete="current-password" required placeholder="请输入登录密码"></label>
|
|
323
|
+
<label class="mci-auth-field mci-auth-captcha-field" hidden><span>验证码</span><div class="mci-auth-captcha"><input name="captcha" autocomplete="off" placeholder="图形验证码"><img alt="点击刷新验证码"></div></label>
|
|
324
|
+
<label class="mci-auth-privacy" hidden><input name="privacy" type="checkbox"><span></span></label>
|
|
325
|
+
<div class="mci-auth-message" role="alert"></div>
|
|
326
|
+
<button class="mci-auth-submit" type="submit">登录并继续</button>
|
|
327
|
+
<div class="mci-auth-links"><a data-link="register" target="_blank">注册账号</a><a data-link="forgot" target="_blank">忘记密码</a></div>
|
|
328
|
+
<p class="mci-auth-note">登录只在您保存、提交或修改数据时需要;继续浏览不会创建个人数据。</p>
|
|
329
|
+
</form>`;
|
|
330
|
+
document.body.appendChild(mask);
|
|
331
|
+
const form = mask.querySelector('form');
|
|
332
|
+
mask.querySelector('[data-link="register"]').href = registerUrl('register.html');
|
|
333
|
+
mask.querySelector('[data-link="forgot"]').href = registerUrl('login.html#forgot');
|
|
334
|
+
modal = {
|
|
335
|
+
mask,
|
|
336
|
+
form,
|
|
337
|
+
account: form.elements.account,
|
|
338
|
+
password: form.elements.password,
|
|
339
|
+
captcha: form.elements.captcha,
|
|
340
|
+
captchaField: mask.querySelector('.mci-auth-captcha-field'),
|
|
341
|
+
captchaImage: mask.querySelector('.mci-auth-captcha img'),
|
|
342
|
+
privacy: form.elements.privacy,
|
|
343
|
+
privacyLabel: mask.querySelector('.mci-auth-privacy'),
|
|
344
|
+
privacyText: mask.querySelector('.mci-auth-privacy span'),
|
|
345
|
+
message: mask.querySelector('.mci-auth-message'),
|
|
346
|
+
submit: mask.querySelector('.mci-auth-submit'),
|
|
347
|
+
close: mask.querySelector('.mci-auth-close')
|
|
348
|
+
};
|
|
349
|
+
modal.account.value = localStorage.getItem('microi_last_login_account') || '';
|
|
350
|
+
modal.captchaImage.addEventListener('click', () => void loadCaptcha());
|
|
351
|
+
return modal;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
async function jsonRequest(path, options = {}) {
|
|
355
|
+
if (!nativeFetch) throw new Error('当前浏览器不支持网络请求');
|
|
356
|
+
const resolved = runtime();
|
|
357
|
+
const response = await nativeFetch(resolved.apiBase + path, options);
|
|
358
|
+
const text = await response.text();
|
|
359
|
+
let body;
|
|
360
|
+
try { body = JSON.parse(text); } catch (error) { body = { Code: 0, Msg: text || `HTTP ${response.status}` }; }
|
|
361
|
+
return { response, body };
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
async function loadSysConfig() {
|
|
365
|
+
const resolved = runtime();
|
|
366
|
+
const result = await jsonRequest('/api/FormEngine/GetSysConfig', {
|
|
367
|
+
method: 'POST',
|
|
368
|
+
headers: { 'Content-Type': 'application/json', osclient: resolved.osClient, did: V8.getDid() },
|
|
369
|
+
body: JSON.stringify({ OsClient: resolved.osClient, _SearchEqual: { IsEnable: 1 } })
|
|
370
|
+
});
|
|
371
|
+
if (!result.body || Number(result.body.Code) !== 1) {
|
|
372
|
+
throw new Error((result.body && result.body.Msg) || '系统登录配置加载失败');
|
|
373
|
+
}
|
|
374
|
+
sysConfig = result.body.Data || {};
|
|
375
|
+
return sysConfig;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
async function loadCaptcha() {
|
|
379
|
+
const view = ensureModal();
|
|
380
|
+
view.captchaField.hidden = true;
|
|
381
|
+
view.captchaImage.removeAttribute('src');
|
|
382
|
+
if (!flag(sysConfig.EnableCaptcha)) {
|
|
383
|
+
captchaId = '';
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
const resolved = runtime();
|
|
387
|
+
const response = await nativeFetch(`${resolved.apiBase}/api/Captcha/GetCaptcha?OsClient=${encodeURIComponent(resolved.osClient)}`, {
|
|
388
|
+
headers: { osclient: resolved.osClient, did: V8.getDid() }
|
|
389
|
+
});
|
|
390
|
+
if (!response.ok) throw new Error('验证码加载失败');
|
|
391
|
+
captchaId = response.headers.get('captchaid') || '';
|
|
392
|
+
if (!captchaId) throw new Error('验证码标识缺失,请刷新后重试');
|
|
393
|
+
const captchaBlob = await response.blob();
|
|
394
|
+
if (!captchaBlob.size) throw new Error('验证码图片为空,请刷新后重试');
|
|
395
|
+
if (captchaObjectUrl) URL.revokeObjectURL(captchaObjectUrl);
|
|
396
|
+
captchaObjectUrl = URL.createObjectURL(captchaBlob);
|
|
397
|
+
await new Promise((resolve, reject) => {
|
|
398
|
+
const done = (callback) => {
|
|
399
|
+
window.clearTimeout(timer);
|
|
400
|
+
view.captchaImage.onload = null;
|
|
401
|
+
view.captchaImage.onerror = null;
|
|
402
|
+
callback();
|
|
403
|
+
};
|
|
404
|
+
const timer = window.setTimeout(() => done(() => reject(new Error('验证码图片加载超时'))), 8000);
|
|
405
|
+
view.captchaImage.onload = () => done(resolve);
|
|
406
|
+
view.captchaImage.onerror = () => done(() => reject(new Error('验证码图片解析失败')));
|
|
407
|
+
view.captchaImage.src = captchaObjectUrl;
|
|
408
|
+
});
|
|
409
|
+
view.captchaField.hidden = false;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
function encryptPassword(password) {
|
|
413
|
+
const publicKey = window.MicroiLoginPublicKey
|
|
414
|
+
|| String(sysConfig.LoginRsaPublicKey || '').replace(/\\n/g, '\n').trim()
|
|
415
|
+
|| DEFAULT_PUBLIC_KEY;
|
|
416
|
+
if (!publicKey) return password;
|
|
417
|
+
const encryptor = new JSEncrypt();
|
|
418
|
+
encryptor.setPublicKey(publicKey);
|
|
419
|
+
const encrypted = encryptor.encrypt(password);
|
|
420
|
+
if (!encrypted) throw new Error('密码加密失败,请刷新后重试');
|
|
421
|
+
return encrypted;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
async function performLogin() {
|
|
425
|
+
const view = ensureModal();
|
|
426
|
+
const account = String(view.account.value || '').trim();
|
|
427
|
+
const password = String(view.password.value || '');
|
|
428
|
+
if (!account) throw new Error('请输入账号');
|
|
429
|
+
if (!password) throw new Error('请输入密码');
|
|
430
|
+
if (flag(sysConfig.EnablePrivacyPolicy) && !view.privacy.checked) {
|
|
431
|
+
throw new Error(`请先勾选${sysConfig.PrivacyPolicyName || '同意隐私协议'}`);
|
|
432
|
+
}
|
|
433
|
+
const resolved = runtime();
|
|
434
|
+
const data = new URLSearchParams();
|
|
435
|
+
data.set('Account', account);
|
|
436
|
+
data.set('Pwd', encryptPassword(password));
|
|
437
|
+
data.set('OsClient', resolved.osClient);
|
|
438
|
+
data.set('_ClientType', V8.config.clientType || 'PC');
|
|
439
|
+
if (flag(sysConfig.EnableCaptcha)) {
|
|
440
|
+
data.set('_CaptchaId', captchaId);
|
|
441
|
+
data.set('_CaptchaValue', String(view.captcha.value || '').trim());
|
|
442
|
+
}
|
|
443
|
+
const result = await jsonRequest('/api/SysUser/Login', {
|
|
444
|
+
method: 'POST',
|
|
445
|
+
headers: {
|
|
446
|
+
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
|
|
447
|
+
osclient: resolved.osClient,
|
|
448
|
+
did: V8.getDid()
|
|
449
|
+
},
|
|
450
|
+
body: data.toString()
|
|
451
|
+
});
|
|
452
|
+
if (!result.body || Number(result.body.Code) !== 1) {
|
|
453
|
+
if (flag(sysConfig.EnableCaptcha)) await loadCaptcha();
|
|
454
|
+
throw new Error((result.body && result.body.Msg) || '登录失败');
|
|
455
|
+
}
|
|
456
|
+
const token = normalizeToken(
|
|
457
|
+
result.response.headers.get('authorization')
|
|
458
|
+
|| result.response.headers.get('token')
|
|
459
|
+
|| result.body.Token
|
|
460
|
+
|| (result.body.Data && (result.body.Data.Token || result.body.Data.Authorization))
|
|
461
|
+
);
|
|
462
|
+
if (!token) throw new Error('登录成功但未收到 Token,请检查服务端登录响应');
|
|
463
|
+
V8.setToken(token);
|
|
464
|
+
V8.setUser(result.body.Data || {});
|
|
465
|
+
validatedSessionToken = token;
|
|
466
|
+
localStorage.setItem('microi_last_login_account', account);
|
|
467
|
+
window.dispatchEvent(new CustomEvent('microi:ai-app-login', { detail: result.body.Data || {} }));
|
|
468
|
+
return result.body.Data || {};
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
async function validateCachedLogin() {
|
|
472
|
+
const token = normalizeToken(V8.getToken());
|
|
473
|
+
if (!token) return null;
|
|
474
|
+
const cachedUser = V8.getUser() || {};
|
|
475
|
+
if (validatedSessionToken === token && authenticatedIdentity()) return cachedUser;
|
|
476
|
+
|
|
477
|
+
const resolved = runtime();
|
|
478
|
+
const result = await jsonRequest('/api/SysUser/GetCurrentUser', {
|
|
479
|
+
method: 'POST',
|
|
480
|
+
headers: {
|
|
481
|
+
'Content-Type': 'application/json',
|
|
482
|
+
osclient: resolved.osClient,
|
|
483
|
+
did: V8.getDid(),
|
|
484
|
+
Token: token,
|
|
485
|
+
Authorization: `Bearer ${token}`
|
|
486
|
+
},
|
|
487
|
+
body: JSON.stringify({ OsClient: resolved.osClient, _ClientType: V8.config.clientType || 'PC' })
|
|
488
|
+
});
|
|
489
|
+
const refreshedToken = normalizeToken(
|
|
490
|
+
result.response.headers.get('authorization') || result.response.headers.get('token') || token
|
|
491
|
+
);
|
|
492
|
+
const user = result.body && Number(result.body.Code) === 1 ? (result.body.Data || {}) : {};
|
|
493
|
+
const userId = String(user.Id || user.id || user.UserId || '').trim();
|
|
494
|
+
if (result.response.ok && userId) {
|
|
495
|
+
if (refreshedToken) V8.setToken(refreshedToken);
|
|
496
|
+
V8.setUser(user);
|
|
497
|
+
validatedSessionToken = refreshedToken || token;
|
|
498
|
+
return user;
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
V8.clearToken();
|
|
502
|
+
validatedSessionToken = '';
|
|
503
|
+
return null;
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
async function showLogin() {
|
|
507
|
+
const currentUser = await validateCachedLogin();
|
|
508
|
+
if (currentUser) return currentUser;
|
|
509
|
+
if (loginPromise) return loginPromise;
|
|
510
|
+
const view = ensureModal();
|
|
511
|
+
document.documentElement.dataset.microiAiAuthState = 'prompt';
|
|
512
|
+
view.mask.hidden = false;
|
|
513
|
+
view.message.textContent = '';
|
|
514
|
+
view.submit.disabled = false;
|
|
515
|
+
view.account.focus();
|
|
516
|
+
loginPromise = new Promise(async (resolve, reject) => {
|
|
517
|
+
let finished = false;
|
|
518
|
+
const cleanup = () => {
|
|
519
|
+
view.form.removeEventListener('submit', submit);
|
|
520
|
+
view.close.removeEventListener('click', cancel);
|
|
521
|
+
view.mask.removeEventListener('click', outside);
|
|
522
|
+
};
|
|
523
|
+
const cancel = () => {
|
|
524
|
+
if (finished) return;
|
|
525
|
+
finished = true;
|
|
526
|
+
cleanup();
|
|
527
|
+
view.mask.hidden = true;
|
|
528
|
+
reject(new Error('已取消登录'));
|
|
529
|
+
};
|
|
530
|
+
const outside = (event) => { if (event.target === view.mask) cancel(); };
|
|
531
|
+
const submit = async (event) => {
|
|
532
|
+
event.preventDefault();
|
|
533
|
+
view.submit.disabled = true;
|
|
534
|
+
view.message.textContent = '';
|
|
535
|
+
try {
|
|
536
|
+
const user = await performLogin();
|
|
537
|
+
finished = true;
|
|
538
|
+
cleanup();
|
|
539
|
+
view.mask.hidden = true;
|
|
540
|
+
resolve(user);
|
|
541
|
+
} catch (error) {
|
|
542
|
+
view.message.textContent = error && error.message ? error.message : String(error);
|
|
543
|
+
} finally {
|
|
544
|
+
view.submit.disabled = false;
|
|
545
|
+
}
|
|
546
|
+
};
|
|
547
|
+
view.form.addEventListener('submit', submit);
|
|
548
|
+
view.close.addEventListener('click', cancel);
|
|
549
|
+
view.mask.addEventListener('click', outside);
|
|
550
|
+
try {
|
|
551
|
+
await loadSysConfig();
|
|
552
|
+
view.privacyLabel.hidden = !flag(sysConfig.EnablePrivacyPolicy);
|
|
553
|
+
view.privacyText.textContent = sysConfig.PrivacyPolicyName || '同意隐私协议';
|
|
554
|
+
await loadCaptcha();
|
|
555
|
+
} catch (error) {
|
|
556
|
+
view.message.textContent = error && error.message ? error.message : String(error);
|
|
557
|
+
}
|
|
558
|
+
}).finally(() => { loginPromise = null; });
|
|
559
|
+
return loginPromise;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
async function fetchWithAuth(input, init = {}, retried = false) {
|
|
563
|
+
const rawUrl = typeof input === 'string' || input instanceof URL ? String(input) : input.url;
|
|
564
|
+
const appRequest = isAppEngineUrl(rawUrl);
|
|
565
|
+
if (!appRequest) return nativeFetch(input, init);
|
|
566
|
+
const writeRequest = isLikelyWrite(rawUrl) || bodyLikelyWrites(init.body, init.headers);
|
|
567
|
+
const promptAllowed = hasRecentUserIntent();
|
|
568
|
+
document.documentElement.dataset.microiLastEngine = appEngineKey(rawUrl) || '';
|
|
569
|
+
document.documentElement.dataset.microiWriteDetected = writeRequest ? 'true' : 'false';
|
|
570
|
+
document.documentElement.dataset.microiHasToken = V8.getToken() ? 'true' : 'false';
|
|
571
|
+
const headers = setRequestHeaders(init.headers || (input && input.headers));
|
|
572
|
+
const target = typeof input === 'string' || input instanceof URL ? rewriteApiUrl(rawUrl) : input;
|
|
573
|
+
const requestBody = applyIdentityToBody(init.body, headers);
|
|
574
|
+
const response = await nativeFetch(target, { ...init, headers, body: requestBody });
|
|
575
|
+
let responseBody = null;
|
|
576
|
+
try { responseBody = await response.clone().json(); } catch (error) {}
|
|
577
|
+
if (!retried && bodyAuthExpired(responseBody, response.status) && promptAllowed) {
|
|
578
|
+
V8.clearToken();
|
|
579
|
+
await showLogin();
|
|
580
|
+
return fetchWithAuth(input, init, true);
|
|
581
|
+
}
|
|
582
|
+
const returnedToken = normalizeToken(response.headers.get('authorization') || response.headers.get('token'));
|
|
583
|
+
if (returnedToken) V8.setToken(returnedToken);
|
|
584
|
+
return response;
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
function installFetchBridge() {
|
|
588
|
+
if (!nativeFetch || window.fetch.__microiAiAuthBridge) return;
|
|
589
|
+
const bridged = function (input, init) { return fetchWithAuth(input, init || {}); };
|
|
590
|
+
bridged.__microiAiAuthBridge = true;
|
|
591
|
+
window.fetch = bridged;
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
function installXhrBridge() {
|
|
595
|
+
if (!NativeXHR || NativeXHR.prototype.__microiAiAuthBridge) return;
|
|
596
|
+
const open = NativeXHR.prototype.open;
|
|
597
|
+
const send = NativeXHR.prototype.send;
|
|
598
|
+
const setRequestHeader = NativeXHR.prototype.setRequestHeader;
|
|
599
|
+
NativeXHR.prototype.open = function (method, url, async, user, password) {
|
|
600
|
+
this.__microiMethod = method;
|
|
601
|
+
this.__microiUrl = String(url || '');
|
|
602
|
+
return open.call(this, method, rewriteApiUrl(url), async === undefined ? true : async, user, password);
|
|
603
|
+
};
|
|
604
|
+
NativeXHR.prototype.send = function (body) {
|
|
605
|
+
if (!isAppEngineUrl(this.__microiUrl)) return send.call(this, body);
|
|
606
|
+
const promptAllowed = hasRecentUserIntent();
|
|
607
|
+
const execute = () => {
|
|
608
|
+
const resolved = runtime();
|
|
609
|
+
setRequestHeader.call(this, 'osclient', resolved.osClient);
|
|
610
|
+
setRequestHeader.call(this, 'did', V8.getDid());
|
|
611
|
+
const token = normalizeToken(V8.getToken());
|
|
612
|
+
if (token) {
|
|
613
|
+
setRequestHeader.call(this, 'Token', token);
|
|
614
|
+
setRequestHeader.call(this, 'Authorization', `Bearer ${token}`);
|
|
615
|
+
}
|
|
616
|
+
this.addEventListener('load', () => {
|
|
617
|
+
try {
|
|
618
|
+
const result = JSON.parse(this.responseText || '{}');
|
|
619
|
+
if (bodyAuthExpired(result, this.status) && promptAllowed) {
|
|
620
|
+
V8.clearToken();
|
|
621
|
+
void showLogin();
|
|
622
|
+
}
|
|
623
|
+
} catch (error) {}
|
|
624
|
+
}, { once: true });
|
|
625
|
+
const requestBody = applyIdentityToBody(body, { 'content-type': this.__microiContentType || '' });
|
|
626
|
+
send.call(this, requestBody);
|
|
627
|
+
};
|
|
628
|
+
execute();
|
|
629
|
+
};
|
|
630
|
+
NativeXHR.prototype.setRequestHeader = function (name, value) {
|
|
631
|
+
const normalized = String(name || '').toLowerCase();
|
|
632
|
+
if (normalized === 'content-type') this.__microiContentType = String(value || '');
|
|
633
|
+
if (normalized === 'osclient') return;
|
|
634
|
+
return setRequestHeader.call(this, name, value);
|
|
635
|
+
};
|
|
636
|
+
NativeXHR.prototype.__microiAiAuthBridge = true;
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
runtime();
|
|
640
|
+
installUserIntentTracking();
|
|
641
|
+
installFetchBridge();
|
|
642
|
+
installXhrBridge();
|
|
643
|
+
window.MicroiV8 = window.MicroiV8 || V8;
|
|
644
|
+
window.MicroiAiAppAuth = {
|
|
645
|
+
login: showLogin,
|
|
646
|
+
logout() { validatedSessionToken = ''; V8.clearToken(); window.dispatchEvent(new Event('microi:ai-app-logout')); },
|
|
647
|
+
getUser: () => V8.getUser(),
|
|
648
|
+
getToken: () => V8.getToken(),
|
|
649
|
+
getDid: () => V8.getDid(),
|
|
650
|
+
runtime
|
|
651
|
+
};
|