@amaster.ai/client 1.1.71 → 1.1.73
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +63 -0
- package/dist/index.cjs +910 -27
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +25 -4
- package/dist/index.d.ts +25 -4
- package/dist/index.js +903 -30
- package/dist/index.js.map +1 -1
- package/package.json +12 -11
- package/types/auth/index.d.ts +7 -0
- package/types/common.d.ts +3 -0
- package/types/http.d.ts +8 -130
- package/types/index.d.ts +38 -2
package/dist/index.js
CHANGED
|
@@ -1,16 +1,19 @@
|
|
|
1
|
-
import { createAuthClient } from '@amaster.ai/auth-client';
|
|
1
|
+
import { createStoredAuthReader, createStoredApplicationAuthReader, takePreservedLegacyAccessToken, readCachedAuthUser, createStorageAdapter, createAuthClient, createConsumerUIHint } from '@amaster.ai/auth-client';
|
|
2
|
+
export { completeOAuthPopup, createMemoryStorage } from '@amaster.ai/auth-client';
|
|
2
3
|
import { createEntityClient } from '@amaster.ai/entity-client';
|
|
3
4
|
import { createBpmClient } from '@amaster.ai/bpm-client';
|
|
4
5
|
import { createWorkflowClient, createChatflowClient } from '@amaster.ai/workflow-client';
|
|
5
6
|
export { ChatflowStreamError } from '@amaster.ai/workflow-client';
|
|
6
|
-
import {
|
|
7
|
+
import { createASRHttpClient, createASRClient } from '@amaster.ai/asr-client';
|
|
7
8
|
import { createCopilotClient } from '@amaster.ai/copilot-client';
|
|
8
9
|
export { createAutoVoiceReplyController, createCopilotFileManager } from '@amaster.ai/copilot-client';
|
|
9
10
|
import { createFunctionClient } from '@amaster.ai/function-client';
|
|
10
11
|
import { createTTSClient } from '@amaster.ai/tts-client';
|
|
11
12
|
export { createTTSSpeakController, preprocessTTSContent, splitTextIntoFragments } from '@amaster.ai/tts-client';
|
|
12
13
|
import { createS3Client } from '@amaster.ai/s3-client';
|
|
13
|
-
import { createHttpClient } from '@amaster.ai/http-client';
|
|
14
|
+
import { RequestScopeController, RequestScopeError, createHttpClient } from '@amaster.ai/http-client';
|
|
15
|
+
import { TenancyCapabilityError, parseTenancyAccount, sameSubject, createConsumerAuthorization, createTenancyClient, parseAuthorization } from '@amaster.ai/auth-client/tenancy';
|
|
16
|
+
export { TenancyCapabilityError } from '@amaster.ai/auth-client/tenancy';
|
|
14
17
|
|
|
15
18
|
// src/client.ts
|
|
16
19
|
|
|
@@ -562,11 +565,748 @@ function createKnowledgeClient(http) {
|
|
|
562
565
|
}
|
|
563
566
|
};
|
|
564
567
|
}
|
|
565
|
-
|
|
566
|
-
|
|
568
|
+
function failure(code, status, captured) {
|
|
569
|
+
return { data: null, status, error: { code, status, message: code }, scopeCapture: captured };
|
|
570
|
+
}
|
|
571
|
+
function waitForRefresh(operation, scope, captured, signal) {
|
|
572
|
+
return new Promise((resolve, reject) => {
|
|
573
|
+
let remove = () => {
|
|
574
|
+
};
|
|
575
|
+
const clean = () => {
|
|
576
|
+
remove();
|
|
577
|
+
signal?.removeEventListener?.("abort", abort);
|
|
578
|
+
};
|
|
579
|
+
const abort = () => {
|
|
580
|
+
clean();
|
|
581
|
+
reject(new Error("request_cancelled"));
|
|
582
|
+
};
|
|
583
|
+
operation.then(
|
|
584
|
+
(value) => {
|
|
585
|
+
clean();
|
|
586
|
+
resolve(value);
|
|
587
|
+
},
|
|
588
|
+
(error) => {
|
|
589
|
+
clean();
|
|
590
|
+
reject(error);
|
|
591
|
+
}
|
|
592
|
+
);
|
|
593
|
+
try {
|
|
594
|
+
remove = scope.onInvalidate(captured, abort);
|
|
595
|
+
} catch (error) {
|
|
596
|
+
reject(error);
|
|
597
|
+
return;
|
|
598
|
+
}
|
|
599
|
+
if (signal?.aborted) abort();
|
|
600
|
+
else signal?.addEventListener?.("abort", abort, { once: true });
|
|
601
|
+
});
|
|
602
|
+
}
|
|
603
|
+
function createScopedHttpClient(transport, scope, auth, autoRefresh, onUnauthorized) {
|
|
604
|
+
let refreshing = null;
|
|
605
|
+
return {
|
|
606
|
+
async request(config) {
|
|
607
|
+
let captured;
|
|
608
|
+
try {
|
|
609
|
+
const token = auth.getAccessToken();
|
|
610
|
+
const dispatchRevision = auth.getCredentialRevision();
|
|
611
|
+
if (auth.getAccessToken() !== token) return failure("scope_changed", 409);
|
|
612
|
+
captured = config.scopeCapture ?? scope.capture(config.scopeLevel ?? "tenant");
|
|
613
|
+
scope.assertCurrent(captured);
|
|
614
|
+
if (!token) return failure("unauthenticated", 401, captured);
|
|
615
|
+
const headers = Object.fromEntries(
|
|
616
|
+
Object.entries(config.headers ?? {}).filter(
|
|
617
|
+
([name]) => name.toLowerCase() !== "authorization"
|
|
618
|
+
)
|
|
619
|
+
);
|
|
620
|
+
const send = (accessToken) => transport.request({
|
|
621
|
+
...config,
|
|
622
|
+
scopeCapture: captured,
|
|
623
|
+
headers: { ...headers, Authorization: `Bearer ${accessToken}` }
|
|
624
|
+
});
|
|
625
|
+
const assertCurrent = () => {
|
|
626
|
+
auth.getAccessToken();
|
|
627
|
+
scope.assertCurrent(captured);
|
|
628
|
+
};
|
|
629
|
+
let result = await send(token);
|
|
630
|
+
assertCurrent();
|
|
631
|
+
const method = String(config.method ?? "GET").toUpperCase();
|
|
632
|
+
const safeRead = ["GET", "HEAD", "OPTIONS"].includes(method) || method === "POST" && config.url === "/api/tenancy/authorize";
|
|
633
|
+
if (autoRefresh && safeRead && !token.startsWith("amsvc1.") && result.status === 401) {
|
|
634
|
+
const revision = auth.getCredentialRevision();
|
|
635
|
+
assertCurrent();
|
|
636
|
+
const alreadyRenewed = revision !== dispatchRevision ? auth.getAccessToken() : null;
|
|
637
|
+
if (alreadyRenewed && alreadyRenewed !== token) {
|
|
638
|
+
result = await send(alreadyRenewed);
|
|
639
|
+
assertCurrent();
|
|
640
|
+
if (result.status === 401) onUnauthorized?.();
|
|
641
|
+
return result;
|
|
642
|
+
}
|
|
643
|
+
if (!refreshing || refreshing.revision !== revision) {
|
|
644
|
+
const flight = { revision, promise: auth.refreshToken() };
|
|
645
|
+
refreshing = flight;
|
|
646
|
+
void flight.promise.finally(() => {
|
|
647
|
+
if (refreshing === flight) refreshing = null;
|
|
648
|
+
}).catch(() => {
|
|
649
|
+
});
|
|
650
|
+
}
|
|
651
|
+
const refreshed = await waitForRefresh(
|
|
652
|
+
refreshing.promise,
|
|
653
|
+
scope,
|
|
654
|
+
captured,
|
|
655
|
+
config.signal
|
|
656
|
+
);
|
|
657
|
+
assertCurrent();
|
|
658
|
+
if (refreshed.error) return { ...refreshed, data: null, scopeCapture: captured };
|
|
659
|
+
const nextToken = auth.getAccessToken();
|
|
660
|
+
assertCurrent();
|
|
661
|
+
if (!nextToken || nextToken !== refreshed.data?.accessToken)
|
|
662
|
+
return failure("scope_changed", 409, captured);
|
|
663
|
+
result = await send(nextToken);
|
|
664
|
+
assertCurrent();
|
|
665
|
+
}
|
|
666
|
+
if (result.status === 401) onUnauthorized?.();
|
|
667
|
+
return result;
|
|
668
|
+
} catch (error) {
|
|
669
|
+
if (error instanceof RequestScopeError)
|
|
670
|
+
return failure(error.code, error.status, captured);
|
|
671
|
+
if (captured && !scope.isCurrent(captured))
|
|
672
|
+
return failure("scope_changed", 409, captured);
|
|
673
|
+
if (config.signal?.aborted) return failure("request_cancelled", 0, captured);
|
|
674
|
+
return failure("dependency_unverifiable", 503, captured);
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
};
|
|
678
|
+
}
|
|
679
|
+
async function discoverApplicationScope(options) {
|
|
680
|
+
const asserted = /* @__PURE__ */ new Map();
|
|
681
|
+
const headers = Object.fromEntries(
|
|
682
|
+
Object.entries(options.headers ?? {}).filter(([key]) => {
|
|
683
|
+
if (key.toLowerCase() === "x-app-tenant-id") throw new RequestScopeError("invalid_scope");
|
|
684
|
+
return key.toLowerCase() !== "authorization";
|
|
685
|
+
})
|
|
686
|
+
);
|
|
687
|
+
for (const [key, raw] of Object.entries(headers)) {
|
|
688
|
+
const name = key.toLowerCase();
|
|
689
|
+
const field = ["x-tenant-id", "x-app-id", "x-app-code"].includes(name) ? "applicationCode" : ["x-env", "env"].includes(name) ? "environment" : null;
|
|
690
|
+
if (!field) continue;
|
|
691
|
+
const candidate = new RequestScopeController({
|
|
692
|
+
applicationCode: field === "applicationCode" ? raw : "context",
|
|
693
|
+
environment: field === "environment" ? raw : "dev",
|
|
694
|
+
storage: null
|
|
695
|
+
});
|
|
696
|
+
const value2 = candidate[field];
|
|
697
|
+
if (asserted.has(field) && asserted.get(field) !== value2)
|
|
698
|
+
throw new RequestScopeError("invalid_scope");
|
|
699
|
+
asserted.set(field, value2);
|
|
700
|
+
}
|
|
701
|
+
if (asserted.has("applicationCode")) headers["x-tenant-id"] = asserted.get("applicationCode");
|
|
702
|
+
if (asserted.has("environment")) headers["x-env"] = asserted.get("environment");
|
|
703
|
+
const http = createHttpClient({
|
|
704
|
+
baseURL: options.baseURL,
|
|
705
|
+
withCredentials: options.withCredentials,
|
|
706
|
+
runtime: options.runtime,
|
|
707
|
+
headers,
|
|
708
|
+
transformResponse: (body) => {
|
|
709
|
+
if (body && typeof body === "object" && "statusCode" in body && body.statusCode === 200 && "data" in body)
|
|
710
|
+
return body.data;
|
|
711
|
+
return null;
|
|
712
|
+
}
|
|
713
|
+
});
|
|
714
|
+
const result = await http.request({
|
|
715
|
+
url: "/api/auth/context",
|
|
716
|
+
method: "GET",
|
|
717
|
+
maxRedirects: 0,
|
|
718
|
+
timeout: 1e4,
|
|
719
|
+
headers: { "Cache-Control": "no-cache" }
|
|
720
|
+
});
|
|
721
|
+
if (result.error) throw Object.assign(new Error(result.error.message), result.error);
|
|
722
|
+
const data = result.data;
|
|
723
|
+
const unavailable = () => Object.assign(new Error("Cannot verify application context"), {
|
|
724
|
+
status: 503,
|
|
725
|
+
code: "dependency_unverifiable"
|
|
726
|
+
});
|
|
727
|
+
if (!data || typeof data !== "object" || Array.isArray(data)) throw unavailable();
|
|
728
|
+
const value = data;
|
|
729
|
+
if (value.protocolVersion !== "1" || typeof value.applicationCode !== "string" || typeof value.environment !== "string" || typeof value.tenancyEnabled !== "boolean" || value.tenantSelectionEnabled !== void 0 && (value.tenantSelectionEnabled !== false || !value.tenancyEnabled) || value.legacySessionMigration !== void 0 && typeof value.legacySessionMigration !== "boolean" || value.legacySessionMigration === true && !value.tenancyEnabled)
|
|
730
|
+
throw unavailable();
|
|
731
|
+
const scope = { applicationCode: value.applicationCode, environment: value.environment };
|
|
732
|
+
try {
|
|
733
|
+
const validated = new RequestScopeController(scope);
|
|
734
|
+
if (validated.environment !== scope.environment) throw unavailable();
|
|
735
|
+
} catch {
|
|
736
|
+
throw unavailable();
|
|
737
|
+
}
|
|
738
|
+
for (const [field, value2] of asserted)
|
|
739
|
+
if (scope[field] !== value2) throw new RequestScopeError("invalid_scope");
|
|
740
|
+
return {
|
|
741
|
+
scope,
|
|
742
|
+
tenancyEnabled: value.tenancyEnabled,
|
|
743
|
+
...value.tenantSelectionEnabled === false ? { tenantSelectionEnabled: false } : {},
|
|
744
|
+
...value.legacySessionMigration === true ? { legacySessionMigration: true } : {}
|
|
745
|
+
};
|
|
746
|
+
}
|
|
747
|
+
function createInitializationFactories(options, http, getToken, getUserUid, wait, check, generation, getAccountScope) {
|
|
748
|
+
function guard(target, asyncMethods, localMethods, cleanup) {
|
|
749
|
+
let epoch = 0;
|
|
750
|
+
let destroyed = false;
|
|
751
|
+
return new Proxy(target, {
|
|
752
|
+
get(owner, property, receiver) {
|
|
753
|
+
const value = Reflect.get(owner, property, receiver);
|
|
754
|
+
if (typeof value !== "function" || typeof property !== "string") return value;
|
|
755
|
+
if (asyncMethods.includes(property))
|
|
756
|
+
return async (...args) => {
|
|
757
|
+
const expected = epoch;
|
|
758
|
+
const scopeGeneration = generation();
|
|
759
|
+
await wait();
|
|
760
|
+
if (destroyed || expected !== epoch || scopeGeneration !== generation())
|
|
761
|
+
throw Object.assign(
|
|
762
|
+
new Error("Instance operation was cancelled during initialization"),
|
|
763
|
+
{ code: "scope_changed", status: 409 }
|
|
764
|
+
);
|
|
765
|
+
return value.apply(owner, args);
|
|
766
|
+
};
|
|
767
|
+
return (...args) => {
|
|
768
|
+
if (cleanup.includes(property)) {
|
|
769
|
+
epoch++;
|
|
770
|
+
if (property === "destroy") destroyed = true;
|
|
771
|
+
} else if (!localMethods.includes(property)) check();
|
|
772
|
+
return value.apply(owner, args);
|
|
773
|
+
};
|
|
774
|
+
}
|
|
775
|
+
});
|
|
776
|
+
}
|
|
777
|
+
const auth = { getAccessToken: getToken };
|
|
778
|
+
const copilot = createCopilotClient(
|
|
779
|
+
{ request: (config) => http.request({ ...config, scopeLevel: "application", preserveBusinessResponse: true }) },
|
|
780
|
+
options.baseURL,
|
|
781
|
+
getToken,
|
|
782
|
+
getUserUid,
|
|
783
|
+
getAccountScope
|
|
784
|
+
);
|
|
785
|
+
return {
|
|
786
|
+
asr: (config) => guard(
|
|
787
|
+
createASRClient(auth)(config),
|
|
788
|
+
["connect", "startRecording", "stopRecording"],
|
|
789
|
+
["isRecording", "isConnected"],
|
|
790
|
+
["close"]
|
|
791
|
+
),
|
|
792
|
+
asrHttp: (config) => guard(
|
|
793
|
+
createASRHttpClient({ ...auth, http })(config),
|
|
794
|
+
["startRecording", "stopRecording", "recordAndRecognize", "recognizeFile", "recognizeUrl"],
|
|
795
|
+
[],
|
|
796
|
+
[]
|
|
797
|
+
),
|
|
798
|
+
tts: (config) => guard(
|
|
799
|
+
createTTSClient(auth)(config),
|
|
800
|
+
["connect", "speak"],
|
|
801
|
+
["isConnected", "hasAudio", "isResponseDone", "isPlaying", "isStreamingPlayback"],
|
|
802
|
+
["close", "stop"]
|
|
803
|
+
),
|
|
804
|
+
copilot: {
|
|
805
|
+
createConversationController: (config) => guard(
|
|
806
|
+
copilot.createConversationController(config),
|
|
807
|
+
[
|
|
808
|
+
"init",
|
|
809
|
+
"sendMessage",
|
|
810
|
+
"cancelChat",
|
|
811
|
+
"startNewConversation",
|
|
812
|
+
"loadHistory",
|
|
813
|
+
"loadMoreHistory"
|
|
814
|
+
],
|
|
815
|
+
[
|
|
816
|
+
"getSnapshot",
|
|
817
|
+
"subscribe",
|
|
818
|
+
"resetConversation",
|
|
819
|
+
"getConversation",
|
|
820
|
+
"clearConversation",
|
|
821
|
+
"removeMessage",
|
|
822
|
+
"updateMessage"
|
|
823
|
+
],
|
|
824
|
+
["destroy", "abort"]
|
|
825
|
+
)
|
|
826
|
+
}
|
|
827
|
+
};
|
|
828
|
+
}
|
|
829
|
+
function createAutomaticClient(options, construct) {
|
|
830
|
+
const captured = { ...options, headers: { ...options.headers } };
|
|
831
|
+
let client;
|
|
832
|
+
let instanceAccountScope;
|
|
833
|
+
let tenantSelectionEnabled = true;
|
|
834
|
+
let pendingToken;
|
|
835
|
+
let hintKey;
|
|
836
|
+
try {
|
|
837
|
+
const endpoint = new URL(options.baseURL ?? "", "https://application.invalid");
|
|
838
|
+
if (!endpoint.username && !endpoint.password && !endpoint.search && !endpoint.hash) {
|
|
839
|
+
const contextHeaders = Object.entries(captured.headers).filter(([key]) => ["x-tenant-id", "x-app-id", "x-app-code", "x-env", "env"].includes(key.toLowerCase())).map(([key, value]) => [key.toLowerCase(), value]).sort(([a], [b]) => a.localeCompare(b));
|
|
840
|
+
hintKey = JSON.stringify([options.baseURL ?? "", contextHeaders]);
|
|
841
|
+
}
|
|
842
|
+
} catch {
|
|
843
|
+
}
|
|
844
|
+
const suppliedStorage = options.storage && typeof options.storage.getItem === "function" ? options.storage : void 0;
|
|
845
|
+
const storedApplication = suppliedStorage ? { reader: createStoredAuthReader(void 0, suppliedStorage), clearConsumerHint() {
|
|
846
|
+
}, remember(_value) {
|
|
847
|
+
} } : createStoredApplicationAuthReader(hintKey);
|
|
848
|
+
const storedAuth = storedApplication.reader;
|
|
849
|
+
let failed = false;
|
|
850
|
+
let generation = 0;
|
|
851
|
+
const queued = [];
|
|
852
|
+
const initialize = () => discoverApplicationScope(captured).then(async ({ scope, tenancyEnabled, tenantSelectionEnabled: selectionEnabled, legacySessionMigration }) => {
|
|
853
|
+
tenantSelectionEnabled = selectionEnabled !== false;
|
|
854
|
+
storedApplication.remember({ ...scope, tenancyEnabled });
|
|
855
|
+
if (!tenantSelectionEnabled) storedApplication.clearConsumerHint();
|
|
856
|
+
const legacyToken = !suppliedStorage && legacySessionMigration && pendingToken === void 0 && !createStoredAuthReader(JSON.stringify([scope.applicationCode, scope.environment])).getAccessToken() ? takePreservedLegacyAccessToken(JSON.stringify([scope.applicationCode, scope.environment])) : null;
|
|
857
|
+
const actions = queued.splice(0);
|
|
858
|
+
const servingScope = tenantSelectionEnabled ? scope : { ...scope, storage: null };
|
|
859
|
+
instanceAccountScope = new RequestScopeController({ ...scope, storage: null });
|
|
860
|
+
client = construct({ ...captured, tenancy: tenancyEnabled ? servingScope : void 0 }, (auth2) => {
|
|
861
|
+
auth2.on("credentialsChanged", (kind) => {
|
|
862
|
+
if (kind !== "refresh") instanceAccountScope?.clear();
|
|
863
|
+
});
|
|
864
|
+
if (legacyToken) auth2.setAccessToken(legacyToken);
|
|
865
|
+
actions.filter(({ path }) => path[0] === "auth").forEach(({ method, args }) => auth2[method](...args));
|
|
866
|
+
});
|
|
867
|
+
actions.filter(({ path }) => path[0] !== "auth").forEach(({ path, method, args }) => resolve(path)?.[method](...args));
|
|
868
|
+
queued.splice(0).forEach(({ path, method, args }) => invoke(path, method, args));
|
|
869
|
+
if (tenancyEnabled && legacySessionMigration && client.auth.isAuthenticated())
|
|
870
|
+
await client.auth.getMe();
|
|
871
|
+
});
|
|
872
|
+
const observe = (operation) => {
|
|
873
|
+
void operation.catch(() => {
|
|
874
|
+
failed = true;
|
|
875
|
+
const local = queued.filter(
|
|
876
|
+
({ path, method }) => path[0] === "auth" && ["on", "off", "setAccessToken", "clearAuth"].includes(method) || path[0] === "tenancy" && method === "clearTenant"
|
|
877
|
+
);
|
|
878
|
+
queued.splice(0, queued.length, ...local);
|
|
879
|
+
});
|
|
880
|
+
return operation;
|
|
881
|
+
};
|
|
882
|
+
let initialized = observe(initialize());
|
|
883
|
+
const ready = () => {
|
|
884
|
+
if (failed && !client) {
|
|
885
|
+
failed = false;
|
|
886
|
+
initialized = observe(initialize());
|
|
887
|
+
}
|
|
888
|
+
return initialized;
|
|
889
|
+
};
|
|
890
|
+
const pending = () => Object.assign(new Error("Application context is not ready; await client.ready()"), {
|
|
891
|
+
code: "context_pending",
|
|
892
|
+
status: 503
|
|
893
|
+
});
|
|
894
|
+
const resolve = (path) => path.reduce((value, key) => value?.[key], client);
|
|
895
|
+
const invoke = (path, method, args) => {
|
|
896
|
+
const owner = resolve(path);
|
|
897
|
+
if (!owner) throw new TenancyCapabilityError("tenant APIs on a non-tenancy application");
|
|
898
|
+
return owner[method](...args);
|
|
899
|
+
};
|
|
900
|
+
const changesScope = (path, method) => path[0] === "auth" && /^(login|logout|register|exchangeOAuthLoginTicket|handleOAuthCallback)/.test(method) || path[0] === "tenancy" && method === "selectTenant";
|
|
901
|
+
const afterReady = (path, method, args) => {
|
|
902
|
+
if (path[0] === "tenancy" && method === "selectTenant") storedApplication.clearConsumerHint();
|
|
903
|
+
if (changesScope(path, method)) generation++;
|
|
904
|
+
const capturedGeneration = generation;
|
|
905
|
+
return ready().then(
|
|
906
|
+
() => capturedGeneration === generation ? invoke(path, method, args) : {
|
|
907
|
+
data: null,
|
|
908
|
+
status: 409,
|
|
909
|
+
error: {
|
|
910
|
+
status: 409,
|
|
911
|
+
code: "scope_changed",
|
|
912
|
+
message: "Context changed during initialization"
|
|
913
|
+
}
|
|
914
|
+
},
|
|
915
|
+
(error) => ({
|
|
916
|
+
data: null,
|
|
917
|
+
status: error.status ?? 503,
|
|
918
|
+
error: {
|
|
919
|
+
status: error.status ?? 503,
|
|
920
|
+
code: error.code ?? "dependency_unverifiable",
|
|
921
|
+
message: error.message
|
|
922
|
+
}
|
|
923
|
+
})
|
|
924
|
+
);
|
|
925
|
+
};
|
|
926
|
+
function sync(path, method, args) {
|
|
927
|
+
if (!client && method === "getOAuthLoginURL") {
|
|
928
|
+
const query = new URLSearchParams();
|
|
929
|
+
if (args[1]) query.set("redirect_uri", String(args[1]));
|
|
930
|
+
const path2 = `/api/auth/oauth/${args[0]}${query.size ? `?${query}` : ""}`;
|
|
931
|
+
if (!options.baseURL) return path2;
|
|
932
|
+
return new URL(path2, typeof window === "undefined" ? options.baseURL : new URL(options.baseURL, window.location.href).href).href;
|
|
933
|
+
}
|
|
934
|
+
if (client) {
|
|
935
|
+
if (["setAccessToken", "clearAuth", "loginWithOAuth"].includes(method)) generation++;
|
|
936
|
+
return invoke(path, method, args);
|
|
937
|
+
}
|
|
938
|
+
if (method === "setAccessToken" || method === "clearAuth") {
|
|
939
|
+
generation++;
|
|
940
|
+
pendingToken = method === "setAccessToken" ? args[0] : null;
|
|
941
|
+
queued.push({ path, method, args });
|
|
942
|
+
return;
|
|
943
|
+
}
|
|
944
|
+
if (["on", "off", "loginWithOAuth", "bindOAuth"].includes(method)) {
|
|
945
|
+
if (method === "loginWithOAuth") generation++;
|
|
946
|
+
queued.push({ path, method, args });
|
|
947
|
+
return;
|
|
948
|
+
}
|
|
949
|
+
if (method === "getAccessToken")
|
|
950
|
+
return failed ? null : pendingToken !== void 0 ? pendingToken : storedAuth.getAccessToken();
|
|
951
|
+
if (method === "isAuthenticated") return !!sync(path, "getAccessToken", []);
|
|
952
|
+
if (!failed && pendingToken === void 0 && method in storedAuth)
|
|
953
|
+
return storedAuth[method](...args);
|
|
954
|
+
return false;
|
|
955
|
+
}
|
|
956
|
+
function service(path) {
|
|
957
|
+
return new Proxy(
|
|
958
|
+
{},
|
|
959
|
+
{
|
|
960
|
+
get(_target, property) {
|
|
961
|
+
if (typeof property !== "string" || property === "then") return void 0;
|
|
962
|
+
if (path[0] === "auth" && property === "getCredentialRevision") return void 0;
|
|
963
|
+
if (path[0] === "tenancy") {
|
|
964
|
+
if (property === "enabled") return client ? !!client.tenancy && tenantSelectionEnabled : null;
|
|
965
|
+
if (["applicationCode", "environment", "appTenantId", "subject", "snapshot", "authorization"].includes(
|
|
966
|
+
property
|
|
967
|
+
))
|
|
968
|
+
return resolve(path)?.[property] ?? null;
|
|
969
|
+
if (["capture", "onInvalidate"].includes(property))
|
|
970
|
+
return (...args) => {
|
|
971
|
+
if (!client) throw pending();
|
|
972
|
+
return invoke(path, property, args);
|
|
973
|
+
};
|
|
974
|
+
if (property === "isCurrent")
|
|
975
|
+
return (...args) => client ? invoke(path, property, args) : false;
|
|
976
|
+
if (property === "clearTenant")
|
|
977
|
+
return () => {
|
|
978
|
+
if (client) resolve(path)?.clearTenant();
|
|
979
|
+
else {
|
|
980
|
+
storedApplication.clearConsumerHint();
|
|
981
|
+
generation++;
|
|
982
|
+
queued.push({ path, method: "clearTenant", args: [] });
|
|
983
|
+
}
|
|
984
|
+
};
|
|
985
|
+
if (!["account", "listAccessible", "current", "selectTenant", "authorize"].includes(property))
|
|
986
|
+
return void 0;
|
|
987
|
+
}
|
|
988
|
+
if (path[0] === "auth" && [
|
|
989
|
+
"on",
|
|
990
|
+
"off",
|
|
991
|
+
"setAccessToken",
|
|
992
|
+
"clearAuth",
|
|
993
|
+
"getAccessToken",
|
|
994
|
+
"isAuthenticated",
|
|
995
|
+
"hasRole",
|
|
996
|
+
"hasPermission",
|
|
997
|
+
"hasAnyPermission",
|
|
998
|
+
"hasAllPermissions",
|
|
999
|
+
"loginWithOAuth",
|
|
1000
|
+
"getOAuthLoginURL",
|
|
1001
|
+
"bindOAuth"
|
|
1002
|
+
].includes(property))
|
|
1003
|
+
return (...args) => sync(path, property, args);
|
|
1004
|
+
if (path[0] === "copilot" && property === "createConversationController")
|
|
1005
|
+
return (...args) => {
|
|
1006
|
+
if (!client) return factories.copilot.createConversationController(...args);
|
|
1007
|
+
return invoke(path, property, args);
|
|
1008
|
+
};
|
|
1009
|
+
if (path[0] === "chatflow" && property === "stream")
|
|
1010
|
+
return async function* (...args) {
|
|
1011
|
+
await ready();
|
|
1012
|
+
yield* invoke(path, property, args);
|
|
1013
|
+
};
|
|
1014
|
+
return (...args) => {
|
|
1015
|
+
if (client) {
|
|
1016
|
+
if (changesScope(path, property)) generation++;
|
|
1017
|
+
return invoke(path, property, args);
|
|
1018
|
+
}
|
|
1019
|
+
return afterReady(path, property, args);
|
|
1020
|
+
};
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
);
|
|
1024
|
+
}
|
|
1025
|
+
const auth = service(["auth"]);
|
|
1026
|
+
const checkFactory = () => {
|
|
1027
|
+
if (!client) throw pending();
|
|
1028
|
+
};
|
|
1029
|
+
const factories = createInitializationFactories(
|
|
1030
|
+
captured,
|
|
1031
|
+
service(["http"]),
|
|
1032
|
+
() => auth.getAccessToken(),
|
|
1033
|
+
() => client ? readCachedAuthUser(client.auth)?.uid ?? null : null,
|
|
1034
|
+
async () => {
|
|
1035
|
+
await ready();
|
|
1036
|
+
checkFactory();
|
|
1037
|
+
},
|
|
1038
|
+
checkFactory,
|
|
1039
|
+
() => generation,
|
|
1040
|
+
() => instanceAccountScope
|
|
1041
|
+
);
|
|
1042
|
+
const factory = (name) => (...args) => {
|
|
1043
|
+
if (!client) return factories[name](...args);
|
|
1044
|
+
return invoke([], name, args);
|
|
1045
|
+
};
|
|
1046
|
+
return {
|
|
1047
|
+
ready,
|
|
1048
|
+
auth,
|
|
1049
|
+
tenancy: service(["tenancy"]),
|
|
1050
|
+
entity: service(["entity"]),
|
|
1051
|
+
bpm: service(["bpm"]),
|
|
1052
|
+
workflow: service(["workflow"]),
|
|
1053
|
+
chatflow: service(["chatflow"]),
|
|
1054
|
+
copilot: service(["copilot"]),
|
|
1055
|
+
function: service(["function"]),
|
|
1056
|
+
knowledge: service(["knowledge"]),
|
|
1057
|
+
s3: service(["s3"]),
|
|
1058
|
+
http: service(["http"]),
|
|
1059
|
+
asr: factory("asr"),
|
|
1060
|
+
asrHttp: factory("asrHttp"),
|
|
1061
|
+
tts: factory("tts"),
|
|
1062
|
+
isAuthenticated: () => auth.isAuthenticated(),
|
|
1063
|
+
getAccessToken: () => auth.getAccessToken(),
|
|
1064
|
+
setAccessToken: (token) => auth.setAccessToken(token),
|
|
1065
|
+
clearAuth: () => auth.clearAuth()
|
|
1066
|
+
};
|
|
1067
|
+
}
|
|
1068
|
+
var record = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
1069
|
+
var contextText = (value) => typeof value === "string" && value.length > 0 && value.length <= 4096 && value.trim() === value && // Reject control characters in identifiers received across the trust boundary.
|
|
1070
|
+
// eslint-disable-next-line no-control-regex
|
|
1071
|
+
!/[\u0000-\u001f\u007f]/.test(value);
|
|
1072
|
+
function parseConsumerProfile(value, expected) {
|
|
1073
|
+
if (!record(value) || !record(value.context) || !record(value.profile)) return null;
|
|
1074
|
+
const account = parseTenancyAccount(value);
|
|
1075
|
+
const contextAccount = parseTenancyAccount({ uid: value.uid, subject: value.context.subject });
|
|
1076
|
+
if (!account?.profile || !contextAccount || !sameSubject(account.subject, contextAccount.subject) || value.context.protocolVersion !== "1" || !contextText(value.context.releaseRevision) || !contextText(value.context.executionId))
|
|
1077
|
+
return null;
|
|
1078
|
+
try {
|
|
1079
|
+
const scope = new RequestScopeController({ ...expected, storage: null });
|
|
1080
|
+
if (value.context.applicationCode !== scope.applicationCode || value.context.environment !== scope.environment || typeof value.context.appTenantId !== "string")
|
|
1081
|
+
return null;
|
|
1082
|
+
scope.setSubject(account.subject);
|
|
1083
|
+
scope.selectTenant(value.context.appTenantId);
|
|
1084
|
+
const captured = scope.capture();
|
|
1085
|
+
const authorization = parseAuthorization(value.authorization, captured);
|
|
1086
|
+
if (!authorization) return null;
|
|
1087
|
+
const context = Object.freeze({
|
|
1088
|
+
protocolVersion: "1",
|
|
1089
|
+
applicationCode: scope.applicationCode,
|
|
1090
|
+
environment: scope.environment,
|
|
1091
|
+
appTenantId: scope.appTenantId,
|
|
1092
|
+
subject: account.subject,
|
|
1093
|
+
releaseRevision: value.context.releaseRevision,
|
|
1094
|
+
executionId: value.context.executionId
|
|
1095
|
+
});
|
|
1096
|
+
const user = {
|
|
1097
|
+
...value.profile,
|
|
1098
|
+
...account.profile,
|
|
1099
|
+
roles: [...authorization.roles],
|
|
1100
|
+
permissions: [...authorization.permissions],
|
|
1101
|
+
isSuperAdmin: authorization.isSuperAdmin === true,
|
|
1102
|
+
consumer: { context, authorization }
|
|
1103
|
+
};
|
|
1104
|
+
return { user, context, authorization };
|
|
1105
|
+
} catch {
|
|
1106
|
+
return null;
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
function parseConsumerUser(value, expected) {
|
|
1110
|
+
if (!record(value) || !record(value.consumer) || !record(value.consumer.context)) return null;
|
|
1111
|
+
return parseConsumerProfile(
|
|
1112
|
+
{
|
|
1113
|
+
uid: value.uid,
|
|
1114
|
+
subject: value.consumer.context.subject,
|
|
1115
|
+
profile: value,
|
|
1116
|
+
context: value.consumer.context,
|
|
1117
|
+
authorization: value.consumer.authorization
|
|
1118
|
+
},
|
|
1119
|
+
expected
|
|
1120
|
+
);
|
|
1121
|
+
}
|
|
1122
|
+
function normalizeConsumerResponse(result, expected) {
|
|
1123
|
+
if (result.error || !record(result.data)) return result;
|
|
1124
|
+
const body = result.data;
|
|
1125
|
+
const nested = record(body.user);
|
|
1126
|
+
const candidate = nested ? body.user : body;
|
|
1127
|
+
if (!record(candidate) || candidate.consumer === void 0) return result;
|
|
1128
|
+
const profile = parseConsumerUser(candidate, expected);
|
|
1129
|
+
if (!profile)
|
|
1130
|
+
return {
|
|
1131
|
+
...result,
|
|
1132
|
+
data: null,
|
|
1133
|
+
status: 503,
|
|
1134
|
+
error: { status: 503, code: "dependency_unverifiable", message: "Invalid consumer profile" }
|
|
1135
|
+
};
|
|
1136
|
+
return { ...result, data: nested ? { ...body, user: profile.user } : profile.user };
|
|
1137
|
+
}
|
|
1138
|
+
function createConsumerContext(scope, http, auth, authority) {
|
|
1139
|
+
let defaultSuppressed = false;
|
|
1140
|
+
const failure2 = (code, status, captured) => ({
|
|
1141
|
+
data: null,
|
|
1142
|
+
status,
|
|
1143
|
+
error: { code, status, message: code },
|
|
1144
|
+
scopeCapture: captured
|
|
1145
|
+
});
|
|
1146
|
+
const bind = (profile, token) => {
|
|
1147
|
+
if (!token || auth.getAccessToken() !== token) return failure2("scope_changed", 409);
|
|
1148
|
+
if (scope.currentIdentity && !sameSubject(scope.currentIdentity, profile.context.subject))
|
|
1149
|
+
return failure2("unauthenticated", 401);
|
|
1150
|
+
let before = scope.capture("application");
|
|
1151
|
+
let expected = before.generation + (sameSubject(scope.currentIdentity, profile.context.subject) ? 0 : 1);
|
|
1152
|
+
scope.setSubject(profile.context.subject);
|
|
1153
|
+
if (auth.getAccessToken() !== token || scope.capture("application").generation !== expected)
|
|
1154
|
+
return failure2("scope_changed", 409, before);
|
|
1155
|
+
before = scope.capture("application");
|
|
1156
|
+
expected = before.generation + (scope.appTenantId === profile.context.appTenantId ? 0 : 1);
|
|
1157
|
+
scope.selectTenant(profile.context.appTenantId);
|
|
1158
|
+
if (auth.getAccessToken() !== token || scope.capture("application").generation !== expected || scope.appTenantId !== profile.context.appTenantId)
|
|
1159
|
+
return failure2("scope_changed", 409, before);
|
|
1160
|
+
const captured = scope.capture();
|
|
1161
|
+
const failedInstall = authority.install(
|
|
1162
|
+
profile.authorization,
|
|
1163
|
+
profile.context.releaseRevision,
|
|
1164
|
+
captured
|
|
1165
|
+
);
|
|
1166
|
+
if (failedInstall) return failedInstall;
|
|
1167
|
+
if (initializing?.generation === before.generation)
|
|
1168
|
+
initializing.generation = captured.generation;
|
|
1169
|
+
return { data: profile.user, status: 200, error: null, scopeCapture: captured };
|
|
1170
|
+
};
|
|
1171
|
+
let initializing = null;
|
|
1172
|
+
const loadProfile = async () => {
|
|
1173
|
+
const token = auth.getAccessToken();
|
|
1174
|
+
const accountOnly = defaultSuppressed && !scope.appTenantId;
|
|
1175
|
+
if (!scope.currentIdentity) {
|
|
1176
|
+
const beforeAccount = scope.capture("application");
|
|
1177
|
+
const accountResult = await http.request({
|
|
1178
|
+
url: "/api/tenancy/account",
|
|
1179
|
+
method: "GET",
|
|
1180
|
+
scopeLevel: "application"
|
|
1181
|
+
});
|
|
1182
|
+
if (accountResult.error) return { ...accountResult, data: null };
|
|
1183
|
+
if (!accountResult.scopeCapture || !scope.isCurrent(accountResult.scopeCapture) || !scope.isCurrent(beforeAccount))
|
|
1184
|
+
return failure2("scope_changed", 409, accountResult.scopeCapture);
|
|
1185
|
+
const account2 = parseTenancyAccount(accountResult.data);
|
|
1186
|
+
if (!account2) return failure2("dependency_unverifiable", 503, accountResult.scopeCapture);
|
|
1187
|
+
const expected = beforeAccount.generation + 1;
|
|
1188
|
+
scope.setSubject(account2.subject);
|
|
1189
|
+
if (scope.capture("application").generation !== expected)
|
|
1190
|
+
return failure2("scope_changed", 409, beforeAccount);
|
|
1191
|
+
if (initializing?.generation === beforeAccount.generation) initializing.generation = expected;
|
|
1192
|
+
if (accountOnly && scope.appTenantId) {
|
|
1193
|
+
scope.clearTenant();
|
|
1194
|
+
if (initializing?.generation === expected)
|
|
1195
|
+
initializing.generation = scope.capture("application").generation;
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
const before = scope.capture("application");
|
|
1199
|
+
const result = await http.request({
|
|
1200
|
+
url: accountOnly ? "/api/tenancy/account" : "/api/auth/me",
|
|
1201
|
+
method: "GET",
|
|
1202
|
+
scopeLevel: scope.currentIdentity && scope.appTenantId ? "tenant" : "application"
|
|
1203
|
+
});
|
|
1204
|
+
if (result.error) {
|
|
1205
|
+
if (result.scopeCapture && scope.isCurrent(result.scopeCapture)) {
|
|
1206
|
+
authority.clear();
|
|
1207
|
+
if (result.status === 401 && auth.getAccessToken() === token) auth.clearAuth();
|
|
1208
|
+
}
|
|
1209
|
+
return { ...result, data: null };
|
|
1210
|
+
}
|
|
1211
|
+
if (!result.scopeCapture || !scope.isCurrent(result.scopeCapture) || !scope.isCurrent(before))
|
|
1212
|
+
return failure2("scope_changed", 409, result.scopeCapture);
|
|
1213
|
+
const profile = accountOnly ? null : parseConsumerUser(result.data, scope);
|
|
1214
|
+
if (profile) {
|
|
1215
|
+
if (result.scopeCapture.appTenantId && profile.context.appTenantId !== result.scopeCapture.appTenantId) {
|
|
1216
|
+
authority.clear();
|
|
1217
|
+
return failure2("dependency_unverifiable", 503, result.scopeCapture);
|
|
1218
|
+
}
|
|
1219
|
+
if (scope.currentIdentity && !sameSubject(scope.currentIdentity, profile.context.subject)) {
|
|
1220
|
+
authority.clear();
|
|
1221
|
+
return failure2("unauthenticated", 401, result.scopeCapture);
|
|
1222
|
+
}
|
|
1223
|
+
return { ...result, ...bind(profile, auth.getAccessToken()) };
|
|
1224
|
+
}
|
|
1225
|
+
const raw = result.data && typeof result.data === "object" && !Array.isArray(result.data) ? result.data : null;
|
|
1226
|
+
if (!accountOnly && raw && typeof raw.uid === "string" && scope.currentIdentity && raw.uid !== scope.currentIdentity.id) {
|
|
1227
|
+
authority.clear();
|
|
1228
|
+
return failure2("unauthenticated", 401, before);
|
|
1229
|
+
}
|
|
1230
|
+
const account = accountOnly ? parseTenancyAccount(result.data) : raw && raw.consumer === void 0 && scope.currentIdentity ? parseTenancyAccount({ uid: raw.uid, subject: scope.currentIdentity, profile: raw }) : null;
|
|
1231
|
+
if (account?.profile && !(result.data && typeof result.data === "object" && "context" in result.data)) {
|
|
1232
|
+
if (scope.currentIdentity && !sameSubject(scope.currentIdentity, account.subject)) {
|
|
1233
|
+
authority.clear();
|
|
1234
|
+
return failure2("unauthenticated", 401, before);
|
|
1235
|
+
}
|
|
1236
|
+
const expected = before.generation + (sameSubject(scope.currentIdentity, account.subject) ? 0 : 1);
|
|
1237
|
+
scope.setSubject(account.subject);
|
|
1238
|
+
if (scope.capture("application").generation !== expected)
|
|
1239
|
+
return failure2("scope_changed", 409, before);
|
|
1240
|
+
authority.clear();
|
|
1241
|
+
return {
|
|
1242
|
+
...result,
|
|
1243
|
+
data: { ...accountOnly ? {} : raw, ...account.profile },
|
|
1244
|
+
scopeCapture: scope.capture("application")
|
|
1245
|
+
};
|
|
1246
|
+
}
|
|
1247
|
+
authority.clear();
|
|
1248
|
+
return failure2("dependency_unverifiable", 503, result.scopeCapture);
|
|
1249
|
+
};
|
|
1250
|
+
const getMe = () => {
|
|
1251
|
+
auth.getAccessToken();
|
|
1252
|
+
const generation = scope.capture("application").generation;
|
|
1253
|
+
if (!initializing || initializing.generation !== generation) {
|
|
1254
|
+
const flight = { generation, promise: loadProfile() };
|
|
1255
|
+
initializing = flight;
|
|
1256
|
+
void flight.promise.finally(() => {
|
|
1257
|
+
if (initializing === flight) initializing = null;
|
|
1258
|
+
}).catch(() => {
|
|
1259
|
+
});
|
|
1260
|
+
}
|
|
1261
|
+
return initializing.promise;
|
|
1262
|
+
};
|
|
1263
|
+
return {
|
|
1264
|
+
suppressDefault() {
|
|
1265
|
+
defaultSuppressed = true;
|
|
1266
|
+
},
|
|
1267
|
+
reset() {
|
|
1268
|
+
defaultSuppressed = false;
|
|
1269
|
+
},
|
|
1270
|
+
get pending() {
|
|
1271
|
+
return initializing !== null;
|
|
1272
|
+
},
|
|
1273
|
+
getMe,
|
|
1274
|
+
login(user) {
|
|
1275
|
+
const profile = parseConsumerUser(user, scope);
|
|
1276
|
+
if (profile) bind(profile, auth.getAccessToken());
|
|
1277
|
+
},
|
|
1278
|
+
async ensure() {
|
|
1279
|
+
if (defaultSuppressed && !scope.appTenantId)
|
|
1280
|
+
return failure2(
|
|
1281
|
+
auth.getAccessToken() ? "invalid_scope" : "unauthenticated",
|
|
1282
|
+
auth.getAccessToken() ? 400 : 401
|
|
1283
|
+
);
|
|
1284
|
+
const result = await getMe();
|
|
1285
|
+
if (result.error) return result;
|
|
1286
|
+
if (!result.scopeCapture || !scope.isCurrent(result.scopeCapture))
|
|
1287
|
+
return failure2("scope_changed", 409, result.scopeCapture);
|
|
1288
|
+
if (!scope.currentIdentity || !scope.appTenantId || !authority.current)
|
|
1289
|
+
return failure2("default_tenant_not_ready", 409, result.scopeCapture);
|
|
1290
|
+
return result;
|
|
1291
|
+
}
|
|
1292
|
+
};
|
|
1293
|
+
}
|
|
1294
|
+
function unsupported() {
|
|
1295
|
+
return { data: null, status: 422, error: { status: 422, code: "capability_unsupported", message: "Use the tenancy account and authorization APIs" } };
|
|
1296
|
+
}
|
|
567
1297
|
function createClient(options = {}) {
|
|
1298
|
+
return createAutomaticClient(options, createResolvedClient);
|
|
1299
|
+
}
|
|
1300
|
+
function createResolvedClient(options, beforeAuthInitialize) {
|
|
1301
|
+
if (options.tenancy && options.tenancy.storage === void 0) {
|
|
1302
|
+
const namespace = JSON.stringify([options.tenancy.applicationCode, options.tenancy.environment]);
|
|
1303
|
+
const tenantStorage = options.storage ?? createStorageAdapter(namespace);
|
|
1304
|
+
options = { ...options, tenancy: { ...options.tenancy, storage: tenantStorage } };
|
|
1305
|
+
}
|
|
568
1306
|
const {
|
|
569
1307
|
baseURL,
|
|
1308
|
+
storage,
|
|
1309
|
+
withCredentials,
|
|
570
1310
|
headers = {},
|
|
571
1311
|
onUnauthorized,
|
|
572
1312
|
onTokenExpired,
|
|
@@ -575,12 +1315,58 @@ function createClient(options = {}) {
|
|
|
575
1315
|
runtime,
|
|
576
1316
|
autoRefresh = true
|
|
577
1317
|
} = options;
|
|
1318
|
+
const scope = options.tenancy ? new RequestScopeController(options.tenancy) : void 0;
|
|
1319
|
+
const defaultHeaders = scope ? Object.fromEntries(Object.entries(headers).filter(([key]) => key.toLowerCase() !== "authorization")) : headers;
|
|
1320
|
+
const accountScope = scope ? new RequestScopeController({ applicationCode: scope.applicationCode, environment: scope.environment, storage: null }) : void 0;
|
|
1321
|
+
const authTransport = accountScope ? createHttpClient({ baseURL, withCredentials, headers: defaultHeaders, runtime, requestScope: accountScope }) : void 0;
|
|
1322
|
+
const authHttp = authTransport ? {
|
|
1323
|
+
request: async (config) => {
|
|
1324
|
+
const method = String(config.method ?? "GET").toUpperCase();
|
|
1325
|
+
const permitted = /* @__PURE__ */ new Set([
|
|
1326
|
+
"GET /api/auth/me",
|
|
1327
|
+
"GET /api/tenancy/account",
|
|
1328
|
+
"GET /api/auth/captcha",
|
|
1329
|
+
"GET /api/auth/oauth/feishu/config",
|
|
1330
|
+
"GET /api/auth/oauth-bindings",
|
|
1331
|
+
"PUT /api/auth/me",
|
|
1332
|
+
"POST /api/auth/change-password",
|
|
1333
|
+
"GET /api/auth/sessions",
|
|
1334
|
+
"GET /api/auth/sessions/current",
|
|
1335
|
+
"DELETE /api/auth/sessions",
|
|
1336
|
+
"POST /api/auth/login",
|
|
1337
|
+
"POST /api/auth/register",
|
|
1338
|
+
"POST /api/auth/login-with-code",
|
|
1339
|
+
"POST /api/auth/send-code",
|
|
1340
|
+
"POST /api/auth/logout",
|
|
1341
|
+
"POST /api/auth/refresh",
|
|
1342
|
+
"POST /api/auth/oauth/ticket",
|
|
1343
|
+
"POST /api/auth/oauth/feishu/code",
|
|
1344
|
+
"POST /api/auth/miniprogram/login",
|
|
1345
|
+
"POST /api/auth/miniprogram/douyin/login",
|
|
1346
|
+
"POST /api/auth/miniprogram/phone-login",
|
|
1347
|
+
"POST /api/auth/miniprogram/phone",
|
|
1348
|
+
"POST /api/auth/miniprogram/douyin/phone"
|
|
1349
|
+
]);
|
|
1350
|
+
if (!permitted.has(`${method} ${config.url}`) && !(method === "DELETE" && (/^\/api\/auth\/sessions\/[1-9][0-9]*$/.test(config.url) || /^\/api\/auth\/oauth\/[^/]+\/unbind$/.test(config.url)))) return unsupported();
|
|
1351
|
+
const result = await authTransport.request({
|
|
1352
|
+
...config,
|
|
1353
|
+
scopeLevel: "application"
|
|
1354
|
+
});
|
|
1355
|
+
return normalizeConsumerResponse(result, accountScope);
|
|
1356
|
+
}
|
|
1357
|
+
} : void 0;
|
|
578
1358
|
const baseHttpClient = createHttpClient({
|
|
579
1359
|
baseURL,
|
|
580
|
-
headers,
|
|
581
|
-
|
|
1360
|
+
headers: defaultHeaders,
|
|
1361
|
+
withCredentials,
|
|
1362
|
+
runtime,
|
|
1363
|
+
requestScope: scope
|
|
582
1364
|
});
|
|
1365
|
+
let consumerContext;
|
|
1366
|
+
let credentialRevision = 0;
|
|
583
1367
|
const auth = createAuthClient({
|
|
1368
|
+
storage,
|
|
1369
|
+
withCredentials,
|
|
584
1370
|
autoRefresh,
|
|
585
1371
|
baseURL,
|
|
586
1372
|
headers,
|
|
@@ -588,11 +1374,46 @@ function createClient(options = {}) {
|
|
|
588
1374
|
onUnauthorized,
|
|
589
1375
|
autoHandleOAuthCallback,
|
|
590
1376
|
autoRedirectAfterLogin,
|
|
591
|
-
runtime
|
|
1377
|
+
runtime,
|
|
1378
|
+
storageNamespace: scope ? JSON.stringify([scope.applicationCode, scope.environment]) : void 0,
|
|
1379
|
+
syncUserOnInit: scope ? false : void 0,
|
|
1380
|
+
verifyRefresh: scope && authHttp ? async (accessToken) => {
|
|
1381
|
+
const expected = scope.currentIdentity;
|
|
1382
|
+
const result = await authHttp.request({ url: "/api/tenancy/account", method: "GET", headers: { Authorization: `Bearer ${accessToken}` } });
|
|
1383
|
+
if (result.error) return result.status === 0 ? { ...result, status: 503, error: { ...result.error, status: 503, code: "dependency_unverifiable" } } : result;
|
|
1384
|
+
const account = parseTenancyAccount(result.data);
|
|
1385
|
+
if (!account) return { data: null, status: 503, error: { status: 503, code: "dependency_unverifiable", message: "Invalid account response" } };
|
|
1386
|
+
return !expected || sameSubject(expected, account.subject) ? result : { data: null, status: 401, error: { status: 401, code: "unauthenticated", message: "Refreshed identity changed" } };
|
|
1387
|
+
} : void 0
|
|
1388
|
+
}, authHttp, (initializedAuth) => {
|
|
1389
|
+
initializedAuth.on("credentialsChanged", () => {
|
|
1390
|
+
credentialRevision++;
|
|
1391
|
+
});
|
|
1392
|
+
if (scope) {
|
|
1393
|
+
initializedAuth.on("credentialsChanged", (kind) => {
|
|
1394
|
+
if (kind !== "refresh") {
|
|
1395
|
+
consumerContext?.reset();
|
|
1396
|
+
scope.clear();
|
|
1397
|
+
accountScope?.clear();
|
|
1398
|
+
if (kind === "login") consumerContext?.login(readCachedAuthUser(initializedAuth));
|
|
1399
|
+
}
|
|
1400
|
+
});
|
|
1401
|
+
initializedAuth.on("login", (user) => consumerContext?.login(user));
|
|
1402
|
+
}
|
|
1403
|
+
beforeAuthInitialize?.(initializedAuth);
|
|
592
1404
|
});
|
|
1405
|
+
const credentials = {
|
|
1406
|
+
getAccessToken: () => auth.getAccessToken(),
|
|
1407
|
+
getCredentialRevision: () => {
|
|
1408
|
+
auth.getAccessToken();
|
|
1409
|
+
return credentialRevision;
|
|
1410
|
+
},
|
|
1411
|
+
refreshToken: () => auth.refreshToken()
|
|
1412
|
+
};
|
|
593
1413
|
const createAuthenticatedHttpClient = () => {
|
|
594
1414
|
let isRefreshing = false;
|
|
595
1415
|
let refreshPromise = null;
|
|
1416
|
+
let completedRefresh;
|
|
596
1417
|
function isTokenExpired(result) {
|
|
597
1418
|
if (result.status !== 401) return false;
|
|
598
1419
|
if (result.error?.message && /expired/i.test(result.error.message)) {
|
|
@@ -628,11 +1449,17 @@ function createClient(options = {}) {
|
|
|
628
1449
|
};
|
|
629
1450
|
let result = await baseHttpClient.request(mergedConfig);
|
|
630
1451
|
if (autoRefresh && result.status === 401 && isTokenExpired(result)) {
|
|
631
|
-
|
|
1452
|
+
const alreadyRefreshed = completedRefresh?.source === token && completedRefresh.token === auth.getAccessToken() && completedRefresh.revision === credentials.getCredentialRevision();
|
|
1453
|
+
if (!alreadyRefreshed && !isRefreshing) {
|
|
632
1454
|
isRefreshing = true;
|
|
633
1455
|
refreshPromise = (async () => {
|
|
634
1456
|
try {
|
|
635
1457
|
const refreshResult = await auth.refreshToken();
|
|
1458
|
+
if (refreshResult.data) completedRefresh = {
|
|
1459
|
+
source: token,
|
|
1460
|
+
token: auth.getAccessToken(),
|
|
1461
|
+
revision: credentials.getCredentialRevision()
|
|
1462
|
+
};
|
|
636
1463
|
return !!refreshResult.data;
|
|
637
1464
|
} finally {
|
|
638
1465
|
isRefreshing = false;
|
|
@@ -640,7 +1467,7 @@ function createClient(options = {}) {
|
|
|
640
1467
|
}
|
|
641
1468
|
})();
|
|
642
1469
|
}
|
|
643
|
-
const refreshed = await refreshPromise;
|
|
1470
|
+
const refreshed = alreadyRefreshed || await refreshPromise;
|
|
644
1471
|
if (refreshed) {
|
|
645
1472
|
const newToken = auth.getAccessToken();
|
|
646
1473
|
result = await baseHttpClient.request({
|
|
@@ -659,51 +1486,97 @@ function createClient(options = {}) {
|
|
|
659
1486
|
}
|
|
660
1487
|
};
|
|
661
1488
|
};
|
|
662
|
-
const
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
cachedUserUid = null;
|
|
1489
|
+
const scopedHttp = scope ? createScopedHttpClient(baseHttpClient, scope, credentials, autoRefresh, onUnauthorized) : void 0;
|
|
1490
|
+
const consumerHint = options.tenancy ? createConsumerUIHint(options.tenancy, () => auth.getAccessToken()) : void 0;
|
|
1491
|
+
const authority = scope ? createConsumerAuthorization(scope, consumerHint) : void 0;
|
|
1492
|
+
auth.on("credentialsChanged", (kind) => {
|
|
1493
|
+
if (kind === "refresh" && authority?.current) consumerHint?.write(authority.current);
|
|
1494
|
+
else consumerHint?.clear();
|
|
669
1495
|
});
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
1496
|
+
consumerContext = scope && scopedHttp && authority ? createConsumerContext(scope, scopedHttp, auth, authority) : void 0;
|
|
1497
|
+
const authenticatedHttpClient = scopedHttp && scope && consumerContext ? {
|
|
1498
|
+
async request(config) {
|
|
1499
|
+
const application = config.scopeLevel === "application" || /^\/api\/auth\//.test(config.url);
|
|
1500
|
+
const selectedContextRead = config.url === "/api/tenancy/current" && !!scope.currentIdentity && !!scope.appTenantId;
|
|
1501
|
+
if (!application && (!selectedContextRead && consumerContext.pending || !scope.currentIdentity || !scope.appTenantId)) {
|
|
1502
|
+
const established = await consumerContext.ensure();
|
|
1503
|
+
if (established.error) return { ...established, data: null };
|
|
1504
|
+
if (!established.scopeCapture || !scope.isCurrent(established.scopeCapture)) return {
|
|
1505
|
+
data: null,
|
|
1506
|
+
status: 409,
|
|
1507
|
+
error: { code: "scope_changed", status: 409, message: "scope_changed" }
|
|
1508
|
+
};
|
|
674
1509
|
}
|
|
675
|
-
|
|
676
|
-
|
|
1510
|
+
const business = !/^\/api\/(auth|tenancy)\//.test(config.url);
|
|
1511
|
+
return scopedHttp.request({
|
|
1512
|
+
...config,
|
|
1513
|
+
...application ? { scopeLevel: "application" } : {},
|
|
1514
|
+
preserveBusinessResponse: business
|
|
1515
|
+
});
|
|
1516
|
+
}
|
|
1517
|
+
} : createAuthenticatedHttpClient();
|
|
1518
|
+
const tenancy = scope ? createTenancyClient(scope, authenticatedHttpClient, authority, () => consumerContext?.suppressDefault()) : void 0;
|
|
1519
|
+
if (tenancy) {
|
|
1520
|
+
auth.hasRole = (role) => {
|
|
1521
|
+
auth.getAccessToken();
|
|
1522
|
+
const view = tenancy.authorization ?? consumerHint?.read();
|
|
1523
|
+
return !!view?.isSuperAdmin || (view?.roles.includes(role) ?? false);
|
|
1524
|
+
};
|
|
1525
|
+
auth.hasPermission = (resource, action) => {
|
|
1526
|
+
auth.getAccessToken();
|
|
1527
|
+
const view = tenancy.authorization ?? consumerHint?.read();
|
|
1528
|
+
return !!view?.isSuperAdmin || (view?.permissions.includes(`${resource}.${action}`) ?? false);
|
|
1529
|
+
};
|
|
1530
|
+
auth.hasAnyPermission = (permissions) => permissions.some(({ resource, action }) => auth.hasPermission(resource, action));
|
|
1531
|
+
auth.hasAllPermissions = (permissions) => permissions.every(({ resource, action }) => auth.hasPermission(resource, action));
|
|
677
1532
|
}
|
|
678
|
-
|
|
1533
|
+
if (tenancy && consumerContext) auth.getMe = () => consumerContext.getMe();
|
|
1534
|
+
const entity = createEntityClient(authenticatedHttpClient, { preserveIdentityStrings: !!scope });
|
|
679
1535
|
const bpm = createBpmClient(authenticatedHttpClient);
|
|
680
1536
|
const workflow = createWorkflowClient(authenticatedHttpClient);
|
|
681
1537
|
const chatflow = createChatflowClient(authenticatedHttpClient, {
|
|
682
1538
|
baseURL,
|
|
683
1539
|
headers,
|
|
684
1540
|
getAccessToken: () => auth.getAccessToken(),
|
|
685
|
-
onUnauthorized
|
|
1541
|
+
onUnauthorized,
|
|
1542
|
+
requestScope: scope,
|
|
1543
|
+
beforeStream: consumerContext ? async () => {
|
|
1544
|
+
if (!scope.currentIdentity || !scope.appTenantId || consumerContext.pending) {
|
|
1545
|
+
const result = await consumerContext.ensure();
|
|
1546
|
+
if (result.error) throw Object.assign(new Error(result.error.message), { status: result.status });
|
|
1547
|
+
}
|
|
1548
|
+
} : void 0
|
|
686
1549
|
});
|
|
687
1550
|
const functionClient = createFunctionClient(authenticatedHttpClient);
|
|
688
|
-
const
|
|
1551
|
+
const accountBusinessTransport = accountScope && authTransport ? createScopedHttpClient(authTransport, accountScope, credentials, autoRefresh, onUnauthorized) : void 0;
|
|
1552
|
+
const applicationHttp = accountBusinessTransport ? {
|
|
1553
|
+
async request(config) {
|
|
1554
|
+
return accountBusinessTransport.request({ ...config, scopeLevel: "application", preserveBusinessResponse: true });
|
|
1555
|
+
}
|
|
1556
|
+
} : authenticatedHttpClient;
|
|
1557
|
+
const knowledge = createKnowledgeClient(applicationHttp);
|
|
689
1558
|
const copilot = createCopilotClient(
|
|
690
|
-
|
|
1559
|
+
applicationHttp,
|
|
691
1560
|
baseURL,
|
|
692
1561
|
() => auth.getAccessToken(),
|
|
693
|
-
() =>
|
|
1562
|
+
() => scope?.currentIdentity?.type === "user" ? scope.currentIdentity.id : readCachedAuthUser(auth)?.uid ?? null,
|
|
1563
|
+
accountScope
|
|
694
1564
|
);
|
|
695
|
-
const s3 = createS3Client(
|
|
1565
|
+
const s3 = createS3Client(applicationHttp);
|
|
696
1566
|
const asr = createASRClient({
|
|
697
1567
|
getAccessToken: () => auth.getAccessToken()
|
|
698
1568
|
});
|
|
699
1569
|
const asrHttp = createASRHttpClient({
|
|
700
1570
|
getAccessToken: () => auth.getAccessToken(),
|
|
701
|
-
http:
|
|
1571
|
+
http: applicationHttp
|
|
702
1572
|
});
|
|
703
1573
|
const tts = createTTSClient({
|
|
704
1574
|
getAccessToken: () => auth.getAccessToken()
|
|
705
1575
|
});
|
|
706
1576
|
const client = {
|
|
1577
|
+
ready: async () => {
|
|
1578
|
+
},
|
|
1579
|
+
...tenancy ? { tenancy } : {},
|
|
707
1580
|
auth,
|
|
708
1581
|
entity,
|
|
709
1582
|
bpm,
|