connectbase-client 6.24.0 → 6.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/dist/cli.js +73 -7
- package/dist/connect-base.umd.js +5 -5
- package/dist/index.d.mts +37 -3
- package/dist/index.d.ts +37 -3
- package/dist/index.js +1762 -1694
- package/dist/index.mjs +1762 -1694
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1805,1907 +1805,1953 @@ var AppMembersAPI = class {
|
|
|
1805
1805
|
}
|
|
1806
1806
|
};
|
|
1807
1807
|
|
|
1808
|
-
// src/core/
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
return typeof value === "string" || typeof value === "number" && Number.isFinite(value);
|
|
1823
|
-
}
|
|
1824
|
-
}
|
|
1825
|
-
function assertShape(value, shape, endpoint) {
|
|
1826
|
-
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
1827
|
-
throw new ApiError(
|
|
1828
|
-
502,
|
|
1829
|
-
`[${endpoint}] expected object, got ${typeof value}`,
|
|
1830
|
-
"SCHEMA_MISMATCH"
|
|
1831
|
-
);
|
|
1832
|
-
}
|
|
1833
|
-
const obj = value;
|
|
1834
|
-
for (const [key, spec] of Object.entries(shape)) {
|
|
1835
|
-
const present = key in obj;
|
|
1836
|
-
if (!present) {
|
|
1837
|
-
if (spec.optional) continue;
|
|
1838
|
-
throw new ApiError(
|
|
1839
|
-
502,
|
|
1840
|
-
`[${endpoint}] missing required field "${key}"`,
|
|
1841
|
-
"SCHEMA_MISMATCH"
|
|
1842
|
-
);
|
|
1843
|
-
}
|
|
1844
|
-
const fieldValue = obj[key];
|
|
1845
|
-
if (spec.optional && (fieldValue === null || fieldValue === void 0)) {
|
|
1846
|
-
continue;
|
|
1808
|
+
// src/core/abort.ts
|
|
1809
|
+
var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
|
|
1810
|
+
function createTimeoutController(options = {}) {
|
|
1811
|
+
const controller = new AbortController();
|
|
1812
|
+
const timeout = options.timeout ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
1813
|
+
const external = options.signal;
|
|
1814
|
+
let timeoutId = null;
|
|
1815
|
+
let externalListener = null;
|
|
1816
|
+
if (external) {
|
|
1817
|
+
if (external.aborted) {
|
|
1818
|
+
controller.abort(external.reason);
|
|
1819
|
+
} else {
|
|
1820
|
+
externalListener = () => controller.abort(external.reason);
|
|
1821
|
+
external.addEventListener("abort", externalListener, { once: true });
|
|
1847
1822
|
}
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1823
|
+
}
|
|
1824
|
+
if (timeout > 0 && Number.isFinite(timeout)) {
|
|
1825
|
+
timeoutId = setTimeout(() => {
|
|
1826
|
+
controller.abort(
|
|
1827
|
+
new DOMException(
|
|
1828
|
+
`Request timed out after ${timeout}ms`,
|
|
1829
|
+
"TimeoutError"
|
|
1830
|
+
)
|
|
1853
1831
|
);
|
|
1832
|
+
}, timeout);
|
|
1833
|
+
}
|
|
1834
|
+
return {
|
|
1835
|
+
signal: controller.signal,
|
|
1836
|
+
cleanup: () => {
|
|
1837
|
+
if (timeoutId !== null) clearTimeout(timeoutId);
|
|
1838
|
+
if (external && externalListener) {
|
|
1839
|
+
external.removeEventListener("abort", externalListener);
|
|
1840
|
+
}
|
|
1854
1841
|
}
|
|
1842
|
+
};
|
|
1843
|
+
}
|
|
1844
|
+
function withAbort(promise, signal) {
|
|
1845
|
+
if (!signal) return promise;
|
|
1846
|
+
const reason = () => signal.reason ?? new DOMException("The operation was aborted.", "AbortError");
|
|
1847
|
+
if (signal.aborted) {
|
|
1848
|
+
promise.catch(() => void 0);
|
|
1849
|
+
return Promise.reject(reason());
|
|
1855
1850
|
}
|
|
1856
|
-
return
|
|
1851
|
+
return new Promise((resolve, reject) => {
|
|
1852
|
+
const onAbort = () => reject(reason());
|
|
1853
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1854
|
+
promise.then(
|
|
1855
|
+
(value) => {
|
|
1856
|
+
signal.removeEventListener("abort", onAbort);
|
|
1857
|
+
resolve(value);
|
|
1858
|
+
},
|
|
1859
|
+
(error) => {
|
|
1860
|
+
signal.removeEventListener("abort", onAbort);
|
|
1861
|
+
reject(error);
|
|
1862
|
+
}
|
|
1863
|
+
);
|
|
1864
|
+
});
|
|
1857
1865
|
}
|
|
1858
1866
|
|
|
1859
|
-
// src/
|
|
1860
|
-
var
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
* AnalyticsAPI 주입 — 로그인/가입/로그아웃 시 방문자 트래커에 member_id 를 전달하여
|
|
1867
|
-
* 게스트 방문자를 회원과 연결한다. ConnectBase 컨스트럭터에서 내부적으로 호출된다.
|
|
1868
|
-
*/
|
|
1869
|
-
_attachAnalytics(analytics) {
|
|
1870
|
-
this.analytics = analytics;
|
|
1867
|
+
// src/core/recent-calls.ts
|
|
1868
|
+
var DEFAULT_CAPACITY = 20;
|
|
1869
|
+
var MAX_CAPACITY = 50;
|
|
1870
|
+
var RecentCallsBuffer = class {
|
|
1871
|
+
constructor(capacity = DEFAULT_CAPACITY) {
|
|
1872
|
+
this.buf = [];
|
|
1873
|
+
this.capacity = Math.min(Math.max(1, capacity), MAX_CAPACITY);
|
|
1871
1874
|
}
|
|
1872
|
-
|
|
1873
|
-
if (this.
|
|
1874
|
-
this.
|
|
1875
|
-
return;
|
|
1876
|
-
}
|
|
1877
|
-
if (typeof window === "undefined") return;
|
|
1878
|
-
const bridge = window;
|
|
1879
|
-
if (memberId) {
|
|
1880
|
-
if (typeof bridge.__cbSetMember === "function") {
|
|
1881
|
-
bridge.__cbSetMember(memberId);
|
|
1882
|
-
}
|
|
1883
|
-
} else {
|
|
1884
|
-
if (typeof bridge.__cbClearMember === "function") {
|
|
1885
|
-
bridge.__cbClearMember();
|
|
1886
|
-
}
|
|
1875
|
+
push(call) {
|
|
1876
|
+
if (this.buf.length >= this.capacity) {
|
|
1877
|
+
this.buf.shift();
|
|
1887
1878
|
}
|
|
1879
|
+
this.buf.push(call);
|
|
1888
1880
|
}
|
|
1889
1881
|
/**
|
|
1890
|
-
*
|
|
1891
|
-
* 어떤 로그인 방식이 허용되는지 확인합니다.
|
|
1892
|
-
*
|
|
1893
|
-
* @example
|
|
1894
|
-
* ```typescript
|
|
1895
|
-
* const settings = await client.auth.getAuthSettings()
|
|
1896
|
-
* if (settings.allow_id_password_login) {
|
|
1897
|
-
* // 로그인 폼 표시
|
|
1898
|
-
* } else if (settings.enabled_oauth_providers.includes('GOOGLE')) {
|
|
1899
|
-
* // 구글 소셜 로그인 버튼 표시
|
|
1900
|
-
* }
|
|
1901
|
-
* ```
|
|
1882
|
+
* 시간순(오래된 → 최신) 복사본 반환. 호출자가 mutate 해도 내부에 영향 없음.
|
|
1902
1883
|
*/
|
|
1903
|
-
|
|
1904
|
-
return this.
|
|
1905
|
-
skipAuth: true
|
|
1906
|
-
});
|
|
1884
|
+
snapshot() {
|
|
1885
|
+
return this.buf.slice();
|
|
1907
1886
|
}
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
* 앱에 새로운 멤버를 등록합니다.
|
|
1911
|
-
*
|
|
1912
|
-
* `login_id` 와 `email` 중 **최소 하나**는 있어야 합니다. 어느 쪽을 주느냐에 따라
|
|
1913
|
-
* 만들어지는 로그인 수단이 달라집니다 — 표는 {@link MemberSignUpRequest} 참고.
|
|
1914
|
-
*
|
|
1915
|
-
* `email` 을 함께 저장해야 나중에 {@link AuthAPI.requestPasswordReset} 로 비밀번호를
|
|
1916
|
-
* 복구할 수 있습니다. `login_id` 만으로 가입한 멤버는 복구 수단이 없습니다.
|
|
1917
|
-
*
|
|
1918
|
-
* 이메일을 넘겨도 **인증 메일이 자동 발송되지는 않습니다.** 발신 주소가 플랫폼 단일
|
|
1919
|
-
* 주소라 앱이 요청하지 않은 메일을 보내지 않는다는 정책입니다 — 필요하면 가입 직후
|
|
1920
|
-
* {@link AuthAPI.sendEmailVerification} 을 직접 호출하세요.
|
|
1921
|
-
*
|
|
1922
|
-
* @example
|
|
1923
|
-
* ```typescript
|
|
1924
|
-
* // 기존 방식 — 아이디만 (동작 그대로, 단 비밀번호 복구 불가)
|
|
1925
|
-
* const result = await client.auth.signUpMember({
|
|
1926
|
-
* login_id: 'myuser123',
|
|
1927
|
-
* password: 'password123',
|
|
1928
|
-
* nickname: 'John'
|
|
1929
|
-
* })
|
|
1930
|
-
*
|
|
1931
|
-
* // 아이디 + 복구용 이메일 (로그인은 여전히 login_id 로)
|
|
1932
|
-
* await client.auth.signUpMember({
|
|
1933
|
-
* login_id: 'myuser123',
|
|
1934
|
-
* email: 'john@example.com',
|
|
1935
|
-
* password: 'password123'
|
|
1936
|
-
* })
|
|
1937
|
-
*
|
|
1938
|
-
* // 이메일만 — 이메일이 곧 로그인 아이디
|
|
1939
|
-
* await client.auth.signUpMember({
|
|
1940
|
-
* email: 'john@example.com',
|
|
1941
|
-
* password: 'password123'
|
|
1942
|
-
* })
|
|
1943
|
-
* ```
|
|
1944
|
-
*/
|
|
1945
|
-
async signUpMember(data) {
|
|
1946
|
-
if (!data.login_id && !data.email) {
|
|
1947
|
-
throw new Error(
|
|
1948
|
-
"signUpMember requires at least one of login_id or email."
|
|
1949
|
-
);
|
|
1950
|
-
}
|
|
1951
|
-
const response = await this.http.post(
|
|
1952
|
-
"/v1/public/app-members/signup",
|
|
1953
|
-
data,
|
|
1954
|
-
{ skipAuth: true }
|
|
1955
|
-
);
|
|
1956
|
-
assertShape(
|
|
1957
|
-
response,
|
|
1958
|
-
{
|
|
1959
|
-
access_token: { type: "string" },
|
|
1960
|
-
refresh_token: { type: "string" },
|
|
1961
|
-
member_id: { type: "string-or-number" }
|
|
1962
|
-
},
|
|
1963
|
-
"auth.signUpMember"
|
|
1964
|
-
);
|
|
1965
|
-
this.http.setTokens(response.access_token, response.refresh_token);
|
|
1966
|
-
this.notifyVisitorTracker(response.member_id);
|
|
1967
|
-
return response;
|
|
1887
|
+
clear() {
|
|
1888
|
+
this.buf = [];
|
|
1968
1889
|
}
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
* @example
|
|
1978
|
-
* ```typescript
|
|
1979
|
-
* // 아이디로 로그인 (기존 방식)
|
|
1980
|
-
* const result = await client.auth.signInMember({
|
|
1981
|
-
* login_id: 'myuser123',
|
|
1982
|
-
* password: 'password123'
|
|
1983
|
-
* })
|
|
1984
|
-
*
|
|
1985
|
-
* // 이메일로 로그인
|
|
1986
|
-
* await client.auth.signInMember({
|
|
1987
|
-
* email: 'john@example.com',
|
|
1988
|
-
* password: 'password123'
|
|
1989
|
-
* })
|
|
1990
|
-
* ```
|
|
1991
|
-
*/
|
|
1992
|
-
async signInMember(data) {
|
|
1993
|
-
if (!data.login_id && !data.email) {
|
|
1994
|
-
throw new Error(
|
|
1995
|
-
"signInMember requires at least one of login_id or email."
|
|
1996
|
-
);
|
|
1997
|
-
}
|
|
1998
|
-
const response = await this.http.post(
|
|
1999
|
-
"/v1/public/app-members/signin",
|
|
2000
|
-
data,
|
|
2001
|
-
{ skipAuth: true }
|
|
2002
|
-
);
|
|
2003
|
-
assertShape(
|
|
2004
|
-
response,
|
|
2005
|
-
{
|
|
2006
|
-
access_token: { type: "string" },
|
|
2007
|
-
refresh_token: { type: "string" },
|
|
2008
|
-
member_id: { type: "string-or-number" }
|
|
2009
|
-
},
|
|
2010
|
-
"auth.signInMember"
|
|
2011
|
-
);
|
|
2012
|
-
this.http.setTokens(response.access_token, response.refresh_token);
|
|
2013
|
-
this.notifyVisitorTracker(response.member_id);
|
|
2014
|
-
return response;
|
|
2015
|
-
}
|
|
2016
|
-
// ── 자격증명 복구/변경 ────────────────────────────────────────────────────
|
|
2017
|
-
//
|
|
2018
|
-
// # 메일 링크는 "앱이 운영하는 페이지"를 거친다
|
|
2019
|
-
//
|
|
2020
|
-
// 재설정/인증 메일의 링크는 이 API 를 직접 열지 않습니다. 브라우저 주소창으로는
|
|
2021
|
-
// `X-Public-Key` 헤더를 붙일 수 없기 때문입니다. 링크는 앱의 페이지(= SDK 가 이미
|
|
2022
|
-
// 초기화돼 있는 곳)로 가고, 그 페이지가 쿼리에서 `token` 을 꺼내 아래 confirm 메서드를
|
|
2023
|
-
// 호출하는 구조입니다.
|
|
2024
|
-
//
|
|
2025
|
-
// 그래서 `redirect_url` 로 넘길 주소는 **앱에 등록된 도메인이어야 합니다**
|
|
2026
|
-
// (자세한 규칙은 {@link MemberRedirectOption}). 도메인을 등록하지 않으면 링크가
|
|
2027
|
-
// 플랫폼 기본 페이지로 폴백합니다.
|
|
2028
|
-
/**
|
|
2029
|
-
* 비밀번호 재설정 메일을 보냅니다. (로그인 불필요)
|
|
2030
|
-
*
|
|
2031
|
-
* # 계정 열거 방지 — 응답으로는 아무것도 알 수 없다
|
|
2032
|
-
*
|
|
2033
|
-
* 가입되지 않은 이메일이든, 소셜 전용 계정(비밀번호 없음)이든, 정지된 멤버든
|
|
2034
|
-
* **똑같은 200 과 똑같은 문구**가 돌아옵니다. 메일이 실제로 나갔는지 여부는 응답으로
|
|
2035
|
-
* 판별할 수 없습니다 — "가입 여부 확인" 용도로 쓸 수 없다는 뜻이며, 의도된 설계입니다.
|
|
2036
|
-
* UI 에서도 "가입된 계정이라면 메일을 보냈습니다" 처럼 안내하세요.
|
|
2037
|
-
*
|
|
2038
|
-
* 메일 링크의 토큰은 **1시간** 만료이고 **1회만** 쓸 수 있습니다.
|
|
2039
|
-
*
|
|
2040
|
-
* @example
|
|
2041
|
-
* ```typescript
|
|
2042
|
-
* // 앱이 자체 재설정 페이지를 운영하는 경우 (도메인 등록 선행 필수)
|
|
2043
|
-
* await client.auth.requestPasswordReset({
|
|
2044
|
-
* email: 'john@example.com',
|
|
2045
|
-
* redirect_url: 'https://myapp.com/reset-password'
|
|
2046
|
-
* })
|
|
2047
|
-
* toast('가입된 계정이라면 재설정 링크를 보냈습니다')
|
|
2048
|
-
* ```
|
|
2049
|
-
*/
|
|
2050
|
-
async requestPasswordReset(data) {
|
|
2051
|
-
return this.http.post(
|
|
2052
|
-
"/v1/public/app-members/password-reset/request",
|
|
2053
|
-
data,
|
|
2054
|
-
{ skipAuth: true }
|
|
2055
|
-
);
|
|
2056
|
-
}
|
|
2057
|
-
/**
|
|
2058
|
-
* 재설정 토큰으로 새 비밀번호를 확정합니다. (로그인 불필요)
|
|
2059
|
-
*
|
|
2060
|
-
* `redirect_url` 페이지의 `?token=` 쿼리 값을 그대로 넘기면 됩니다.
|
|
2061
|
-
*
|
|
2062
|
-
* 성공하면 **그 멤버의 모든 세션이 서버에서 폐기**됩니다. 다른 기기 로그인까지 전부
|
|
2063
|
-
* 끊기며, 이 SDK 인스턴스에 남아 있던 토큰도 함께 정리하므로 새 비밀번호로 다시
|
|
2064
|
-
* 로그인해야 합니다.
|
|
2065
|
-
*
|
|
2066
|
-
* 토큰이 만료(1시간)됐거나 이미 사용됐거나 위조/타앱 토큰이면 400 이 납니다. 사유는
|
|
2067
|
-
* 구분되지 않습니다 — 토큰을 탐색하는 단서를 주지 않기 위해서입니다.
|
|
2068
|
-
*
|
|
2069
|
-
* @example
|
|
2070
|
-
* ```typescript
|
|
2071
|
-
* const token = new URLSearchParams(location.search).get('token')
|
|
2072
|
-
* if (!token) return
|
|
2073
|
-
* try {
|
|
2074
|
-
* await client.auth.confirmPasswordReset({ token, new_password: 'newpass123' })
|
|
2075
|
-
* location.href = '/login'
|
|
2076
|
-
* } catch (e) {
|
|
2077
|
-
* // 만료, 이미 사용됨, 잘못된 링크가 모두 여기로 온다
|
|
2078
|
-
* alert('링크가 만료되었거나 이미 사용되었습니다. 재설정을 다시 요청해 주세요.')
|
|
2079
|
-
* }
|
|
2080
|
-
* ```
|
|
2081
|
-
*/
|
|
2082
|
-
async confirmPasswordReset(data) {
|
|
2083
|
-
const response = await this.http.post(
|
|
2084
|
-
"/v1/public/app-members/password-reset/confirm",
|
|
2085
|
-
data,
|
|
2086
|
-
{ skipAuth: true }
|
|
2087
|
-
);
|
|
2088
|
-
this.http.clearTokens();
|
|
2089
|
-
this.notifyVisitorTracker(null);
|
|
2090
|
-
return response;
|
|
1890
|
+
};
|
|
1891
|
+
function sanitizePathForBreadcrumb(rawUrl) {
|
|
1892
|
+
try {
|
|
1893
|
+
const u = rawUrl.startsWith("http") ? new URL(rawUrl) : new URL(rawUrl, "http://x");
|
|
1894
|
+
return u.pathname || rawUrl;
|
|
1895
|
+
} catch {
|
|
1896
|
+
const idx = rawUrl.indexOf("?");
|
|
1897
|
+
return idx >= 0 ? rawUrl.slice(0, idx) : rawUrl;
|
|
2091
1898
|
}
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
*/
|
|
2108
|
-
async changePassword(data) {
|
|
2109
|
-
const response = await this.http.post(
|
|
2110
|
-
"/v1/public/app-members/me/password",
|
|
2111
|
-
data
|
|
2112
|
-
);
|
|
2113
|
-
this.http.clearTokens();
|
|
2114
|
-
this.notifyVisitorTracker(null);
|
|
2115
|
-
return response;
|
|
1899
|
+
}
|
|
1900
|
+
|
|
1901
|
+
// src/core/http.ts
|
|
1902
|
+
var COOKIE_BEARING_PUBLIC_PATHS = /* @__PURE__ */ new Set([
|
|
1903
|
+
"/v1/public/app-members/signup",
|
|
1904
|
+
"/v1/public/app-members/signin",
|
|
1905
|
+
"/v1/public/app-members/signout"
|
|
1906
|
+
]);
|
|
1907
|
+
function isAbortError(err) {
|
|
1908
|
+
return typeof err === "object" && err !== null && "name" in err && err.name === "AbortError";
|
|
1909
|
+
}
|
|
1910
|
+
function fetchCredentialsForPath(url) {
|
|
1911
|
+
const path = url.split("?")[0];
|
|
1912
|
+
if (COOKIE_BEARING_PUBLIC_PATHS.has(path)) {
|
|
1913
|
+
return "include";
|
|
2116
1914
|
}
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
|
|
2124
|
-
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
|
|
2130
|
-
|
|
2131
|
-
* redirect_url: 'https://myapp.com/verify-email'
|
|
2132
|
-
* })
|
|
2133
|
-
*
|
|
2134
|
-
* // redirect_url 없이 — 플랫폼 기본 페이지 링크로 발송된다
|
|
2135
|
-
* await client.auth.sendEmailVerification()
|
|
2136
|
-
* ```
|
|
2137
|
-
*/
|
|
2138
|
-
async sendEmailVerification(data) {
|
|
2139
|
-
return this.http.post(
|
|
2140
|
-
"/v1/public/app-members/me/email-verification/request",
|
|
2141
|
-
data ?? {}
|
|
2142
|
-
);
|
|
1915
|
+
return path.startsWith("/v1/public/") || path.startsWith("/v1/proxy/") ? "omit" : "include";
|
|
1916
|
+
}
|
|
1917
|
+
var TOKEN_STORAGE_KEY = "cb_auth_tokens";
|
|
1918
|
+
var NO_COOKIE_SESSION_COOLDOWN_MS = 6e4;
|
|
1919
|
+
function gatewayCodeFromStatus(status) {
|
|
1920
|
+
switch (status) {
|
|
1921
|
+
case 502:
|
|
1922
|
+
return "bad_gateway";
|
|
1923
|
+
case 503:
|
|
1924
|
+
return "service_unavailable";
|
|
1925
|
+
case 504:
|
|
1926
|
+
return "gateway_timeout";
|
|
1927
|
+
default:
|
|
1928
|
+
return void 0;
|
|
2143
1929
|
}
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
|
|
2154
|
-
|
|
2155
|
-
* if (!token) return
|
|
2156
|
-
* try {
|
|
2157
|
-
* const r = await client.auth.confirmEmailVerification({ token })
|
|
2158
|
-
* console.log(r.email, r.is_email_verified) // true
|
|
2159
|
-
* } catch {
|
|
2160
|
-
* alert('인증 링크가 만료되었거나 이미 사용되었습니다.')
|
|
2161
|
-
* }
|
|
2162
|
-
* ```
|
|
2163
|
-
*/
|
|
2164
|
-
async confirmEmailVerification(data) {
|
|
2165
|
-
const response = await this.http.post(
|
|
2166
|
-
"/v1/public/app-members/email-verification/confirm",
|
|
2167
|
-
data,
|
|
2168
|
-
{ skipAuth: true }
|
|
2169
|
-
);
|
|
2170
|
-
assertShape(
|
|
2171
|
-
response,
|
|
2172
|
-
{
|
|
2173
|
-
member_id: { type: "string-or-number" }
|
|
2174
|
-
},
|
|
2175
|
-
"auth.confirmEmailVerification"
|
|
2176
|
-
);
|
|
2177
|
-
return response;
|
|
1930
|
+
}
|
|
1931
|
+
function gatewayMessageFromStatus(status) {
|
|
1932
|
+
switch (status) {
|
|
1933
|
+
case 502:
|
|
1934
|
+
return "\uAC8C\uC774\uD2B8\uC6E8\uC774\uAC00 \uC11C\uBC84\uB85C\uBD80\uD130 \uC62C\uBC14\uB978 \uC751\uB2F5\uC744 \uBC1B\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4 (502)";
|
|
1935
|
+
case 503:
|
|
1936
|
+
return "\uC11C\uBC84\uAC00 \uC77C\uC2DC\uC801\uC73C\uB85C \uC694\uCCAD\uC744 \uCC98\uB9AC\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4 (503)";
|
|
1937
|
+
case 504:
|
|
1938
|
+
return "\uAC8C\uC774\uD2B8\uC6E8\uC774\uAC00 \uC751\uB2F5\uC744 \uAE30\uB2E4\uB9AC\uB2E4 \uC5F0\uACB0\uC744 \uB04A\uC5C8\uC2B5\uB2C8\uB2E4 (504). \uC624\uB798 \uAC78\uB9AC\uB294 \uC791\uC5C5\uC774\uBA74 \uC694\uCCAD \uD0C0\uC784\uC544\uC6C3\uC744 \uB298\uB9AC\uAC70\uB098 \uC2A4\uD2B8\uB9AC\uBC0D\uC744 \uC0AC\uC6A9\uD558\uC138\uC694";
|
|
1939
|
+
default:
|
|
1940
|
+
return void 0;
|
|
2178
1941
|
}
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
|
-
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
|
|
2186
|
-
|
|
2187
|
-
|
|
2188
|
-
|
|
2189
|
-
|
|
2190
|
-
if (this.http.knowsNoSession()) {
|
|
2191
|
-
throw await this.http.rejectNoSession();
|
|
2192
|
-
}
|
|
2193
|
-
const response = await this.http.get(
|
|
2194
|
-
"/v1/public/app-members/me"
|
|
2195
|
-
);
|
|
2196
|
-
assertShape(
|
|
2197
|
-
response,
|
|
2198
|
-
{
|
|
2199
|
-
member_id: { type: "string-or-number" }
|
|
2200
|
-
},
|
|
2201
|
-
"auth.getMe"
|
|
2202
|
-
);
|
|
2203
|
-
return response;
|
|
1942
|
+
}
|
|
1943
|
+
function decodeJwtPayload(token) {
|
|
1944
|
+
try {
|
|
1945
|
+
const part = token.split(".")[1];
|
|
1946
|
+
if (!part) return null;
|
|
1947
|
+
const base64 = part.replace(/-/g, "+").replace(/_/g, "/");
|
|
1948
|
+
const padded = base64 + "=".repeat((4 - base64.length % 4) % 4);
|
|
1949
|
+
const parsed = JSON.parse(atob(padded));
|
|
1950
|
+
return parsed && typeof parsed === "object" ? parsed : null;
|
|
1951
|
+
} catch {
|
|
1952
|
+
return null;
|
|
2204
1953
|
}
|
|
2205
|
-
|
|
2206
|
-
|
|
2207
|
-
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
|
|
2211
|
-
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
* // 키 삭제 (null 전달)
|
|
2217
|
-
* await client.auth.updateCustomData({
|
|
2218
|
-
* custom_data: { role: null }
|
|
2219
|
-
* })
|
|
2220
|
-
* ```
|
|
2221
|
-
*/
|
|
2222
|
-
async updateCustomData(data) {
|
|
2223
|
-
return this.http.patch(
|
|
2224
|
-
"/v1/public/app-members/me/custom-data",
|
|
2225
|
-
data
|
|
2226
|
-
);
|
|
1954
|
+
}
|
|
1955
|
+
function tokenExpiresWithin(token, sec) {
|
|
1956
|
+
const payload = decodeJwtPayload(token);
|
|
1957
|
+
if (!payload || typeof payload.exp !== "number") return true;
|
|
1958
|
+
return payload.exp < Date.now() / 1e3 + sec;
|
|
1959
|
+
}
|
|
1960
|
+
function isSameMemberToken(a, b) {
|
|
1961
|
+
const pa = decodeJwtPayload(a);
|
|
1962
|
+
const pb = decodeJwtPayload(b);
|
|
1963
|
+
if (!pa || !pb || pa.role !== "AppMember" || pb.role !== "AppMember") {
|
|
1964
|
+
return false;
|
|
2227
1965
|
}
|
|
2228
|
-
|
|
2229
|
-
|
|
2230
|
-
|
|
2231
|
-
|
|
2232
|
-
|
|
2233
|
-
|
|
2234
|
-
|
|
2235
|
-
|
|
2236
|
-
|
|
2237
|
-
|
|
2238
|
-
|
|
2239
|
-
|
|
2240
|
-
|
|
2241
|
-
|
|
2242
|
-
|
|
2243
|
-
|
|
2244
|
-
|
|
2245
|
-
|
|
2246
|
-
|
|
2247
|
-
|
|
2248
|
-
|
|
2249
|
-
|
|
2250
|
-
|
|
2251
|
-
|
|
2252
|
-
|
|
2253
|
-
|
|
2254
|
-
|
|
2255
|
-
* // 역할 여러 개 (6.7.0+): role 은 주 역할(RLS auth.role), roles 는 추가 역할 목록을 **통째로 바꾼다**
|
|
2256
|
-
* // ([] 면 비우고, 빼면 그대로). auth.roles, hasRole(), 실시간 publisher_roles 는 role + roles 를 함께 본다.
|
|
2257
|
-
* await cb.auth.adminUpdateMember('member-uuid', { roles: ['performer'] })
|
|
2258
|
-
* // → { role: 'admin', roles: ['performer'], effective_roles: ['admin', 'performer'], ... }
|
|
2259
|
-
* ```
|
|
2260
|
-
*/
|
|
2261
|
-
async adminUpdateMember(memberID, fields) {
|
|
2262
|
-
if (!this.http.getSecretKey()) {
|
|
2263
|
-
throw new Error(
|
|
2264
|
-
"adminUpdateMember requires a secretKey. Initialize ConnectBase with both publicKey and secretKey."
|
|
2265
|
-
);
|
|
1966
|
+
const member = pa.app_member_id;
|
|
1967
|
+
return typeof member === "string" && member !== "" && member === pb.app_member_id && pa.app_id === pb.app_id;
|
|
1968
|
+
}
|
|
1969
|
+
function isConsolePlatformToken(token) {
|
|
1970
|
+
const role = decodeJwtPayload(token)?.role;
|
|
1971
|
+
return role === "User" || role === "AdminInvite";
|
|
1972
|
+
}
|
|
1973
|
+
var EDGE_HINTS_TTL_MS = 10 * 6e4;
|
|
1974
|
+
var sharedEdgeHints = /* @__PURE__ */ new Map();
|
|
1975
|
+
function lookupEdgeHints(baseUrl, timeoutMs) {
|
|
1976
|
+
const cached = sharedEdgeHints.get(baseUrl);
|
|
1977
|
+
if (cached && Date.now() < cached.expiresAt) return cached.promise;
|
|
1978
|
+
const entry = {
|
|
1979
|
+
promise: fetchEdgeHintAdverts(baseUrl, timeoutMs),
|
|
1980
|
+
// 진행 중에는 만료되지 않는다 — 시간 제한(withAbort) 때문에 timeoutMs 안에 반드시 끝난다. 늦게 합류한
|
|
1981
|
+
// 인스턴스는 남은 시간만 기다린다.
|
|
1982
|
+
expiresAt: Number.POSITIVE_INFINITY
|
|
1983
|
+
};
|
|
1984
|
+
sharedEdgeHints.set(baseUrl, entry);
|
|
1985
|
+
entry.promise.then(
|
|
1986
|
+
() => {
|
|
1987
|
+
entry.expiresAt = Date.now() + EDGE_HINTS_TTL_MS;
|
|
1988
|
+
},
|
|
1989
|
+
() => {
|
|
1990
|
+
if (sharedEdgeHints.get(baseUrl) === entry) {
|
|
1991
|
+
sharedEdgeHints.delete(baseUrl);
|
|
1992
|
+
}
|
|
2266
1993
|
}
|
|
2267
|
-
|
|
2268
|
-
|
|
2269
|
-
|
|
1994
|
+
);
|
|
1995
|
+
return entry.promise;
|
|
1996
|
+
}
|
|
1997
|
+
async function fetchEdgeHintAdverts(baseUrl, timeoutMs) {
|
|
1998
|
+
const { signal, cleanup } = createTimeoutController({ timeout: timeoutMs });
|
|
1999
|
+
try {
|
|
2000
|
+
const response = await withAbort(
|
|
2001
|
+
fetch(`${baseUrl}/v1/public/edge-hints`, {
|
|
2002
|
+
method: "GET",
|
|
2003
|
+
credentials: "omit",
|
|
2004
|
+
signal
|
|
2005
|
+
}),
|
|
2006
|
+
signal
|
|
2270
2007
|
);
|
|
2271
|
-
|
|
2272
|
-
|
|
2273
|
-
* Admin: 다른 멤버를 삭제(탈퇴 처리)합니다. **되돌릴 수 없습니다.**
|
|
2274
|
-
*
|
|
2275
|
-
* `adminUpdateMember` 와 같은 권한 컨텍스트입니다 — `cb_pk_` 로 앱을 식별하고 함께 보낸
|
|
2276
|
-
* `cb_sk_` 의 사용자가 그 앱에 `app_member:write` 권한을 가져야 합니다. 브라우저 번들에
|
|
2277
|
-
* 시크릿 키를 넣지 마세요. 서버(함수·백엔드)에서만 호출합니다.
|
|
2278
|
-
*
|
|
2279
|
-
* 멤버 행과 함께 **로그인 수단(identities)** 이 지워집니다. 따라서 같은 소셜 계정으로 다시
|
|
2280
|
-
* 로그인하면 기존 member_id 로 되살아나지 않고 **새 member_id** 를 받습니다. 결제·구독·
|
|
2281
|
-
* 푸시 디바이스·방문 기록 등 멤버에 매달린 행도 함께 사라집니다.
|
|
2282
|
-
*
|
|
2283
|
-
* 앱이 자체 테이블(`cb.database`)에 보관한 데이터는 지우지 않습니다 — 그건 `service_role`
|
|
2284
|
-
* 로 앱이 직접 정리하세요.
|
|
2285
|
-
*
|
|
2286
|
-
* 이미 발급된 그 멤버의 access token 은 만료(최대 1시간)까지 서명이 유효합니다. 즉시
|
|
2287
|
-
* 차단이 필요하면 삭제 전에 정지(콘솔 `멤버 정지`)를 함께 쓰세요.
|
|
2288
|
-
*
|
|
2289
|
-
* @example
|
|
2290
|
-
* ```typescript
|
|
2291
|
-
* const cb = new ConnectBase({ publicKey: 'cb_pk_...', secretKey: 'cb_sk_...' })
|
|
2292
|
-
* await cb.auth.adminDeleteMember('member-uuid')
|
|
2293
|
-
* ```
|
|
2294
|
-
*/
|
|
2295
|
-
async adminDeleteMember(memberID) {
|
|
2296
|
-
if (!this.http.getSecretKey()) {
|
|
2297
|
-
throw new Error(
|
|
2298
|
-
"adminDeleteMember requires a secretKey. Initialize ConnectBase with both publicKey and secretKey."
|
|
2299
|
-
);
|
|
2008
|
+
if (!response.ok) {
|
|
2009
|
+
throw new Error(`edge-hints HTTP ${response.status}`);
|
|
2300
2010
|
}
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
|
|
2304
|
-
|
|
2305
|
-
|
|
2306
|
-
* 로그인한 본인이 스스로 탈퇴합니다. **되돌릴 수 없습니다.**
|
|
2307
|
-
*
|
|
2308
|
-
* App Store 심사 가이드라인 5.1.1(v)는 "앱 안에서 가입이 되면 앱 안에서 탈퇴도 가능해야
|
|
2309
|
-
* 한다"를 요구합니다 — 고객센터 안내로는 통과되지 않습니다. 이 메서드가 그 요구를 만족하는
|
|
2310
|
-
* 경로입니다.
|
|
2311
|
-
*
|
|
2312
|
-
* 확인 UI(“정말 탈퇴하시겠습니까?”)는 앱이 책임집니다. 서버는 확인 없이 즉시 삭제합니다.
|
|
2313
|
-
*
|
|
2314
|
-
* 성공하면 로컬 토큰이 정리되고 refresh 쿠키도 서버가 만료시킵니다 — `signOut()` 을 따로
|
|
2315
|
-
* 부를 필요가 없습니다.
|
|
2316
|
-
*
|
|
2317
|
-
* `adminDeleteMember` 와 동일하게 로그인 수단(identities)까지 지우므로, 같은 소셜 계정으로
|
|
2318
|
-
* 재가입하면 새 member_id 를 받습니다.
|
|
2319
|
-
*
|
|
2320
|
-
* @example
|
|
2321
|
-
* ```typescript
|
|
2322
|
-
* // 설정 > 회원 탈퇴 버튼
|
|
2323
|
-
* if (confirm('탈퇴하면 되돌릴 수 없습니다. 계속할까요?')) {
|
|
2324
|
-
* await cb.auth.deleteMyAccount()
|
|
2325
|
-
* location.href = '/'
|
|
2326
|
-
* }
|
|
2327
|
-
* ```
|
|
2328
|
-
*/
|
|
2329
|
-
async deleteMyAccount() {
|
|
2011
|
+
const header = {
|
|
2012
|
+
direct: response.headers?.get("X-CB-Direct-Base") || null,
|
|
2013
|
+
realtime: response.headers?.get("X-CB-Realtime-Direct-Base") || null
|
|
2014
|
+
};
|
|
2015
|
+
let body;
|
|
2330
2016
|
try {
|
|
2331
|
-
|
|
2332
|
-
|
|
2333
|
-
);
|
|
2334
|
-
|
|
2335
|
-
this.http.clearTokens();
|
|
2336
|
-
this.notifyVisitorTracker(null);
|
|
2017
|
+
body = await withAbort(response.json(), signal);
|
|
2018
|
+
} catch (err) {
|
|
2019
|
+
if (header.direct || header.realtime) return [header];
|
|
2020
|
+
throw err;
|
|
2337
2021
|
}
|
|
2022
|
+
return [
|
|
2023
|
+
header,
|
|
2024
|
+
{ direct: body?.direct_base, realtime: body?.realtime_direct_base }
|
|
2025
|
+
];
|
|
2026
|
+
} finally {
|
|
2027
|
+
cleanup();
|
|
2338
2028
|
}
|
|
2339
|
-
|
|
2340
|
-
|
|
2341
|
-
|
|
2342
|
-
|
|
2343
|
-
|
|
2344
|
-
|
|
2345
|
-
|
|
2346
|
-
|
|
2347
|
-
|
|
2348
|
-
|
|
2029
|
+
}
|
|
2030
|
+
var HttpClient = class {
|
|
2031
|
+
constructor(config) {
|
|
2032
|
+
this.isRefreshing = false;
|
|
2033
|
+
this.refreshPromise = null;
|
|
2034
|
+
// 연속 refresh 실패 시 지수 백오프 — 같은 세션이 스피너 UI 로 묶였을 때
|
|
2035
|
+
// 밀리초 단위로 서버에 재시도 요청이 쏟아지는 것을 차단.
|
|
2036
|
+
this.refreshFailureCount = 0;
|
|
2037
|
+
this.refreshLockedUntil = 0;
|
|
2038
|
+
/**
|
|
2039
|
+
* 최근 API 호출 breadcrumb (PII strip 후 저장). platform_issue 발행 시 자동 첨부 가능.
|
|
2040
|
+
* `client.support.getRecentApiCalls()` 로 외부 노출.
|
|
2041
|
+
*/
|
|
2042
|
+
this.recentCalls = new RecentCallsBuffer();
|
|
2043
|
+
/**
|
|
2044
|
+
* 부팅 시 fire-and-forget 으로 시작한 cookie 기반 복구 promise. `prepareHeaders` 가
|
|
2045
|
+
* 인증 호출을 보내기 직전에 이 promise 를 await 해, 페이지 진입 직후 첫 API 호출이
|
|
2046
|
+
* 메모리 토큰 빈 상태로 401 받는 race 를 막는다 (platform-issue 019e638d, 2026-05-26).
|
|
2047
|
+
* 한 번 settle 되면 그 결과(메모리 적재 또는 미로그인)가 항상 반영되어 있다.
|
|
2048
|
+
*/
|
|
2049
|
+
this.bootRestorePromise = null;
|
|
2050
|
+
// OAuth 콜백 부트스트랩처럼 세션 힌트 유무와 무관하게 첫 인증 호출이 반드시 기다려야
|
|
2051
|
+
// 하는 boot promise 인지 여부 (setBootRestorePromise 의 alwaysAwait 옵션).
|
|
2052
|
+
this.bootRestoreAlwaysAwait = false;
|
|
2053
|
+
/**
|
|
2054
|
+
* 서버가 `X-CB-Direct-Base` 로 알려준 저지연 원본. 학습 전에는 null 이라 항상 `baseUrl`
|
|
2055
|
+
* 을 쓴다. {@link resolveOrigin} 참고.
|
|
2056
|
+
*/
|
|
2057
|
+
this.directBaseUrl = null;
|
|
2058
|
+
/**
|
|
2059
|
+
* direct 원본을 이 세션에서 더는 쓰지 않는다는 표시. 한 번이라도 네트워크 레벨에서
|
|
2060
|
+
* 실패하면(CSP `connect-src` 차단, 사내 프록시, DNS 미전파, 호스트 회수 등) 즉시 세워
|
|
2061
|
+
* 이후 요청은 전부 `baseUrl` 로 간다. direct 는 최적화일 뿐 필수가 아니므로 재시도를
|
|
2062
|
+
* 반복하지 않고 한 번에 포기하는 쪽이 안전하다.
|
|
2063
|
+
*/
|
|
2064
|
+
this.directDisabled = false;
|
|
2065
|
+
/**
|
|
2066
|
+
* 서버가 `X-CB-Realtime-Direct-Base` 로 알려준 socket-server 저지연 원본(`wss://...`).
|
|
2067
|
+
* HTTP direct(`directBaseUrl`)와 별도 값·별도 킬 스위치 — core-server 응답에서만 학습되고
|
|
2068
|
+
* (WS 업그레이드 응답 헤더는 브라우저가 못 읽는다), `RealtimeAPI.doConnect()` 가 매 연결
|
|
2069
|
+
* 시도마다 lazy 하게 조회한다. platform-issue 019fe448.
|
|
2070
|
+
*/
|
|
2071
|
+
this.directRealtimeBaseUrl = null;
|
|
2072
|
+
/**
|
|
2073
|
+
* realtime WS 연결이 direct 원본에서 네트워크 레벨로 실패하면 세운다 — `directDisabled`
|
|
2074
|
+
* 와 같은 철학("한 번 실패하면 이 세션에서는 포기하고 원래 호스트로")이지만, 실패 감지가
|
|
2075
|
+
* WS 상태 머신(RealtimeAPI) 쪽에서 일어나므로 별도 플래그로 둔다.
|
|
2076
|
+
*/
|
|
2077
|
+
this.directRealtimeDisabled = false;
|
|
2078
|
+
this.config = { ...config };
|
|
2079
|
+
this.storageKey = this.buildStorageKey();
|
|
2080
|
+
this.warnIfUnsafePersistence();
|
|
2081
|
+
this.warnIfSecretKeyInBrowser();
|
|
2082
|
+
this.restoreTokens();
|
|
2349
2083
|
}
|
|
2350
|
-
// ── 활성 세션(로그인된 기기) 관리 ────────────────────────────────────────
|
|
2351
|
-
//
|
|
2352
|
-
// 대상은 언제나 **로그인한 본인**이다. 세 메서드 모두 사용자 식별자를 받지 않는다 —
|
|
2353
|
-
// 누구의 세션인지는 서버가 검증된 토큰에서 정하고, 요청은 정할 수 없다.
|
|
2354
|
-
//
|
|
2355
|
-
// 폐기는 되돌릴 수 없다. 다만 이미 발급된 액세스 토큰은 만료(최대 1시간)까지 유효하므로,
|
|
2356
|
-
// 끊긴 기기가 곧바로 모든 호출에 실패하지는 않는다. 즉시 차단이 필요하면 앱이 서버
|
|
2357
|
-
// 측에서 회원을 정지시켜야 한다.
|
|
2358
2084
|
/**
|
|
2359
|
-
*
|
|
2360
|
-
*
|
|
2361
|
-
* 현재 세션이 맨 앞에 오고, 나머지는 최근 사용 순입니다. 응답에는 토큰도 평문 IP 도
|
|
2362
|
-
* 담기지 않습니다.
|
|
2363
|
-
*
|
|
2364
|
-
* **`current` 를 화면에 반드시 표시하세요.** 구분이 없으면 사용자가 자기가 쓰고 있는
|
|
2365
|
-
* 기기를 끊고 영문도 모른 채 로그아웃됩니다. refresh 쿠키가 없는 환경에서는 서버가
|
|
2366
|
-
* 현재 세션을 특정하지 못해 `current` 가 어느 항목에도 붙지 않을 수 있습니다.
|
|
2085
|
+
* 클라이언트 생성 시 명시된 요청 타임아웃(ms). 미지정이면 `undefined`.
|
|
2367
2086
|
*
|
|
2368
|
-
*
|
|
2369
|
-
*
|
|
2370
|
-
*
|
|
2371
|
-
* for (const s of sessions) {
|
|
2372
|
-
* console.log(s.browser, s.os, s.location, s.current ? '(이 기기)' : '')
|
|
2373
|
-
* }
|
|
2374
|
-
* ```
|
|
2087
|
+
* API 모듈이 자기 엔드포인트에 맞는 기본 타임아웃을 고를 때, 사용자가 명시한 값이
|
|
2088
|
+
* 있으면 그쪽을 존중하기 위해 필요하다 (`ai.chat` 이 이 값을 읽는다). `config` 자체를
|
|
2089
|
+
* 노출하면 토큰/스토리지 설정까지 새므로 이 필드만 읽기 전용으로 연다.
|
|
2375
2090
|
*/
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
"/v1/public/app-members/me/sessions"
|
|
2379
|
-
);
|
|
2380
|
-
assertShape(
|
|
2381
|
-
response,
|
|
2382
|
-
{
|
|
2383
|
-
sessions: { type: "array" }
|
|
2384
|
-
},
|
|
2385
|
-
"auth.listSessions"
|
|
2386
|
-
);
|
|
2387
|
-
return response;
|
|
2091
|
+
get requestTimeoutMs() {
|
|
2092
|
+
return this.config.requestTimeoutMs;
|
|
2388
2093
|
}
|
|
2389
2094
|
/**
|
|
2390
|
-
*
|
|
2391
|
-
*
|
|
2392
|
-
*
|
|
2393
|
-
* 이미 끝난 세션도 같은 404 입니다.
|
|
2394
|
-
*
|
|
2395
|
-
* **현재 세션을 지목하면 그 자리에서 로그아웃됩니다.** 서버가 refresh 쿠키를 함께
|
|
2396
|
-
* 만료시키므로 로컬 토큰도 정리합니다 — 이 경우 앱은 로그인 화면으로 보내야 합니다.
|
|
2397
|
-
* 그렇지 않은 기기를 끊는 것은 현재 세션에 영향을 주지 않습니다.
|
|
2095
|
+
* 페이지 진입 시 fire-and-forget 으로 시작된 cookie 복구 promise 를 SDK 가 등록한다.
|
|
2096
|
+
* 같은 promise 가 `prepareHeaders` 에서 await 되어, 첫 인증 호출이 cookie 복구
|
|
2097
|
+
* 완료 후 발화한다.
|
|
2398
2098
|
*
|
|
2399
|
-
*
|
|
2400
|
-
*
|
|
2401
|
-
*
|
|
2402
|
-
|
|
2403
|
-
|
|
2099
|
+
* options.alwaysAwait=true 면 세션 힌트가 없어도 첫 인증 호출이 이 promise 를
|
|
2100
|
+
* 기다린다 — OAuth 리다이렉트 콜백처럼 "이 부트 promise 가 곧 세션을 만든다"는 것이
|
|
2101
|
+
* 확실한 흐름용 (일반 cookie 복구는 힌트 기반 fast-path 적용).
|
|
2102
|
+
*/
|
|
2103
|
+
setBootRestorePromise(p, options) {
|
|
2104
|
+
this.bootRestorePromise = p.catch(() => false);
|
|
2105
|
+
this.bootRestoreAlwaysAwait = options?.alwaysAwait === true;
|
|
2106
|
+
}
|
|
2107
|
+
/** 최근 호출 ring buffer 스냅샷 (시간순). */
|
|
2108
|
+
getRecentCalls() {
|
|
2109
|
+
return this.recentCalls.snapshot();
|
|
2110
|
+
}
|
|
2111
|
+
/** 최근 호출 buffer clear (테스트/프라이버시 처리). */
|
|
2112
|
+
clearRecentCalls() {
|
|
2113
|
+
this.recentCalls.clear();
|
|
2114
|
+
}
|
|
2115
|
+
/**
|
|
2116
|
+
* Secret Key 는 계정 권한의 자격증명이다. 브라우저 번들에 넣으면 페이지를 여는 누구나 읽는다.
|
|
2117
|
+
* 막지는 않는다(Electron 등 신뢰된 환경이 있다) — 대신 무엇이 위험한지 분명히 알린다.
|
|
2404
2118
|
*/
|
|
2405
|
-
|
|
2406
|
-
|
|
2407
|
-
|
|
2408
|
-
|
|
2119
|
+
warnIfSecretKeyInBrowser() {
|
|
2120
|
+
if (typeof window === "undefined" || typeof document === "undefined") {
|
|
2121
|
+
return;
|
|
2122
|
+
}
|
|
2123
|
+
const misplaced = this.config.publicKey?.startsWith("cb_sk_") === true;
|
|
2124
|
+
if (!this.config.secretKey && !misplaced) return;
|
|
2125
|
+
console.warn(
|
|
2126
|
+
"[connect-base-client] \uBE0C\uB77C\uC6B0\uC800\uC5D0\uC11C Secret Key(cb_sk_)\uB97C \uC4F0\uACE0 \uC788\uC2B5\uB2C8\uB2E4. \uD398\uC774\uC9C0\uB97C \uC5EC\uB294 \uB204\uAD6C\uB098 \uC774 \uD0A4\uB97C \uC77D\uC5B4 \uACC4\uC815 \uAD8C\uD55C\uC73C\uB85C API \uB97C \uD638\uCD9C\uD560 \uC218 \uC788\uC2B5\uB2C8\uB2E4. \uBE0C\uB77C\uC6B0\uC800\uC5D0\uB294 publicKey(cb_pk_)\uB9CC \uB123\uACE0 Secret Key \uB294 \uC11C\uBC84\uB098 CLI \uC5D0\uC11C\uB9CC \uC4F0\uC138\uC694. \uC774\uBBF8 \uBC30\uD3EC\uB410\uB2E4\uBA74 \uCF58\uC194\uC5D0\uC11C \uD0A4\uB97C \uD3D0\uAE30\uD558\uACE0 \uC0C8\uB85C \uBC1C\uAE09\uD558\uC138\uC694."
|
|
2409
2127
|
);
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
|
|
2128
|
+
}
|
|
2129
|
+
warnIfUnsafePersistence() {
|
|
2130
|
+
if (typeof window === "undefined") return;
|
|
2131
|
+
if (this.config.persistence === "localStorage") {
|
|
2132
|
+
console.warn(
|
|
2133
|
+
`[connect-base-client] persistence="localStorage" \uB294 XSS \uC2DC refresh token \uC601\uAD6C \uD0C8\uCDE8 \uC704\uD5D8\uC774 \uC788\uC2B5\uB2C8\uB2E4. \uAE30\uBCF8\uAC12('none') \uC744 \uC0AC\uC6A9\uD558\uBA74 \uC11C\uBC84\uAC00 \uBC1C\uAE09\uD55C HttpOnly cookie \uB85C\uB9CC refresh token \uC774 \uBCF4\uAD00\uB418\uC5B4 JS \uAC00 \uC811\uADFC\uD560 \uC218 \uC5C6\uACE0, \uC0C8\uB85C\uACE0\uCE68 \uD6C4\uC5D0\uB3C4 autoRestoreSession \uC73C\uB85C \uC790\uB3D9 \uBCF5\uAD6C\uB429\uB2C8\uB2E4.`
|
|
2134
|
+
);
|
|
2135
|
+
} else if (this.config.persistence === "sessionStorage") {
|
|
2136
|
+
console.warn(
|
|
2137
|
+
`[connect-base-client] persistence="sessionStorage" \uB294 XSS \uC2DC \uD0ED \uC138\uC158 \uD0C8\uCDE8 \uC704\uD5D8\uC774 \uC788\uC2B5\uB2C8\uB2E4. \uAE30\uBCF8\uAC12('none') + HttpOnly cookie \uD750\uB984\uC744 \uAD8C\uC7A5\uD569\uB2C8\uB2E4.`
|
|
2138
|
+
);
|
|
2413
2139
|
}
|
|
2414
|
-
|
|
2140
|
+
}
|
|
2141
|
+
updateConfig(config) {
|
|
2142
|
+
this.config = { ...this.config, ...config };
|
|
2143
|
+
}
|
|
2144
|
+
setTokens(accessToken, refreshToken) {
|
|
2145
|
+
this.config.accessToken = accessToken;
|
|
2146
|
+
this.config.refreshToken = refreshToken;
|
|
2147
|
+
this.persistTokens();
|
|
2148
|
+
this.markSessionHint();
|
|
2149
|
+
this.clearNoCookieSessionMark();
|
|
2150
|
+
}
|
|
2151
|
+
clearTokens() {
|
|
2152
|
+
this.config.accessToken = void 0;
|
|
2153
|
+
this.config.refreshToken = void 0;
|
|
2154
|
+
this.removePersistedTokens();
|
|
2155
|
+
this.clearSessionHint();
|
|
2415
2156
|
}
|
|
2416
2157
|
/**
|
|
2417
|
-
*
|
|
2418
|
-
*
|
|
2419
|
-
* 자기 세션까지 포함한 전체 로그아웃은 `signOut()` 입니다 — 자격증명 유출 대응처럼
|
|
2420
|
-
* 모든 기기를 내보내야 하는 상황에서는 그쪽을 쓰세요.
|
|
2421
|
-
*
|
|
2422
|
-
* refresh 쿠키가 없어 서버가 현재 세션을 특정하지 못하면 이 호출은 **실패합니다**
|
|
2423
|
-
* (400). 기준점 없이 진행하면 사용자가 의도하지 않은 자기 세션 종료가 함께 일어나기
|
|
2424
|
-
* 때문입니다. 그 경우 `signOut()` 후 재로그인을 안내하세요.
|
|
2158
|
+
* Access Token 만 교체한다 (refresh token 은 건드리지 않는다).
|
|
2425
2159
|
*
|
|
2426
|
-
*
|
|
2160
|
+
* 조직 컨텍스트 발급(`POST /v1/public/organizations/:orgID/context`)처럼 **새 액세스
|
|
2161
|
+
* 토큰만 돌려주는** 엔드포인트를 위한 것이다. 그 엔드포인트는 refresh token 을 회전시키지
|
|
2162
|
+
* 않으므로 `setTokens()` 로 빈 refresh token 을 덮어쓰면 세션 복구가 깨진다.
|
|
2427
2163
|
*
|
|
2428
|
-
*
|
|
2429
|
-
*
|
|
2430
|
-
* const { revoked } = await cb.auth.revokeOtherSessions()
|
|
2431
|
-
* toast(`${revoked}개 기기에서 로그아웃했습니다`)
|
|
2432
|
-
* ```
|
|
2164
|
+
* 세션이 새로 생기는 것이 아니므로 세션 힌트/쿠키 없음 마커는 건드리지 않는다 — 그 두
|
|
2165
|
+
* 마커는 로그인/재발급이 소유한다.
|
|
2433
2166
|
*/
|
|
2434
|
-
|
|
2435
|
-
|
|
2436
|
-
|
|
2437
|
-
);
|
|
2167
|
+
setAccessToken(accessToken) {
|
|
2168
|
+
this.config.accessToken = accessToken;
|
|
2169
|
+
this.persistTokens();
|
|
2438
2170
|
}
|
|
2439
|
-
|
|
2440
|
-
|
|
2441
|
-
|
|
2442
|
-
|
|
2443
|
-
|
|
2171
|
+
// ===== 세션 힌트 =====
|
|
2172
|
+
//
|
|
2173
|
+
// "이 origin 에서 이 앱으로 로그인한 적이 있다"는 boolean 마커 (토큰 아님 — 민감정보 없음).
|
|
2174
|
+
// 부트 시 cookie 복구(`/v1/auth/re-issue`)를 첫 인증 호출이 기다릴지 판단하는 데 쓴다:
|
|
2175
|
+
// - 힌트 있음 → 기존과 동일하게 대기 (로그인 세션의 첫 호출이 익명으로 나가는 것 방지).
|
|
2176
|
+
// - 힌트 없음 → 대기 생략. 익명 방문자(공개 사이트 첫 방문 대부분)의 첫 조회가
|
|
2177
|
+
// re-issue 왕복만큼 빨라진다. 복구 자체는 백그라운드로 계속 진행되므로, 드물게
|
|
2178
|
+
// 힌트가 지워졌지만 cookie 세션이 살아있는 경우도 이후 호출부터 자동 회복된다.
|
|
2179
|
+
//
|
|
2180
|
+
// 세션을 만드는 모든 흐름(로그인/OAuth 콜백/토큰 refresh)이 setTokens 를 경유하므로
|
|
2181
|
+
// 그곳에서 마킹하고, clearTokens(로그아웃)에서 지운다.
|
|
2182
|
+
buildSessionHintKey() {
|
|
2183
|
+
return `${this.buildStorageKey()}:has_session`;
|
|
2184
|
+
}
|
|
2185
|
+
markSessionHint() {
|
|
2186
|
+
if (typeof window === "undefined") return;
|
|
2444
2187
|
try {
|
|
2445
|
-
|
|
2446
|
-
return sessions.some(
|
|
2447
|
-
(s) => s.session_id === sessionId && s.current === true
|
|
2448
|
-
);
|
|
2188
|
+
localStorage.setItem(this.buildSessionHintKey(), "1");
|
|
2449
2189
|
} catch {
|
|
2450
|
-
return false;
|
|
2451
2190
|
}
|
|
2452
2191
|
}
|
|
2453
|
-
|
|
2454
|
-
|
|
2455
|
-
|
|
2456
|
-
|
|
2457
|
-
|
|
2458
|
-
const controller = new AbortController();
|
|
2459
|
-
const timeout = options.timeout ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
2460
|
-
const external = options.signal;
|
|
2461
|
-
let timeoutId = null;
|
|
2462
|
-
let externalListener = null;
|
|
2463
|
-
if (external) {
|
|
2464
|
-
if (external.aborted) {
|
|
2465
|
-
controller.abort(external.reason);
|
|
2466
|
-
} else {
|
|
2467
|
-
externalListener = () => controller.abort(external.reason);
|
|
2468
|
-
external.addEventListener("abort", externalListener, { once: true });
|
|
2192
|
+
clearSessionHint() {
|
|
2193
|
+
if (typeof window === "undefined") return;
|
|
2194
|
+
try {
|
|
2195
|
+
localStorage.removeItem(this.buildSessionHintKey());
|
|
2196
|
+
} catch {
|
|
2469
2197
|
}
|
|
2470
2198
|
}
|
|
2471
|
-
|
|
2472
|
-
|
|
2473
|
-
|
|
2474
|
-
|
|
2475
|
-
|
|
2476
|
-
|
|
2477
|
-
)
|
|
2478
|
-
);
|
|
2479
|
-
}, timeout);
|
|
2480
|
-
}
|
|
2481
|
-
return {
|
|
2482
|
-
signal: controller.signal,
|
|
2483
|
-
cleanup: () => {
|
|
2484
|
-
if (timeoutId !== null) clearTimeout(timeoutId);
|
|
2485
|
-
if (external && externalListener) {
|
|
2486
|
-
external.removeEventListener("abort", externalListener);
|
|
2487
|
-
}
|
|
2199
|
+
hasSessionHint() {
|
|
2200
|
+
if (typeof window === "undefined") return false;
|
|
2201
|
+
try {
|
|
2202
|
+
return localStorage.getItem(this.buildSessionHintKey()) === "1";
|
|
2203
|
+
} catch {
|
|
2204
|
+
return true;
|
|
2488
2205
|
}
|
|
2489
|
-
};
|
|
2490
|
-
}
|
|
2491
|
-
function withAbort(promise, signal) {
|
|
2492
|
-
if (!signal) return promise;
|
|
2493
|
-
const reason = () => signal.reason ?? new DOMException("The operation was aborted.", "AbortError");
|
|
2494
|
-
if (signal.aborted) {
|
|
2495
|
-
promise.catch(() => void 0);
|
|
2496
|
-
return Promise.reject(reason());
|
|
2497
2206
|
}
|
|
2498
|
-
|
|
2499
|
-
|
|
2500
|
-
|
|
2501
|
-
|
|
2502
|
-
|
|
2503
|
-
|
|
2504
|
-
|
|
2505
|
-
},
|
|
2506
|
-
(error) => {
|
|
2507
|
-
signal.removeEventListener("abort", onAbort);
|
|
2508
|
-
reject(error);
|
|
2509
|
-
}
|
|
2510
|
-
);
|
|
2511
|
-
});
|
|
2512
|
-
}
|
|
2513
|
-
|
|
2514
|
-
// src/core/recent-calls.ts
|
|
2515
|
-
var DEFAULT_CAPACITY = 20;
|
|
2516
|
-
var MAX_CAPACITY = 50;
|
|
2517
|
-
var RecentCallsBuffer = class {
|
|
2518
|
-
constructor(capacity = DEFAULT_CAPACITY) {
|
|
2519
|
-
this.buf = [];
|
|
2520
|
-
this.capacity = Math.min(Math.max(1, capacity), MAX_CAPACITY);
|
|
2207
|
+
// ===== cookie 세션 없음 마커 (platform-issue 01a0237f) =====
|
|
2208
|
+
//
|
|
2209
|
+
// `refreshLockedUntil` 백오프는 인스턴스 안에서만 산다. 앱이 클라이언트를 새로 만들 때마다
|
|
2210
|
+
// 초기화되므로, 쿠키가 없는 브라우저에서는 인증 호출마다 re-issue 401 이 새로 나간다.
|
|
2211
|
+
// 이 마커는 같은 사실을 localStorage 에 짧게 남겨 인스턴스 경계를 넘어 공유한다.
|
|
2212
|
+
buildNoCookieSessionKey() {
|
|
2213
|
+
return `${this.storageKey}:no_cookie_session`;
|
|
2521
2214
|
}
|
|
2522
|
-
|
|
2523
|
-
if (
|
|
2524
|
-
|
|
2215
|
+
markNoCookieSession() {
|
|
2216
|
+
if (typeof window === "undefined") return;
|
|
2217
|
+
try {
|
|
2218
|
+
localStorage.setItem(this.buildNoCookieSessionKey(), String(Date.now()));
|
|
2219
|
+
} catch {
|
|
2220
|
+
}
|
|
2221
|
+
}
|
|
2222
|
+
clearNoCookieSessionMark() {
|
|
2223
|
+
if (typeof window === "undefined") return;
|
|
2224
|
+
try {
|
|
2225
|
+
localStorage.removeItem(this.buildNoCookieSessionKey());
|
|
2226
|
+
} catch {
|
|
2525
2227
|
}
|
|
2526
|
-
this.buf.push(call);
|
|
2527
2228
|
}
|
|
2229
|
+
/** 쿠키 전용 refresh 를 지금 건너뛰어야 하는지 (최근에 401/403 을 받았는지). */
|
|
2528
2230
|
/**
|
|
2529
|
-
*
|
|
2231
|
+
* 이 브라우저에 세션이 없다는 것을 이미 아는가. 메모리에 access/refresh token 이 없고, 60초 안의 쿠키 복구가
|
|
2232
|
+
* "세션 없음"(401 또는 quiet 204)으로 끝났으면 true 다. 회원 전용 API 는 물어도 401 뿐이라, 부르는 쪽이 요청을
|
|
2233
|
+
* 건너뛰고 {@link rejectNoSession} 으로 같은 오류를 던질 때 쓴다.
|
|
2530
2234
|
*/
|
|
2531
|
-
|
|
2532
|
-
return this.
|
|
2533
|
-
}
|
|
2534
|
-
clear() {
|
|
2535
|
-
this.buf = [];
|
|
2235
|
+
knowsNoSession() {
|
|
2236
|
+
return typeof window !== "undefined" && !this.config.accessToken && !this.config.refreshToken && this.isNoCookieSessionMarkFresh();
|
|
2536
2237
|
}
|
|
2537
|
-
|
|
2538
|
-
|
|
2539
|
-
|
|
2540
|
-
|
|
2541
|
-
|
|
2542
|
-
|
|
2543
|
-
|
|
2544
|
-
|
|
2238
|
+
/**
|
|
2239
|
+
* 세션이 없을 때 서버가 돌려주는 것과 같은 401 ApiError 를 요청 없이 만든다. 서버 경로와 같은 변환(buildApiError)과
|
|
2240
|
+
* 오류 알림(emitError)을 거치므로 앱이 받는 오류는 그대로이고, 브라우저 콘솔에 실패한 요청만 남지 않는다.
|
|
2241
|
+
*/
|
|
2242
|
+
async rejectNoSession() {
|
|
2243
|
+
const err = await this.buildApiError(
|
|
2244
|
+
new Response(JSON.stringify({ error: "\uC778\uC99D \uD1A0\uD070\uC774 \uD544\uC694\uD569\uB2C8\uB2E4" }), {
|
|
2245
|
+
status: 401,
|
|
2246
|
+
headers: { "Content-Type": "application/json" }
|
|
2247
|
+
})
|
|
2248
|
+
);
|
|
2249
|
+
this.emitError(err);
|
|
2250
|
+
return err;
|
|
2545
2251
|
}
|
|
2546
|
-
|
|
2547
|
-
|
|
2548
|
-
|
|
2549
|
-
|
|
2550
|
-
|
|
2551
|
-
|
|
2552
|
-
|
|
2553
|
-
|
|
2554
|
-
|
|
2555
|
-
|
|
2556
|
-
}
|
|
2557
|
-
|
|
2558
|
-
|
|
2559
|
-
|
|
2560
|
-
|
|
2252
|
+
isNoCookieSessionMarkFresh() {
|
|
2253
|
+
if (typeof window === "undefined") return false;
|
|
2254
|
+
try {
|
|
2255
|
+
const raw = localStorage.getItem(this.buildNoCookieSessionKey());
|
|
2256
|
+
if (!raw) return false;
|
|
2257
|
+
const at = Number.parseInt(raw, 10);
|
|
2258
|
+
if (!Number.isFinite(at)) return false;
|
|
2259
|
+
if (Date.now() - at >= NO_COOKIE_SESSION_COOLDOWN_MS) {
|
|
2260
|
+
this.clearNoCookieSessionMark();
|
|
2261
|
+
return false;
|
|
2262
|
+
}
|
|
2263
|
+
return true;
|
|
2264
|
+
} catch {
|
|
2265
|
+
return false;
|
|
2266
|
+
}
|
|
2561
2267
|
}
|
|
2562
|
-
|
|
2563
|
-
|
|
2564
|
-
|
|
2565
|
-
|
|
2566
|
-
|
|
2567
|
-
|
|
2568
|
-
|
|
2569
|
-
|
|
2570
|
-
|
|
2571
|
-
|
|
2572
|
-
|
|
2573
|
-
|
|
2574
|
-
|
|
2575
|
-
|
|
2268
|
+
/**
|
|
2269
|
+
* OAuth redirect callback 직후 호출되어 HttpOnly cookie 를 부트스트랩한다.
|
|
2270
|
+
*
|
|
2271
|
+
* 배경: 콜백 흐름에서 서버가 redirect 응답에 Set-Cookie 를 함께 발급하지만, 일부 deployment /
|
|
2272
|
+
* 브라우저 정책 / 사용자 설정 (3rd-party cookie 차단 등) 환경에서 이 Set-Cookie 가 브라우저에
|
|
2273
|
+
* 저장되지 않는다. `persistence='none'` 모드에서는 토큰이 메모리에만 있고 cookie 가 없는 상태로
|
|
2274
|
+
* 페이지 새로고침이 발생하면 `/v1/auth/re-issue` 가 401 으로 떨어져 강제 로그아웃되는 회귀가
|
|
2275
|
+
* 있다 (platform-issue 019e3960, 2026-05-18).
|
|
2276
|
+
*
|
|
2277
|
+
* 이 메서드는 메모리의 refresh token 으로 한 번 `/v1/auth/re-issue` 를 호출해 서버가 cookie 를
|
|
2278
|
+
* 명시적으로 발급하도록 유도한다. 백엔드는 Bearer + `X-Public-Key` 조합을 SDK 호출 신호로
|
|
2279
|
+
* 인식해 응답에 `cb_member_refresh_token` cookie 를 함께 내려준다.
|
|
2280
|
+
*
|
|
2281
|
+
* persistence='localStorage' / 'sessionStorage' 모드는 새로고침 후에도 메모리 복구가 가능하므로
|
|
2282
|
+
* 호출하지 않는다 (rotation 만 일어나 비용만 증가). 비-브라우저 환경에서도 cookie 자체가 없으므로
|
|
2283
|
+
* 호출하지 않는다.
|
|
2284
|
+
*/
|
|
2285
|
+
async bootstrapRefreshCookie() {
|
|
2286
|
+
if (typeof window === "undefined") return;
|
|
2287
|
+
if (this.persistence !== "none") return;
|
|
2288
|
+
if (!this.config.refreshToken) return;
|
|
2289
|
+
try {
|
|
2290
|
+
await this.refreshAccessToken({ silent: true });
|
|
2291
|
+
} catch {
|
|
2292
|
+
}
|
|
2576
2293
|
}
|
|
2577
|
-
|
|
2578
|
-
|
|
2579
|
-
|
|
2580
|
-
case 502:
|
|
2581
|
-
return "\uAC8C\uC774\uD2B8\uC6E8\uC774\uAC00 \uC11C\uBC84\uB85C\uBD80\uD130 \uC62C\uBC14\uB978 \uC751\uB2F5\uC744 \uBC1B\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4 (502)";
|
|
2582
|
-
case 503:
|
|
2583
|
-
return "\uC11C\uBC84\uAC00 \uC77C\uC2DC\uC801\uC73C\uB85C \uC694\uCCAD\uC744 \uCC98\uB9AC\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4 (503)";
|
|
2584
|
-
case 504:
|
|
2585
|
-
return "\uAC8C\uC774\uD2B8\uC6E8\uC774\uAC00 \uC751\uB2F5\uC744 \uAE30\uB2E4\uB9AC\uB2E4 \uC5F0\uACB0\uC744 \uB04A\uC5C8\uC2B5\uB2C8\uB2E4 (504). \uC624\uB798 \uAC78\uB9AC\uB294 \uC791\uC5C5\uC774\uBA74 \uC694\uCCAD \uD0C0\uC784\uC544\uC6C3\uC744 \uB298\uB9AC\uAC70\uB098 \uC2A4\uD2B8\uB9AC\uBC0D\uC744 \uC0AC\uC6A9\uD558\uC138\uC694";
|
|
2586
|
-
default:
|
|
2587
|
-
return void 0;
|
|
2294
|
+
// ===== Token Persistence =====
|
|
2295
|
+
get persistence() {
|
|
2296
|
+
return this.config.persistence ?? "none";
|
|
2588
2297
|
}
|
|
2589
|
-
|
|
2590
|
-
|
|
2591
|
-
|
|
2592
|
-
|
|
2593
|
-
if (
|
|
2594
|
-
|
|
2595
|
-
const padded = base64 + "=".repeat((4 - base64.length % 4) % 4);
|
|
2596
|
-
const parsed = JSON.parse(atob(padded));
|
|
2597
|
-
return parsed && typeof parsed === "object" ? parsed : null;
|
|
2598
|
-
} catch {
|
|
2298
|
+
getStorage() {
|
|
2299
|
+
if (typeof window === "undefined") return null;
|
|
2300
|
+
if (this.persistence === "localStorage" && typeof localStorage !== "undefined")
|
|
2301
|
+
return localStorage;
|
|
2302
|
+
if (this.persistence === "sessionStorage" && typeof sessionStorage !== "undefined")
|
|
2303
|
+
return sessionStorage;
|
|
2599
2304
|
return null;
|
|
2600
2305
|
}
|
|
2601
|
-
|
|
2602
|
-
|
|
2603
|
-
|
|
2604
|
-
|
|
2605
|
-
|
|
2606
|
-
|
|
2607
|
-
function isSameMemberToken(a, b) {
|
|
2608
|
-
const pa = decodeJwtPayload(a);
|
|
2609
|
-
const pb = decodeJwtPayload(b);
|
|
2610
|
-
if (!pa || !pb || pa.role !== "AppMember" || pb.role !== "AppMember") {
|
|
2611
|
-
return false;
|
|
2306
|
+
/**
|
|
2307
|
+
* AuthAPI 등 내부 사용자가 "현재 persistence 설정된 스토리지"를 확인할 수 있도록 노출.
|
|
2308
|
+
* persistence='none' 이면 null. XSS 완화 기본값을 공유하기 위함.
|
|
2309
|
+
*/
|
|
2310
|
+
getPersistenceStorage() {
|
|
2311
|
+
return this.getStorage();
|
|
2612
2312
|
}
|
|
2613
|
-
|
|
2614
|
-
|
|
2615
|
-
|
|
2616
|
-
|
|
2617
|
-
|
|
2618
|
-
|
|
2619
|
-
|
|
2620
|
-
var EDGE_HINTS_TTL_MS = 10 * 6e4;
|
|
2621
|
-
var sharedEdgeHints = /* @__PURE__ */ new Map();
|
|
2622
|
-
function lookupEdgeHints(baseUrl, timeoutMs) {
|
|
2623
|
-
const cached = sharedEdgeHints.get(baseUrl);
|
|
2624
|
-
if (cached && Date.now() < cached.expiresAt) return cached.promise;
|
|
2625
|
-
const entry = {
|
|
2626
|
-
promise: fetchEdgeHintAdverts(baseUrl, timeoutMs),
|
|
2627
|
-
// 진행 중에는 만료되지 않는다 — 시간 제한(withAbort) 때문에 timeoutMs 안에 반드시 끝난다. 늦게 합류한
|
|
2628
|
-
// 인스턴스는 남은 시간만 기다린다.
|
|
2629
|
-
expiresAt: Number.POSITIVE_INFINITY
|
|
2630
|
-
};
|
|
2631
|
-
sharedEdgeHints.set(baseUrl, entry);
|
|
2632
|
-
entry.promise.then(
|
|
2633
|
-
() => {
|
|
2634
|
-
entry.expiresAt = Date.now() + EDGE_HINTS_TTL_MS;
|
|
2635
|
-
},
|
|
2636
|
-
() => {
|
|
2637
|
-
if (sharedEdgeHints.get(baseUrl) === entry) {
|
|
2638
|
-
sharedEdgeHints.delete(baseUrl);
|
|
2639
|
-
}
|
|
2313
|
+
buildStorageKey() {
|
|
2314
|
+
const credential = this.config.publicKey ?? this.config.secretKey;
|
|
2315
|
+
if (!credential) return TOKEN_STORAGE_KEY;
|
|
2316
|
+
let hash = 0;
|
|
2317
|
+
for (let i = 0; i < credential.length; i++) {
|
|
2318
|
+
hash = (hash << 5) - hash + credential.charCodeAt(i);
|
|
2319
|
+
hash = hash & hash;
|
|
2640
2320
|
}
|
|
2641
|
-
|
|
2642
|
-
|
|
2643
|
-
|
|
2644
|
-
|
|
2645
|
-
|
|
2646
|
-
|
|
2647
|
-
|
|
2648
|
-
|
|
2649
|
-
|
|
2650
|
-
|
|
2651
|
-
|
|
2652
|
-
|
|
2653
|
-
|
|
2321
|
+
return `${TOKEN_STORAGE_KEY}_${Math.abs(hash).toString(36)}`;
|
|
2322
|
+
}
|
|
2323
|
+
persistTokens() {
|
|
2324
|
+
if (this.persistence === "none") return;
|
|
2325
|
+
const storage = this.getStorage();
|
|
2326
|
+
if (!storage || !this.config.accessToken || !this.config.refreshToken)
|
|
2327
|
+
return;
|
|
2328
|
+
storage.setItem(
|
|
2329
|
+
this.storageKey,
|
|
2330
|
+
JSON.stringify({
|
|
2331
|
+
accessToken: this.config.accessToken,
|
|
2332
|
+
refreshToken: this.config.refreshToken
|
|
2333
|
+
})
|
|
2654
2334
|
);
|
|
2655
|
-
|
|
2656
|
-
|
|
2657
|
-
|
|
2658
|
-
|
|
2659
|
-
|
|
2660
|
-
|
|
2661
|
-
|
|
2662
|
-
|
|
2335
|
+
}
|
|
2336
|
+
restoreTokens() {
|
|
2337
|
+
if (this.persistence === "none") return;
|
|
2338
|
+
if (this.config.accessToken && this.config.refreshToken) return;
|
|
2339
|
+
const storage = this.getStorage();
|
|
2340
|
+
if (!storage) return;
|
|
2341
|
+
const stored = storage.getItem(this.storageKey);
|
|
2342
|
+
if (!stored) return;
|
|
2663
2343
|
try {
|
|
2664
|
-
|
|
2665
|
-
|
|
2666
|
-
|
|
2667
|
-
|
|
2344
|
+
const { accessToken, refreshToken } = JSON.parse(stored);
|
|
2345
|
+
if (accessToken && refreshToken) {
|
|
2346
|
+
this.config.accessToken = accessToken;
|
|
2347
|
+
this.config.refreshToken = refreshToken;
|
|
2348
|
+
}
|
|
2349
|
+
} catch {
|
|
2350
|
+
storage.removeItem(this.storageKey);
|
|
2668
2351
|
}
|
|
2669
|
-
return [
|
|
2670
|
-
header,
|
|
2671
|
-
{ direct: body?.direct_base, realtime: body?.realtime_direct_base }
|
|
2672
|
-
];
|
|
2673
|
-
} finally {
|
|
2674
|
-
cleanup();
|
|
2675
2352
|
}
|
|
2676
|
-
|
|
2677
|
-
|
|
2678
|
-
|
|
2679
|
-
|
|
2680
|
-
this.
|
|
2681
|
-
|
|
2682
|
-
|
|
2683
|
-
|
|
2684
|
-
|
|
2685
|
-
|
|
2686
|
-
|
|
2687
|
-
|
|
2688
|
-
|
|
2689
|
-
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
|
|
2694
|
-
|
|
2695
|
-
|
|
2696
|
-
|
|
2697
|
-
|
|
2698
|
-
|
|
2699
|
-
this.bootRestoreAlwaysAwait = false;
|
|
2700
|
-
/**
|
|
2701
|
-
* 서버가 `X-CB-Direct-Base` 로 알려준 저지연 원본. 학습 전에는 null 이라 항상 `baseUrl`
|
|
2702
|
-
* 을 쓴다. {@link resolveOrigin} 참고.
|
|
2703
|
-
*/
|
|
2704
|
-
this.directBaseUrl = null;
|
|
2705
|
-
/**
|
|
2706
|
-
* direct 원본을 이 세션에서 더는 쓰지 않는다는 표시. 한 번이라도 네트워크 레벨에서
|
|
2707
|
-
* 실패하면(CSP `connect-src` 차단, 사내 프록시, DNS 미전파, 호스트 회수 등) 즉시 세워
|
|
2708
|
-
* 이후 요청은 전부 `baseUrl` 로 간다. direct 는 최적화일 뿐 필수가 아니므로 재시도를
|
|
2709
|
-
* 반복하지 않고 한 번에 포기하는 쪽이 안전하다.
|
|
2710
|
-
*/
|
|
2711
|
-
this.directDisabled = false;
|
|
2712
|
-
/**
|
|
2713
|
-
* 서버가 `X-CB-Realtime-Direct-Base` 로 알려준 socket-server 저지연 원본(`wss://...`).
|
|
2714
|
-
* HTTP direct(`directBaseUrl`)와 별도 값·별도 킬 스위치 — core-server 응답에서만 학습되고
|
|
2715
|
-
* (WS 업그레이드 응답 헤더는 브라우저가 못 읽는다), `RealtimeAPI.doConnect()` 가 매 연결
|
|
2716
|
-
* 시도마다 lazy 하게 조회한다. platform-issue 019fe448.
|
|
2717
|
-
*/
|
|
2718
|
-
this.directRealtimeBaseUrl = null;
|
|
2719
|
-
/**
|
|
2720
|
-
* realtime WS 연결이 direct 원본에서 네트워크 레벨로 실패하면 세운다 — `directDisabled`
|
|
2721
|
-
* 와 같은 철학("한 번 실패하면 이 세션에서는 포기하고 원래 호스트로")이지만, 실패 감지가
|
|
2722
|
-
* WS 상태 머신(RealtimeAPI) 쪽에서 일어나므로 별도 플래그로 둔다.
|
|
2723
|
-
*/
|
|
2724
|
-
this.directRealtimeDisabled = false;
|
|
2725
|
-
this.config = { ...config };
|
|
2726
|
-
this.storageKey = this.buildStorageKey();
|
|
2727
|
-
this.warnIfUnsafePersistence();
|
|
2728
|
-
this.warnIfSecretKeyInBrowser();
|
|
2729
|
-
this.restoreTokens();
|
|
2353
|
+
removePersistedTokens() {
|
|
2354
|
+
if (this.persistence === "none") return;
|
|
2355
|
+
const storage = this.getStorage();
|
|
2356
|
+
if (!storage) return;
|
|
2357
|
+
storage.removeItem(this.storageKey);
|
|
2358
|
+
}
|
|
2359
|
+
/**
|
|
2360
|
+
* Public Key 가 설정되어 있는지 확인
|
|
2361
|
+
*/
|
|
2362
|
+
hasPublicKey() {
|
|
2363
|
+
return !!this.config.publicKey;
|
|
2364
|
+
}
|
|
2365
|
+
/**
|
|
2366
|
+
* Public Key 반환
|
|
2367
|
+
*/
|
|
2368
|
+
getPublicKey() {
|
|
2369
|
+
return this.config.publicKey;
|
|
2370
|
+
}
|
|
2371
|
+
/**
|
|
2372
|
+
* Secret Key 가 설정되어 있는지 확인
|
|
2373
|
+
*/
|
|
2374
|
+
hasSecretKey() {
|
|
2375
|
+
return !!this.config.secretKey;
|
|
2730
2376
|
}
|
|
2731
2377
|
/**
|
|
2732
|
-
*
|
|
2733
|
-
*
|
|
2734
|
-
* API 모듈이 자기 엔드포인트에 맞는 기본 타임아웃을 고를 때, 사용자가 명시한 값이
|
|
2735
|
-
* 있으면 그쪽을 존중하기 위해 필요하다 (`ai.chat` 이 이 값을 읽는다). `config` 자체를
|
|
2736
|
-
* 노출하면 토큰/스토리지 설정까지 새므로 이 필드만 읽기 전용으로 연다.
|
|
2378
|
+
* Secret Key 반환
|
|
2737
2379
|
*/
|
|
2738
|
-
|
|
2739
|
-
return this.config.
|
|
2380
|
+
getSecretKey() {
|
|
2381
|
+
return this.config.secretKey;
|
|
2740
2382
|
}
|
|
2741
2383
|
/**
|
|
2742
|
-
*
|
|
2743
|
-
* 같은 promise 가 `prepareHeaders` 에서 await 되어, 첫 인증 호출이 cookie 복구
|
|
2744
|
-
* 완료 후 발화한다.
|
|
2384
|
+
* 현재 설정된 자격증명 반환.
|
|
2745
2385
|
*
|
|
2746
|
-
*
|
|
2747
|
-
*
|
|
2748
|
-
*
|
|
2386
|
+
* publicKey 가 있으면 그걸 반환한다 (X-Public-Key 헤더 = 앱 식별용 = cb_pk_*).
|
|
2387
|
+
* publicKey 가 없고 secretKey 만 있는 경우는 secretKey 로 폴백 — 단, 서버는
|
|
2388
|
+
* cb_sk_ 가 X-Public-Key 에 실리면 거부하므로 의도된 401 이 나간다(앱 식별 불가).
|
|
2389
|
+
*
|
|
2390
|
+
* secretKey 의 admin 권한은 별도로 Authorization: Bearer 로 보낸다. 그 처리는
|
|
2391
|
+
* prepareHeaders 안에서 publicKey + secretKey 가 함께 있을 때 수행한다.
|
|
2749
2392
|
*/
|
|
2750
|
-
|
|
2751
|
-
this.
|
|
2752
|
-
this.bootRestoreAlwaysAwait = options?.alwaysAwait === true;
|
|
2393
|
+
getCredential() {
|
|
2394
|
+
return this.config.publicKey ?? this.config.secretKey;
|
|
2753
2395
|
}
|
|
2754
|
-
/**
|
|
2755
|
-
|
|
2756
|
-
|
|
2396
|
+
/**
|
|
2397
|
+
* Access Token 반환
|
|
2398
|
+
*/
|
|
2399
|
+
getAccessToken() {
|
|
2400
|
+
return this.config.accessToken;
|
|
2757
2401
|
}
|
|
2758
|
-
/**
|
|
2759
|
-
|
|
2760
|
-
|
|
2402
|
+
/**
|
|
2403
|
+
* JWT(Access Token) 가 설정되어 있는지 확인
|
|
2404
|
+
*/
|
|
2405
|
+
hasJWT() {
|
|
2406
|
+
return !!this.config.accessToken;
|
|
2761
2407
|
}
|
|
2762
2408
|
/**
|
|
2763
|
-
*
|
|
2764
|
-
* 막지는 않는다(Electron 등 신뢰된 환경이 있다) — 대신 무엇이 위험한지 분명히 알린다.
|
|
2409
|
+
* Base URL 반환
|
|
2765
2410
|
*/
|
|
2766
|
-
|
|
2767
|
-
|
|
2768
|
-
return;
|
|
2769
|
-
}
|
|
2770
|
-
const misplaced = this.config.publicKey?.startsWith("cb_sk_") === true;
|
|
2771
|
-
if (!this.config.secretKey && !misplaced) return;
|
|
2772
|
-
console.warn(
|
|
2773
|
-
"[connect-base-client] \uBE0C\uB77C\uC6B0\uC800\uC5D0\uC11C Secret Key(cb_sk_)\uB97C \uC4F0\uACE0 \uC788\uC2B5\uB2C8\uB2E4. \uD398\uC774\uC9C0\uB97C \uC5EC\uB294 \uB204\uAD6C\uB098 \uC774 \uD0A4\uB97C \uC77D\uC5B4 \uACC4\uC815 \uAD8C\uD55C\uC73C\uB85C API \uB97C \uD638\uCD9C\uD560 \uC218 \uC788\uC2B5\uB2C8\uB2E4. \uBE0C\uB77C\uC6B0\uC800\uC5D0\uB294 publicKey(cb_pk_)\uB9CC \uB123\uACE0 Secret Key \uB294 \uC11C\uBC84\uB098 CLI \uC5D0\uC11C\uB9CC \uC4F0\uC138\uC694. \uC774\uBBF8 \uBC30\uD3EC\uB410\uB2E4\uBA74 \uCF58\uC194\uC5D0\uC11C \uD0A4\uB97C \uD3D0\uAE30\uD558\uACE0 \uC0C8\uB85C \uBC1C\uAE09\uD558\uC138\uC694."
|
|
2774
|
-
);
|
|
2411
|
+
getBaseUrl() {
|
|
2412
|
+
return this.config.baseUrl;
|
|
2775
2413
|
}
|
|
2776
|
-
|
|
2777
|
-
|
|
2778
|
-
|
|
2779
|
-
|
|
2780
|
-
|
|
2781
|
-
|
|
2782
|
-
|
|
2783
|
-
console.warn(
|
|
2784
|
-
`[connect-base-client] persistence="sessionStorage" \uB294 XSS \uC2DC \uD0ED \uC138\uC158 \uD0C8\uCDE8 \uC704\uD5D8\uC774 \uC788\uC2B5\uB2C8\uB2E4. \uAE30\uBCF8\uAC12('none') + HttpOnly cookie \uD750\uB984\uC744 \uAD8C\uC7A5\uD569\uB2C8\uB2E4.`
|
|
2785
|
-
);
|
|
2786
|
-
}
|
|
2414
|
+
/**
|
|
2415
|
+
* socket-server 의 direct(저지연) WS 원본. 아직 학습 전이거나(REST 요청을 한 번도 안
|
|
2416
|
+
* 보냈거나 서버가 광고를 안 함) 네트워크 레벨로 실패해 이 세션에서 포기했으면 `null` —
|
|
2417
|
+
* 호출자(`RealtimeAPI`)는 이 경우 원래 소켓 URL로 폴백해야 한다.
|
|
2418
|
+
*/
|
|
2419
|
+
getDirectRealtimeBaseUrl() {
|
|
2420
|
+
return this.directRealtimeDisabled ? null : this.directRealtimeBaseUrl;
|
|
2787
2421
|
}
|
|
2788
|
-
|
|
2789
|
-
|
|
2422
|
+
/**
|
|
2423
|
+
* direct WS 원본이 네트워크 레벨로 실패했을 때 `RealtimeAPI` 가 호출한다. 이후 연결
|
|
2424
|
+
* 시도는 이 세션 동안 전부 원래 소켓 URL로 간다 — direct 는 최적화일 뿐 필수가 아니므로
|
|
2425
|
+
* 재시도를 반복하지 않는다(`directDisabled`/HTTP direct 와 같은 철학).
|
|
2426
|
+
*/
|
|
2427
|
+
disableDirectRealtime() {
|
|
2428
|
+
this.directRealtimeDisabled = true;
|
|
2790
2429
|
}
|
|
2791
|
-
|
|
2792
|
-
|
|
2793
|
-
|
|
2794
|
-
|
|
2795
|
-
|
|
2796
|
-
|
|
2430
|
+
/**
|
|
2431
|
+
* 이 클라이언트에 설정된 앱 ID 반환 (미설정 시 undefined).
|
|
2432
|
+
*
|
|
2433
|
+
* 콘솔(앱 소유자 JWT) 경로를 호출하기 전에 appId 유무를 확인하기 위한 public 접근자.
|
|
2434
|
+
* private `config` 필드를 access-modifier 관통 cast 없이 노출한다.
|
|
2435
|
+
*/
|
|
2436
|
+
getAppId() {
|
|
2437
|
+
return this.config.appId;
|
|
2797
2438
|
}
|
|
2798
|
-
|
|
2799
|
-
|
|
2800
|
-
this.
|
|
2801
|
-
|
|
2802
|
-
|
|
2439
|
+
async refreshAccessToken(options) {
|
|
2440
|
+
const silent = options?.silent ?? false;
|
|
2441
|
+
if (this.isRefreshing) {
|
|
2442
|
+
return this.refreshPromise;
|
|
2443
|
+
}
|
|
2444
|
+
const now = Date.now();
|
|
2445
|
+
if (now < this.refreshLockedUntil) {
|
|
2446
|
+
const error = new AuthError(
|
|
2447
|
+
"Token refresh locked due to repeated failures. Please login again."
|
|
2448
|
+
);
|
|
2449
|
+
this.emitError(error);
|
|
2450
|
+
this.config.onAuthError?.(error);
|
|
2451
|
+
throw error;
|
|
2452
|
+
}
|
|
2453
|
+
if (!this.config.refreshToken && this.isNoCookieSessionMarkFresh()) {
|
|
2454
|
+
throw new AuthError(
|
|
2455
|
+
"No cookie session (recently rejected). Skipping token refresh."
|
|
2456
|
+
);
|
|
2457
|
+
}
|
|
2458
|
+
this.isRefreshing = true;
|
|
2459
|
+
if (!this.config.refreshToken && typeof window === "undefined") {
|
|
2460
|
+
this.isRefreshing = false;
|
|
2461
|
+
this.config.onTokenExpired?.();
|
|
2462
|
+
const error = new AuthError(
|
|
2463
|
+
"Refresh token is missing. Please login again."
|
|
2464
|
+
);
|
|
2465
|
+
this.emitError(error);
|
|
2466
|
+
this.config.onAuthError?.(error);
|
|
2467
|
+
throw error;
|
|
2468
|
+
}
|
|
2469
|
+
this.refreshPromise = (async () => {
|
|
2470
|
+
const { signal, cleanup } = createTimeoutController({
|
|
2471
|
+
timeout: this.config.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS
|
|
2472
|
+
});
|
|
2473
|
+
let failureKind = "transient";
|
|
2474
|
+
try {
|
|
2475
|
+
const headers = {
|
|
2476
|
+
"Content-Type": "application/json"
|
|
2477
|
+
};
|
|
2478
|
+
if (this.config.refreshToken) {
|
|
2479
|
+
headers.Authorization = `Bearer ${this.config.refreshToken}`;
|
|
2480
|
+
}
|
|
2481
|
+
const credential = this.getCredential();
|
|
2482
|
+
if (credential) {
|
|
2483
|
+
headers["X-Public-Key"] = credential;
|
|
2484
|
+
}
|
|
2485
|
+
const cookieOnly = !this.config.refreshToken;
|
|
2486
|
+
const response = await withAbort(
|
|
2487
|
+
fetch(
|
|
2488
|
+
`${this.config.baseUrl}/v1/auth/re-issue${cookieOnly ? "?quiet=1" : ""}`,
|
|
2489
|
+
{
|
|
2490
|
+
method: "POST",
|
|
2491
|
+
headers,
|
|
2492
|
+
credentials: "include",
|
|
2493
|
+
signal
|
|
2494
|
+
}
|
|
2495
|
+
),
|
|
2496
|
+
signal
|
|
2497
|
+
);
|
|
2498
|
+
if (cookieOnly && response.status === 204) {
|
|
2499
|
+
failureKind = "permanent";
|
|
2500
|
+
throw new Error("Token refresh failed (no session)");
|
|
2501
|
+
}
|
|
2502
|
+
if (!response.ok) {
|
|
2503
|
+
const status = response.status;
|
|
2504
|
+
let oauthError;
|
|
2505
|
+
try {
|
|
2506
|
+
const errBody = await response.clone().json();
|
|
2507
|
+
if (errBody && typeof errBody.error === "string") {
|
|
2508
|
+
oauthError = errBody.error;
|
|
2509
|
+
} else if (errBody && typeof errBody.code === "string") {
|
|
2510
|
+
oauthError = errBody.code;
|
|
2511
|
+
}
|
|
2512
|
+
} catch {
|
|
2513
|
+
}
|
|
2514
|
+
if (status >= 500) {
|
|
2515
|
+
throw new Error(`Token refresh failed (${status})`);
|
|
2516
|
+
}
|
|
2517
|
+
if (status === 401 || status === 403 || status === 400 && (oauthError === "invalid_grant" || oauthError === "invalid_token")) {
|
|
2518
|
+
failureKind = "permanent";
|
|
2519
|
+
} else {
|
|
2520
|
+
failureKind = "client_bug";
|
|
2521
|
+
}
|
|
2522
|
+
throw new Error(
|
|
2523
|
+
`Token refresh failed (${status}${oauthError ? ` ${oauthError}` : ""})`
|
|
2524
|
+
);
|
|
2525
|
+
}
|
|
2526
|
+
const data = await response.json();
|
|
2527
|
+
if (!data || typeof data.access_token !== "string") {
|
|
2528
|
+
throw new Error("Token refresh response missing access_token");
|
|
2529
|
+
}
|
|
2530
|
+
if (isConsolePlatformToken(data.access_token)) {
|
|
2531
|
+
this.refreshFailureCount = 0;
|
|
2532
|
+
this.refreshLockedUntil = 0;
|
|
2533
|
+
return null;
|
|
2534
|
+
}
|
|
2535
|
+
if (this.config.appId) {
|
|
2536
|
+
const tokenAppId = decodeJwtPayload(data.access_token)?.app_id;
|
|
2537
|
+
if (typeof tokenAppId === "string" && tokenAppId !== this.config.appId) {
|
|
2538
|
+
this.clearTokens();
|
|
2539
|
+
this.refreshFailureCount = 0;
|
|
2540
|
+
this.refreshLockedUntil = 0;
|
|
2541
|
+
return null;
|
|
2542
|
+
}
|
|
2543
|
+
}
|
|
2544
|
+
const nextRefreshToken = typeof data.refresh_token === "string" && data.refresh_token.length > 0 ? data.refresh_token : this.config.refreshToken ?? "";
|
|
2545
|
+
if (nextRefreshToken) {
|
|
2546
|
+
this.setTokens(data.access_token, nextRefreshToken);
|
|
2547
|
+
} else {
|
|
2548
|
+
this.config.accessToken = data.access_token;
|
|
2549
|
+
this.persistTokens();
|
|
2550
|
+
}
|
|
2551
|
+
this.config.onTokenRefresh?.({
|
|
2552
|
+
accessToken: data.access_token,
|
|
2553
|
+
refreshToken: nextRefreshToken
|
|
2554
|
+
});
|
|
2555
|
+
this.refreshFailureCount = 0;
|
|
2556
|
+
this.refreshLockedUntil = 0;
|
|
2557
|
+
this.clearNoCookieSessionMark();
|
|
2558
|
+
return data.access_token;
|
|
2559
|
+
} catch (e) {
|
|
2560
|
+
const baseMsg = e instanceof Error ? e.message : "Token refresh failed";
|
|
2561
|
+
this.refreshFailureCount++;
|
|
2562
|
+
const backoffMs = Math.min(
|
|
2563
|
+
500 * 2 ** Math.max(0, this.refreshFailureCount - 1),
|
|
2564
|
+
3e4
|
|
2565
|
+
);
|
|
2566
|
+
this.refreshLockedUntil = Date.now() + backoffMs;
|
|
2567
|
+
if (failureKind === "permanent" && !this.config.refreshToken) {
|
|
2568
|
+
this.markNoCookieSession();
|
|
2569
|
+
}
|
|
2570
|
+
if (failureKind === "permanent") {
|
|
2571
|
+
if (!silent) {
|
|
2572
|
+
this.clearTokens();
|
|
2573
|
+
this.config.onTokenExpired?.();
|
|
2574
|
+
}
|
|
2575
|
+
const error2 = new AuthError(`${baseMsg}. Please login again.`);
|
|
2576
|
+
if (!silent) {
|
|
2577
|
+
this.emitError(error2);
|
|
2578
|
+
this.config.onAuthError?.(error2);
|
|
2579
|
+
}
|
|
2580
|
+
throw error2;
|
|
2581
|
+
}
|
|
2582
|
+
if (failureKind === "client_bug") {
|
|
2583
|
+
const error2 = new AuthError(
|
|
2584
|
+
`${baseMsg}. Client request invalid; tokens preserved.`
|
|
2585
|
+
);
|
|
2586
|
+
if (!silent) {
|
|
2587
|
+
this.emitError(error2);
|
|
2588
|
+
this.config.onAuthError?.(error2);
|
|
2589
|
+
}
|
|
2590
|
+
throw error2;
|
|
2591
|
+
}
|
|
2592
|
+
const error = new AuthError(
|
|
2593
|
+
`${baseMsg}. Transient failure; tokens preserved, will retry after backoff.`
|
|
2594
|
+
);
|
|
2595
|
+
if (!silent) {
|
|
2596
|
+
this.emitError(error);
|
|
2597
|
+
this.config.onTransientRefreshFailure?.(error);
|
|
2598
|
+
this.config.onAuthError?.(error);
|
|
2599
|
+
}
|
|
2600
|
+
throw error;
|
|
2601
|
+
} finally {
|
|
2602
|
+
cleanup();
|
|
2603
|
+
this.isRefreshing = false;
|
|
2604
|
+
this.refreshPromise = null;
|
|
2605
|
+
}
|
|
2606
|
+
})();
|
|
2607
|
+
return this.refreshPromise;
|
|
2803
2608
|
}
|
|
2804
2609
|
/**
|
|
2805
|
-
*
|
|
2610
|
+
* 새로고침/탭 재개 시 HttpOnly cookie 만으로 access token 을 복구한다.
|
|
2806
2611
|
*
|
|
2807
|
-
*
|
|
2808
|
-
*
|
|
2809
|
-
*
|
|
2612
|
+
* 동작:
|
|
2613
|
+
* - 메모리에 access token 이 이미 있으면 그대로 반환 (true).
|
|
2614
|
+
* - 없으면 `/v1/auth/re-issue` 를 cookie 만으로 호출. cookie 가 있으면 access token 회복.
|
|
2615
|
+
* - cookie 가 없거나(미로그인) 만료된 경우 조용히 false 반환 (콘솔 에러 없음).
|
|
2810
2616
|
*
|
|
2811
|
-
*
|
|
2812
|
-
* 마커는 로그인/재발급이 소유한다.
|
|
2617
|
+
* 비-브라우저 환경에서는 cookie 흐름이 없으므로 즉시 false 반환.
|
|
2813
2618
|
*/
|
|
2814
|
-
|
|
2815
|
-
|
|
2816
|
-
this.
|
|
2817
|
-
|
|
2818
|
-
// ===== 세션 힌트 =====
|
|
2819
|
-
//
|
|
2820
|
-
// "이 origin 에서 이 앱으로 로그인한 적이 있다"는 boolean 마커 (토큰 아님 — 민감정보 없음).
|
|
2821
|
-
// 부트 시 cookie 복구(`/v1/auth/re-issue`)를 첫 인증 호출이 기다릴지 판단하는 데 쓴다:
|
|
2822
|
-
// - 힌트 있음 → 기존과 동일하게 대기 (로그인 세션의 첫 호출이 익명으로 나가는 것 방지).
|
|
2823
|
-
// - 힌트 없음 → 대기 생략. 익명 방문자(공개 사이트 첫 방문 대부분)의 첫 조회가
|
|
2824
|
-
// re-issue 왕복만큼 빨라진다. 복구 자체는 백그라운드로 계속 진행되므로, 드물게
|
|
2825
|
-
// 힌트가 지워졌지만 cookie 세션이 살아있는 경우도 이후 호출부터 자동 회복된다.
|
|
2826
|
-
//
|
|
2827
|
-
// 세션을 만드는 모든 흐름(로그인/OAuth 콜백/토큰 refresh)이 setTokens 를 경유하므로
|
|
2828
|
-
// 그곳에서 마킹하고, clearTokens(로그아웃)에서 지운다.
|
|
2829
|
-
buildSessionHintKey() {
|
|
2830
|
-
return `${this.buildStorageKey()}:has_session`;
|
|
2831
|
-
}
|
|
2832
|
-
markSessionHint() {
|
|
2833
|
-
if (typeof window === "undefined") return;
|
|
2834
|
-
try {
|
|
2835
|
-
localStorage.setItem(this.buildSessionHintKey(), "1");
|
|
2836
|
-
} catch {
|
|
2619
|
+
async tryRestoreSessionFromCookie() {
|
|
2620
|
+
if (typeof window === "undefined") return false;
|
|
2621
|
+
if (this.config.accessToken && !this.isTokenExpired(this.config.accessToken)) {
|
|
2622
|
+
return true;
|
|
2837
2623
|
}
|
|
2838
|
-
}
|
|
2839
|
-
clearSessionHint() {
|
|
2840
|
-
if (typeof window === "undefined") return;
|
|
2841
2624
|
try {
|
|
2842
|
-
|
|
2625
|
+
const newAccessToken = await this.refreshAccessToken();
|
|
2626
|
+
return !!newAccessToken;
|
|
2843
2627
|
} catch {
|
|
2628
|
+
return false;
|
|
2844
2629
|
}
|
|
2845
2630
|
}
|
|
2846
|
-
|
|
2847
|
-
if (typeof window === "undefined") return false;
|
|
2631
|
+
emitError(error) {
|
|
2848
2632
|
try {
|
|
2849
|
-
|
|
2633
|
+
this.config.onError?.(error);
|
|
2850
2634
|
} catch {
|
|
2851
|
-
return true;
|
|
2852
2635
|
}
|
|
2853
2636
|
}
|
|
2854
|
-
|
|
2855
|
-
|
|
2856
|
-
// `refreshLockedUntil` 백오프는 인스턴스 안에서만 산다. 앱이 클라이언트를 새로 만들 때마다
|
|
2857
|
-
// 초기화되므로, 쿠키가 없는 브라우저에서는 인증 호출마다 re-issue 401 이 새로 나간다.
|
|
2858
|
-
// 이 마커는 같은 사실을 localStorage 에 짧게 남겨 인스턴스 경계를 넘어 공유한다.
|
|
2859
|
-
buildNoCookieSessionKey() {
|
|
2860
|
-
return `${this.storageKey}:no_cookie_session`;
|
|
2637
|
+
isTokenExpired(token) {
|
|
2638
|
+
return tokenExpiresWithin(token, 300);
|
|
2861
2639
|
}
|
|
2862
|
-
|
|
2863
|
-
|
|
2864
|
-
|
|
2865
|
-
|
|
2866
|
-
|
|
2640
|
+
/**
|
|
2641
|
+
* 실시간 연결(`cb.realtime`, `cb.database` 실시간)이 연결 위에서 token 을 갱신할 수 있는지 — token 이 이 클라이언트가 들고
|
|
2642
|
+
* 있는 멤버 세션(같은 앱, 같은 멤버)의 것이고, 세션을 refresh 할 수단(메모리의 refresh token, 또는 브라우저의 HttpOnly
|
|
2643
|
+
* 쿠키)이 있을 때만이다. 앱이 다른 곳에서 받은 토큰(다른 멤버, 함수의 위임 토큰, OAuth 토큰)이면 false.
|
|
2644
|
+
*/
|
|
2645
|
+
canRefreshMemberToken(token) {
|
|
2646
|
+
const current = this.config.accessToken;
|
|
2647
|
+
if (!token || !current || !isSameMemberToken(token, current)) {
|
|
2648
|
+
return false;
|
|
2867
2649
|
}
|
|
2650
|
+
return !!this.config.refreshToken || typeof window !== "undefined";
|
|
2868
2651
|
}
|
|
2869
|
-
|
|
2870
|
-
|
|
2652
|
+
/**
|
|
2653
|
+
* token 과 같은 멤버 세션의 access token 을 minValiditySec 초 이상 남은 것으로 돌려준다. 지금 세션 토큰이 그만큼 남았으면
|
|
2654
|
+
* 그대로, 아니면 HTTP 요청과 같은 refresh(같은 single-flight, 같은 실패 처리 — 세션이 끝났으면 onTokenExpired)를 한다.
|
|
2655
|
+
* 세션이 다르거나 갱신에 실패하면 undefined.
|
|
2656
|
+
*
|
|
2657
|
+
* `replace` 는 token 이 곧 만료된다고 서버가 알렸을 때 쓴다 — 세션 토큰이 token 과 같으면 이쪽 시계로는 아직 남았어도
|
|
2658
|
+
* 갱신한다(기기 시계가 늦으면 서버 기준 만료를 놓친다).
|
|
2659
|
+
*/
|
|
2660
|
+
async freshTokenForMember(token, minValiditySec, options) {
|
|
2661
|
+
if (!this.canRefreshMemberToken(token)) return void 0;
|
|
2662
|
+
const current = this.config.accessToken;
|
|
2663
|
+
const mustReplace = options?.replace === true && current === token;
|
|
2664
|
+
if (current && !mustReplace && !tokenExpiresWithin(current, minValiditySec)) {
|
|
2665
|
+
return current;
|
|
2666
|
+
}
|
|
2871
2667
|
try {
|
|
2872
|
-
|
|
2668
|
+
const next = await this.refreshAccessToken();
|
|
2669
|
+
return next && isSameMemberToken(next, token) ? next : void 0;
|
|
2873
2670
|
} catch {
|
|
2671
|
+
return void 0;
|
|
2874
2672
|
}
|
|
2875
2673
|
}
|
|
2876
|
-
|
|
2877
|
-
|
|
2878
|
-
|
|
2879
|
-
|
|
2880
|
-
|
|
2881
|
-
|
|
2882
|
-
|
|
2883
|
-
|
|
2674
|
+
async prepareHeaders(config) {
|
|
2675
|
+
const headers = new Headers();
|
|
2676
|
+
headers.set("Content-Type", "application/json");
|
|
2677
|
+
const credential = this.getCredential();
|
|
2678
|
+
if (credential) {
|
|
2679
|
+
headers.set("X-Public-Key", credential);
|
|
2680
|
+
}
|
|
2681
|
+
if (!config?.skipAuth && !this.config.accessToken && this.config.publicKey && typeof window !== "undefined" && this.bootRestorePromise && (this.bootRestoreAlwaysAwait || this.hasSessionHint())) {
|
|
2682
|
+
try {
|
|
2683
|
+
await this.bootRestorePromise;
|
|
2684
|
+
} catch {
|
|
2685
|
+
}
|
|
2686
|
+
}
|
|
2687
|
+
if (!config?.skipAuth && this.config.accessToken) {
|
|
2688
|
+
let token = this.config.accessToken;
|
|
2689
|
+
if (this.isTokenExpired(token) && this.config.refreshToken) {
|
|
2690
|
+
const newToken = await this.refreshAccessToken();
|
|
2691
|
+
if (newToken) {
|
|
2692
|
+
token = newToken;
|
|
2693
|
+
}
|
|
2694
|
+
}
|
|
2695
|
+
if (!isConsolePlatformToken(token)) {
|
|
2696
|
+
headers.set("Authorization", `Bearer ${token}`);
|
|
2697
|
+
}
|
|
2698
|
+
} else if (!config?.skipAuth && this.config.publicKey && this.config.secretKey && !headers.has("Authorization")) {
|
|
2699
|
+
headers.set("Authorization", `Bearer ${this.config.secretKey}`);
|
|
2700
|
+
}
|
|
2701
|
+
if (!config?.skipAuth && this.config.secretKey) {
|
|
2702
|
+
headers.set("X-User-Secret-Key", this.config.secretKey);
|
|
2703
|
+
}
|
|
2704
|
+
if (config?.headers) {
|
|
2705
|
+
Object.entries(config.headers).forEach(([key, value]) => {
|
|
2706
|
+
headers.set(key, value);
|
|
2707
|
+
});
|
|
2708
|
+
}
|
|
2709
|
+
return headers;
|
|
2884
2710
|
}
|
|
2885
2711
|
/**
|
|
2886
|
-
*
|
|
2887
|
-
*
|
|
2712
|
+
* 실패 응답(`!response.ok`)을 ApiError 로 변환한다. 던지지도, emitError 하지도 않는다.
|
|
2713
|
+
*
|
|
2714
|
+
* handleResponse 와 **같은 파싱을 두 곳이 필요로 해서** 뽑아냈다 — `ai.chat` 이 스트리밍
|
|
2715
|
+
* 전송으로 옮겨가면서 SSE 응답의 HTTP 레벨 실패도 기존 비스트리밍과 **완전히 같은
|
|
2716
|
+
* ApiError** 로 보여야 하기 때문이다. 파싱을 복제하면 그 순간부터 두 경로의 에러 모양이
|
|
2717
|
+
* 갈린다 (실제로 코드 유실 사고가 있었다 — platform-issue 019fa21c).
|
|
2888
2718
|
*/
|
|
2889
|
-
async
|
|
2890
|
-
|
|
2891
|
-
|
|
2892
|
-
|
|
2893
|
-
|
|
2894
|
-
|
|
2719
|
+
async buildApiError(response) {
|
|
2720
|
+
let errorData = {};
|
|
2721
|
+
let bodyIsJson = true;
|
|
2722
|
+
try {
|
|
2723
|
+
errorData = await response.json();
|
|
2724
|
+
} catch {
|
|
2725
|
+
bodyIsJson = false;
|
|
2726
|
+
}
|
|
2727
|
+
const retryAfterHeader = response.status === 429 ? response.headers.get("Retry-After") : null;
|
|
2728
|
+
let retryAfterSeconds;
|
|
2729
|
+
if (retryAfterHeader) {
|
|
2730
|
+
const asInt = Number.parseInt(retryAfterHeader, 10);
|
|
2731
|
+
if (Number.isFinite(asInt) && asInt >= 0) {
|
|
2732
|
+
retryAfterSeconds = asInt;
|
|
2733
|
+
} else {
|
|
2734
|
+
const dateMs = Date.parse(retryAfterHeader);
|
|
2735
|
+
if (Number.isFinite(dateMs)) {
|
|
2736
|
+
retryAfterSeconds = Math.max(
|
|
2737
|
+
0,
|
|
2738
|
+
Math.round((dateMs - Date.now()) / 1e3)
|
|
2739
|
+
);
|
|
2740
|
+
}
|
|
2741
|
+
}
|
|
2742
|
+
}
|
|
2743
|
+
const rawError = errorData.error;
|
|
2744
|
+
if (rawError && typeof rawError === "object" && "message" in rawError) {
|
|
2745
|
+
const structured = rawError;
|
|
2746
|
+
const details = {
|
|
2747
|
+
...structured.details && typeof structured.details === "object" ? structured.details : {}
|
|
2748
|
+
};
|
|
2749
|
+
if (retryAfterSeconds !== void 0) {
|
|
2750
|
+
details.retry_after_seconds = retryAfterSeconds;
|
|
2751
|
+
}
|
|
2752
|
+
const err2 = new ApiError(
|
|
2753
|
+
response.status,
|
|
2754
|
+
typeof structured.message === "string" && structured.message !== "" ? structured.message : "Unknown error",
|
|
2755
|
+
typeof structured.code === "string" ? structured.code : void 0,
|
|
2756
|
+
Object.keys(details).length > 0 ? details : void 0
|
|
2757
|
+
);
|
|
2758
|
+
return err2;
|
|
2759
|
+
}
|
|
2760
|
+
const flatMessage = typeof errorData.message === "string" && errorData.message !== "" ? errorData.message : void 0;
|
|
2761
|
+
const explicitCode = typeof errorData.code === "string" && errorData.code !== "" ? errorData.code : void 0;
|
|
2762
|
+
const errorIsCode = typeof rawError === "string" && /^[a-z][a-z0-9_]*$/.test(rawError);
|
|
2763
|
+
const message = flatMessage ?? (typeof rawError === "string" && rawError !== "" ? rawError : void 0) ?? (bodyIsJson ? void 0 : gatewayMessageFromStatus(response.status)) ?? (response.statusText !== "" ? response.statusText : "Unknown error");
|
|
2764
|
+
const code = explicitCode ?? (errorIsCode ? rawError : void 0) ?? gatewayCodeFromStatus(response.status);
|
|
2765
|
+
const legacyDetails = {};
|
|
2766
|
+
if (retryAfterSeconds !== void 0) {
|
|
2767
|
+
legacyDetails.retry_after_seconds = retryAfterSeconds;
|
|
2768
|
+
}
|
|
2769
|
+
if (typeof errorData.provider === "string") {
|
|
2770
|
+
legacyDetails.provider = errorData.provider;
|
|
2771
|
+
}
|
|
2772
|
+
if (typeof errorData.model === "string") {
|
|
2773
|
+
legacyDetails.model = errorData.model;
|
|
2774
|
+
}
|
|
2775
|
+
const err = new ApiError(
|
|
2776
|
+
response.status,
|
|
2777
|
+
message,
|
|
2778
|
+
code,
|
|
2779
|
+
Object.keys(legacyDetails).length > 0 ? legacyDetails : void 0
|
|
2895
2780
|
);
|
|
2896
|
-
this.emitError(err);
|
|
2897
2781
|
return err;
|
|
2898
2782
|
}
|
|
2899
|
-
|
|
2900
|
-
if (
|
|
2901
|
-
|
|
2902
|
-
|
|
2903
|
-
|
|
2904
|
-
|
|
2905
|
-
|
|
2906
|
-
|
|
2907
|
-
this.clearNoCookieSessionMark();
|
|
2908
|
-
return false;
|
|
2909
|
-
}
|
|
2910
|
-
return true;
|
|
2911
|
-
} catch {
|
|
2912
|
-
return false;
|
|
2783
|
+
async handleResponse(response) {
|
|
2784
|
+
if (!response.ok) {
|
|
2785
|
+
const err = await this.buildApiError(response);
|
|
2786
|
+
this.emitError(err);
|
|
2787
|
+
throw err;
|
|
2788
|
+
}
|
|
2789
|
+
if (response.status === 204 || response.headers.get("content-length") === "0") {
|
|
2790
|
+
return {};
|
|
2913
2791
|
}
|
|
2792
|
+
return response.json();
|
|
2914
2793
|
}
|
|
2915
2794
|
/**
|
|
2916
|
-
*
|
|
2917
|
-
*
|
|
2918
|
-
* 배경: 콜백 흐름에서 서버가 redirect 응답에 Set-Cookie 를 함께 발급하지만, 일부 deployment /
|
|
2919
|
-
* 브라우저 정책 / 사용자 설정 (3rd-party cookie 차단 등) 환경에서 이 Set-Cookie 가 브라우저에
|
|
2920
|
-
* 저장되지 않는다. `persistence='none'` 모드에서는 토큰이 메모리에만 있고 cookie 가 없는 상태로
|
|
2921
|
-
* 페이지 새로고침이 발생하면 `/v1/auth/re-issue` 가 401 으로 떨어져 강제 로그아웃되는 회귀가
|
|
2922
|
-
* 있다 (platform-issue 019e3960, 2026-05-18).
|
|
2923
|
-
*
|
|
2924
|
-
* 이 메서드는 메모리의 refresh token 으로 한 번 `/v1/auth/re-issue` 를 호출해 서버가 cookie 를
|
|
2925
|
-
* 명시적으로 발급하도록 유도한다. 백엔드는 Bearer + `X-Public-Key` 조합을 SDK 호출 신호로
|
|
2926
|
-
* 인식해 응답에 `cb_member_refresh_token` cookie 를 함께 내려준다.
|
|
2795
|
+
* AbortController 를 관리하며 fetch 호출을 실행. 타임아웃/외부 signal 병합.
|
|
2927
2796
|
*
|
|
2928
|
-
*
|
|
2929
|
-
*
|
|
2930
|
-
*
|
|
2797
|
+
* 401 자동 복구: 인증 호출이 401 을 받으면 cookie 기반 복구를 *한 번* 시도하고 retry 한다.
|
|
2798
|
+
* 메모리 토큰이 만료/누락 + cookie 는 살아 있는 경우를 자동으로 회복시켜,
|
|
2799
|
+
* 페이지 진입 직후 race 로 401 을 받은 첫 호출이 사용자 흐름을 차단하지 않게 한다
|
|
2800
|
+
* (platform-issue 019e638d, 2026-05-26). retry 는 1회 한정 — 무한 루프 차단.
|
|
2931
2801
|
*/
|
|
2932
|
-
async
|
|
2933
|
-
|
|
2934
|
-
|
|
2935
|
-
if (!this.config.refreshToken) return;
|
|
2802
|
+
async doFetch(url, init, config) {
|
|
2803
|
+
const startedAt = Date.now();
|
|
2804
|
+
let status = 0;
|
|
2936
2805
|
try {
|
|
2937
|
-
await this.
|
|
2938
|
-
|
|
2806
|
+
const first = await this.tryFetchOnce(url, init, config);
|
|
2807
|
+
status = first.status;
|
|
2808
|
+
if (!first.ok && first.status === 401 && !config?.skipAuth && this.config.publicKey && typeof window !== "undefined") {
|
|
2809
|
+
const recovered = await this.tryRestoreSessionFromCookie();
|
|
2810
|
+
if (recovered) {
|
|
2811
|
+
const retryHeaders = await this.prepareHeaders(config);
|
|
2812
|
+
if (init.body instanceof FormData) {
|
|
2813
|
+
retryHeaders.delete("Content-Type");
|
|
2814
|
+
}
|
|
2815
|
+
const second = await this.tryFetchOnce(
|
|
2816
|
+
url,
|
|
2817
|
+
{ ...init, headers: retryHeaders },
|
|
2818
|
+
config
|
|
2819
|
+
);
|
|
2820
|
+
status = second.status;
|
|
2821
|
+
return await this.handleResponse(second.response);
|
|
2822
|
+
}
|
|
2823
|
+
}
|
|
2824
|
+
return await this.handleResponse(first.response);
|
|
2825
|
+
} finally {
|
|
2826
|
+
this.recentCalls.push({
|
|
2827
|
+
method: (init.method || "GET").toUpperCase(),
|
|
2828
|
+
path: sanitizePathForBreadcrumb(url),
|
|
2829
|
+
status,
|
|
2830
|
+
duration_ms: Date.now() - startedAt,
|
|
2831
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
2832
|
+
});
|
|
2939
2833
|
}
|
|
2940
2834
|
}
|
|
2941
|
-
// ===== Token Persistence =====
|
|
2942
|
-
get persistence() {
|
|
2943
|
-
return this.config.persistence ?? "none";
|
|
2944
|
-
}
|
|
2945
|
-
getStorage() {
|
|
2946
|
-
if (typeof window === "undefined") return null;
|
|
2947
|
-
if (this.persistence === "localStorage" && typeof localStorage !== "undefined")
|
|
2948
|
-
return localStorage;
|
|
2949
|
-
if (this.persistence === "sessionStorage" && typeof sessionStorage !== "undefined")
|
|
2950
|
-
return sessionStorage;
|
|
2951
|
-
return null;
|
|
2952
|
-
}
|
|
2953
2835
|
/**
|
|
2954
|
-
*
|
|
2955
|
-
*
|
|
2836
|
+
* 이 요청을 보낼 원본을 고른다.
|
|
2837
|
+
*
|
|
2838
|
+
* `credentials:'omit'` 인 요청 — 즉 `X-Public-Key` 로만 인증하고 쿠키를 주고받지 않는
|
|
2839
|
+
* `/v1/public/*` 데이터 평면 — 만 direct 원본으로 보낸다. 이 조건이 곧 안전 조건이다:
|
|
2840
|
+
* 멤버 refresh 쿠키는 **host-only** 로 발급되므로(백엔드 auth_cookie.SetMemberRefreshCookie)
|
|
2841
|
+
* 로그인·가입·로그아웃·OAuth·탈퇴를 다른 호스트로 보내면 세션이 조용히 끊긴다.
|
|
2842
|
+
* `fetchCredentialsForPath` 가 이미 그 경계를 계산하고 있어, 나중에 쿠키 엔드포인트가
|
|
2843
|
+
* 추가돼도 자동으로 제외된다(서버도 같은 경로를 421 로 되돌려보낸다).
|
|
2956
2844
|
*/
|
|
2957
|
-
|
|
2958
|
-
|
|
2959
|
-
|
|
2960
|
-
buildStorageKey() {
|
|
2961
|
-
const credential = this.config.publicKey ?? this.config.secretKey;
|
|
2962
|
-
if (!credential) return TOKEN_STORAGE_KEY;
|
|
2963
|
-
let hash = 0;
|
|
2964
|
-
for (let i = 0; i < credential.length; i++) {
|
|
2965
|
-
hash = (hash << 5) - hash + credential.charCodeAt(i);
|
|
2966
|
-
hash = hash & hash;
|
|
2845
|
+
resolveOrigin(url, overrideBaseUrl) {
|
|
2846
|
+
if (overrideBaseUrl) {
|
|
2847
|
+
return overrideBaseUrl;
|
|
2967
2848
|
}
|
|
2968
|
-
|
|
2969
|
-
|
|
2970
|
-
persistTokens() {
|
|
2971
|
-
if (this.persistence === "none") return;
|
|
2972
|
-
const storage = this.getStorage();
|
|
2973
|
-
if (!storage || !this.config.accessToken || !this.config.refreshToken)
|
|
2974
|
-
return;
|
|
2975
|
-
storage.setItem(
|
|
2976
|
-
this.storageKey,
|
|
2977
|
-
JSON.stringify({
|
|
2978
|
-
accessToken: this.config.accessToken,
|
|
2979
|
-
refreshToken: this.config.refreshToken
|
|
2980
|
-
})
|
|
2981
|
-
);
|
|
2982
|
-
}
|
|
2983
|
-
restoreTokens() {
|
|
2984
|
-
if (this.persistence === "none") return;
|
|
2985
|
-
if (this.config.accessToken && this.config.refreshToken) return;
|
|
2986
|
-
const storage = this.getStorage();
|
|
2987
|
-
if (!storage) return;
|
|
2988
|
-
const stored = storage.getItem(this.storageKey);
|
|
2989
|
-
if (!stored) return;
|
|
2990
|
-
try {
|
|
2991
|
-
const { accessToken, refreshToken } = JSON.parse(stored);
|
|
2992
|
-
if (accessToken && refreshToken) {
|
|
2993
|
-
this.config.accessToken = accessToken;
|
|
2994
|
-
this.config.refreshToken = refreshToken;
|
|
2995
|
-
}
|
|
2996
|
-
} catch {
|
|
2997
|
-
storage.removeItem(this.storageKey);
|
|
2849
|
+
if (this.directBaseUrl && !this.directDisabled && fetchCredentialsForPath(url) === "omit") {
|
|
2850
|
+
return this.directBaseUrl;
|
|
2998
2851
|
}
|
|
2999
|
-
|
|
3000
|
-
removePersistedTokens() {
|
|
3001
|
-
if (this.persistence === "none") return;
|
|
3002
|
-
const storage = this.getStorage();
|
|
3003
|
-
if (!storage) return;
|
|
3004
|
-
storage.removeItem(this.storageKey);
|
|
3005
|
-
}
|
|
3006
|
-
/**
|
|
3007
|
-
* Public Key 가 설정되어 있는지 확인
|
|
3008
|
-
*/
|
|
3009
|
-
hasPublicKey() {
|
|
3010
|
-
return !!this.config.publicKey;
|
|
3011
|
-
}
|
|
3012
|
-
/**
|
|
3013
|
-
* Public Key 반환
|
|
3014
|
-
*/
|
|
3015
|
-
getPublicKey() {
|
|
3016
|
-
return this.config.publicKey;
|
|
3017
|
-
}
|
|
3018
|
-
/**
|
|
3019
|
-
* Secret Key 가 설정되어 있는지 확인
|
|
3020
|
-
*/
|
|
3021
|
-
hasSecretKey() {
|
|
3022
|
-
return !!this.config.secretKey;
|
|
3023
|
-
}
|
|
3024
|
-
/**
|
|
3025
|
-
* Secret Key 반환
|
|
3026
|
-
*/
|
|
3027
|
-
getSecretKey() {
|
|
3028
|
-
return this.config.secretKey;
|
|
2852
|
+
return this.config.baseUrl;
|
|
3029
2853
|
}
|
|
3030
2854
|
/**
|
|
3031
|
-
*
|
|
2855
|
+
* 응답에서 저지연 원본 광고를 학습한다.
|
|
3032
2856
|
*
|
|
3033
|
-
*
|
|
3034
|
-
*
|
|
3035
|
-
*
|
|
2857
|
+
* 왜 서버가 정하나: 클라이언트는 자기가 어느 나라에서 접속했는지 신뢰성 있게 모르고,
|
|
2858
|
+
* 두 호스트를 재보는 프로브는 요청을 한 번 더 쓴다. Cloudflare 엣지는 `CF-IPCountry` 로
|
|
2859
|
+
* 이미 알고 있으므로 서버가 판단해 알려주는 쪽이 정확하고 공짜다. 서버 env 하나로
|
|
2860
|
+
* 즉시 회수할 수도 있다.
|
|
3036
2861
|
*
|
|
3037
|
-
*
|
|
3038
|
-
*
|
|
3039
|
-
|
|
3040
|
-
getCredential() {
|
|
3041
|
-
return this.config.publicKey ?? this.config.secretKey;
|
|
3042
|
-
}
|
|
3043
|
-
/**
|
|
3044
|
-
* Access Token 반환
|
|
3045
|
-
*/
|
|
3046
|
-
getAccessToken() {
|
|
3047
|
-
return this.config.accessToken;
|
|
3048
|
-
}
|
|
3049
|
-
/**
|
|
3050
|
-
* JWT(Access Token) 가 설정되어 있는지 확인
|
|
3051
|
-
*/
|
|
3052
|
-
hasJWT() {
|
|
3053
|
-
return !!this.config.accessToken;
|
|
3054
|
-
}
|
|
3055
|
-
/**
|
|
3056
|
-
* Base URL 반환
|
|
2862
|
+
* 값은 검증한다 — https 이고 `baseUrl` 과 같은 등록 도메인이어야 한다. 응답은 우리
|
|
2863
|
+
* 서버에서 TLS 로 오지만, 설정 실수 하나로 SDK 트래픽 전체가 엉뚱한 호스트로 향하는
|
|
2864
|
+
* 일은 없어야 한다.
|
|
3057
2865
|
*/
|
|
3058
|
-
|
|
3059
|
-
|
|
2866
|
+
learnDirectOrigin(response) {
|
|
2867
|
+
if (!response.headers) return;
|
|
2868
|
+
this.adoptDirectBases(
|
|
2869
|
+
response.headers.get("X-CB-Direct-Base"),
|
|
2870
|
+
response.headers.get("X-CB-Realtime-Direct-Base")
|
|
2871
|
+
);
|
|
3060
2872
|
}
|
|
3061
2873
|
/**
|
|
3062
|
-
*
|
|
3063
|
-
*
|
|
3064
|
-
* 호출자(`RealtimeAPI`)는 이 경우 원래 소켓 URL로 폴백해야 한다.
|
|
2874
|
+
* 광고된 direct 원본을 검증해 받아들인다. 응답 헤더(learnDirectOrigin)와 edge-hints 본문
|
|
2875
|
+
* (primeEdgeHints)이 같은 검증을 거친다.
|
|
3065
2876
|
*/
|
|
3066
|
-
|
|
3067
|
-
|
|
2877
|
+
adoptDirectBases(advertised, advertisedRealtime) {
|
|
2878
|
+
const tail = (h) => h.split(".").slice(-2).join(".");
|
|
2879
|
+
let base = null;
|
|
2880
|
+
try {
|
|
2881
|
+
base = new URL(this.config.baseUrl);
|
|
2882
|
+
} catch {
|
|
2883
|
+
}
|
|
2884
|
+
if (base && !this.directDisabled && !this.directBaseUrl && typeof advertised === "string" && advertised) {
|
|
2885
|
+
try {
|
|
2886
|
+
const next = new URL(advertised);
|
|
2887
|
+
if (next.protocol === "https:" && tail(next.hostname) === tail(base.hostname)) {
|
|
2888
|
+
this.directBaseUrl = next.origin;
|
|
2889
|
+
}
|
|
2890
|
+
} catch {
|
|
2891
|
+
}
|
|
2892
|
+
}
|
|
2893
|
+
if (!this.directRealtimeDisabled && !this.directRealtimeBaseUrl && typeof advertisedRealtime === "string" && advertisedRealtime) {
|
|
2894
|
+
const expectedTail = base ? tail(base.hostname) : "connectbase.world";
|
|
2895
|
+
try {
|
|
2896
|
+
const next = new URL(advertisedRealtime);
|
|
2897
|
+
if (next.protocol === "wss:" && tail(next.hostname) === expectedTail) {
|
|
2898
|
+
this.directRealtimeBaseUrl = next.origin;
|
|
2899
|
+
}
|
|
2900
|
+
} catch {
|
|
2901
|
+
}
|
|
2902
|
+
}
|
|
3068
2903
|
}
|
|
3069
2904
|
/**
|
|
3070
|
-
*
|
|
3071
|
-
*
|
|
3072
|
-
*
|
|
2905
|
+
* realtime 첫 연결 전에 저지연 direct 원본 힌트를 묻는다 (`GET /v1/public/edge-hints`, 6.6.0+).
|
|
2906
|
+
*
|
|
2907
|
+
* **커스텀 헤더 없는 단순 GET** 이다. `X-Public-Key` 같은 헤더가 붙으면 브라우저가 CORS 사전 요청을
|
|
2908
|
+
* 먼저 보내 Cloudflare 를 두 번 왕복하고, 앱의 "로컬 개발 origin 허용" 이 꺼진 localhost 페이지에서는
|
|
2909
|
+
* 키 기반 opt-in 에 막혀 브라우저만 direct 를 못 썼다(Node 는 썼다 — platform-issue 01a15e24).
|
|
2910
|
+
* 서버는 이 경로를 키 없이 열어 두고 같은 값을 본문으로도 준다. 본문을 읽으므로 CORS
|
|
2911
|
+
* Expose-Headers 에도 기대지 않는다. 실패는 호출자에게 던지고 호출자(RealtimeAPI)가 조용히 넘어간다 —
|
|
2912
|
+
* direct 는 최적화일 뿐이다.
|
|
2913
|
+
*
|
|
2914
|
+
* 조회 자체는 같은 baseUrl 의 인스턴스끼리 함께 쓴다(6.7.0+, {@link sharedEdgeHints} 참고). 진행 중인
|
|
2915
|
+
* 조회가 있으면 새로 보내지 않고 기다리며, 성공한 결과는 잠시 다시 쓴다. 받아들일지는 이 인스턴스가 정한다 —
|
|
2916
|
+
* 이미 배웠거나(`directRealtimeBaseUrl`) direct 를 포기했으면(`directRealtimeDisabled`) 바꾸지 않는다.
|
|
3073
2917
|
*/
|
|
3074
|
-
|
|
3075
|
-
this.directRealtimeDisabled
|
|
2918
|
+
async primeEdgeHints(timeoutMs) {
|
|
2919
|
+
if (this.directRealtimeBaseUrl || this.directRealtimeDisabled) return;
|
|
2920
|
+
const adverts = await lookupEdgeHints(this.config.baseUrl, timeoutMs);
|
|
2921
|
+
for (const advert of adverts) {
|
|
2922
|
+
this.adoptDirectBases(advert.direct, advert.realtime);
|
|
2923
|
+
}
|
|
3076
2924
|
}
|
|
3077
2925
|
/**
|
|
3078
|
-
*
|
|
2926
|
+
* SDK 인증 헤더를 **주입하지 않는** raw fetch. 저지연 원본 선택과 폴백만 얹는다.
|
|
3079
2927
|
*
|
|
3080
|
-
*
|
|
3081
|
-
*
|
|
2928
|
+
* `cb.endpoint.call()`(`/v1/proxy/*`) 전용이다. 그 경로는 dumb pipe 라 요청 헤더가
|
|
2929
|
+
* 사용자 PC 의 모델 서버로 그대로 전달된다 — `prepareHeaders()` 를 태우면 SDK 의
|
|
2930
|
+
* `Authorization` 이 남의 서버로 나가고, 호출자가 자기 모델 서버용으로 설정한
|
|
2931
|
+
* `Authorization` 을 덮어쓴다. 그래서 fetchRaw 를 재사용하지 않는다.
|
|
2932
|
+
*
|
|
2933
|
+
* @param path `/v1/proxy/...` 형태의 절대 경로 (origin 없이)
|
|
3082
2934
|
*/
|
|
3083
|
-
|
|
3084
|
-
|
|
3085
|
-
|
|
3086
|
-
|
|
3087
|
-
|
|
3088
|
-
|
|
3089
|
-
|
|
3090
|
-
|
|
3091
|
-
|
|
3092
|
-
|
|
3093
|
-
|
|
3094
|
-
|
|
3095
|
-
);
|
|
3096
|
-
this.emitError(error);
|
|
3097
|
-
this.config.onAuthError?.(error);
|
|
3098
|
-
throw error;
|
|
3099
|
-
}
|
|
3100
|
-
if (!this.config.refreshToken && this.isNoCookieSessionMarkFresh()) {
|
|
3101
|
-
throw new AuthError(
|
|
3102
|
-
"No cookie session (recently rejected). Skipping token refresh."
|
|
3103
|
-
);
|
|
2935
|
+
async fetchPassthrough(path, init) {
|
|
2936
|
+
const origin = this.resolveOrigin(path);
|
|
2937
|
+
try {
|
|
2938
|
+
const response = await fetch(`${origin}${path}`, init);
|
|
2939
|
+
this.learnDirectOrigin(response);
|
|
2940
|
+
return response;
|
|
2941
|
+
} catch (err) {
|
|
2942
|
+
if (origin !== this.config.baseUrl && !isAbortError(err)) {
|
|
2943
|
+
this.directDisabled = true;
|
|
2944
|
+
return fetch(`${this.config.baseUrl}${path}`, init);
|
|
2945
|
+
}
|
|
2946
|
+
throw err;
|
|
3104
2947
|
}
|
|
3105
|
-
|
|
3106
|
-
|
|
3107
|
-
|
|
3108
|
-
this.config.
|
|
3109
|
-
|
|
3110
|
-
|
|
2948
|
+
}
|
|
2949
|
+
async tryFetchOnce(url, init, config) {
|
|
2950
|
+
const { signal, cleanup } = createTimeoutController({
|
|
2951
|
+
timeout: config?.timeout ?? this.config.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
|
|
2952
|
+
signal: config?.signal
|
|
2953
|
+
});
|
|
2954
|
+
const origin = this.resolveOrigin(url, config?.baseUrl);
|
|
2955
|
+
try {
|
|
2956
|
+
const response = await withAbort(
|
|
2957
|
+
fetch(`${origin}${url}`, {
|
|
2958
|
+
...init,
|
|
2959
|
+
credentials: fetchCredentialsForPath(url),
|
|
2960
|
+
signal
|
|
2961
|
+
}),
|
|
2962
|
+
signal
|
|
3111
2963
|
);
|
|
3112
|
-
|
|
3113
|
-
|
|
3114
|
-
|
|
3115
|
-
|
|
3116
|
-
|
|
3117
|
-
|
|
3118
|
-
|
|
3119
|
-
});
|
|
3120
|
-
let failureKind = "transient";
|
|
3121
|
-
try {
|
|
3122
|
-
const headers = {
|
|
3123
|
-
"Content-Type": "application/json"
|
|
3124
|
-
};
|
|
3125
|
-
if (this.config.refreshToken) {
|
|
3126
|
-
headers.Authorization = `Bearer ${this.config.refreshToken}`;
|
|
3127
|
-
}
|
|
3128
|
-
const credential = this.getCredential();
|
|
3129
|
-
if (credential) {
|
|
3130
|
-
headers["X-Public-Key"] = credential;
|
|
3131
|
-
}
|
|
3132
|
-
const cookieOnly = !this.config.refreshToken;
|
|
2964
|
+
if (!config?.baseUrl) {
|
|
2965
|
+
this.learnDirectOrigin(response);
|
|
2966
|
+
}
|
|
2967
|
+
return { response, ok: response.ok, status: response.status };
|
|
2968
|
+
} catch (err) {
|
|
2969
|
+
if (!config?.baseUrl && origin !== this.config.baseUrl && !isAbortError(err)) {
|
|
2970
|
+
this.directDisabled = true;
|
|
3133
2971
|
const response = await withAbort(
|
|
3134
|
-
fetch(
|
|
3135
|
-
|
|
3136
|
-
|
|
3137
|
-
|
|
3138
|
-
|
|
3139
|
-
credentials: "include",
|
|
3140
|
-
signal
|
|
3141
|
-
}
|
|
3142
|
-
),
|
|
2972
|
+
fetch(`${this.config.baseUrl}${url}`, {
|
|
2973
|
+
...init,
|
|
2974
|
+
credentials: fetchCredentialsForPath(url),
|
|
2975
|
+
signal
|
|
2976
|
+
}),
|
|
3143
2977
|
signal
|
|
3144
2978
|
);
|
|
3145
|
-
|
|
3146
|
-
failureKind = "permanent";
|
|
3147
|
-
throw new Error("Token refresh failed (no session)");
|
|
3148
|
-
}
|
|
3149
|
-
if (!response.ok) {
|
|
3150
|
-
const status = response.status;
|
|
3151
|
-
let oauthError;
|
|
3152
|
-
try {
|
|
3153
|
-
const errBody = await response.clone().json();
|
|
3154
|
-
if (errBody && typeof errBody.error === "string") {
|
|
3155
|
-
oauthError = errBody.error;
|
|
3156
|
-
} else if (errBody && typeof errBody.code === "string") {
|
|
3157
|
-
oauthError = errBody.code;
|
|
3158
|
-
}
|
|
3159
|
-
} catch {
|
|
3160
|
-
}
|
|
3161
|
-
if (status >= 500) {
|
|
3162
|
-
throw new Error(`Token refresh failed (${status})`);
|
|
3163
|
-
}
|
|
3164
|
-
if (status === 401 || status === 403 || status === 400 && (oauthError === "invalid_grant" || oauthError === "invalid_token")) {
|
|
3165
|
-
failureKind = "permanent";
|
|
3166
|
-
} else {
|
|
3167
|
-
failureKind = "client_bug";
|
|
3168
|
-
}
|
|
3169
|
-
throw new Error(
|
|
3170
|
-
`Token refresh failed (${status}${oauthError ? ` ${oauthError}` : ""})`
|
|
3171
|
-
);
|
|
3172
|
-
}
|
|
3173
|
-
const data = await response.json();
|
|
3174
|
-
if (!data || typeof data.access_token !== "string") {
|
|
3175
|
-
throw new Error("Token refresh response missing access_token");
|
|
3176
|
-
}
|
|
3177
|
-
if (isConsolePlatformToken(data.access_token)) {
|
|
3178
|
-
this.refreshFailureCount = 0;
|
|
3179
|
-
this.refreshLockedUntil = 0;
|
|
3180
|
-
return null;
|
|
3181
|
-
}
|
|
3182
|
-
if (this.config.appId) {
|
|
3183
|
-
const tokenAppId = decodeJwtPayload(data.access_token)?.app_id;
|
|
3184
|
-
if (typeof tokenAppId === "string" && tokenAppId !== this.config.appId) {
|
|
3185
|
-
this.clearTokens();
|
|
3186
|
-
this.refreshFailureCount = 0;
|
|
3187
|
-
this.refreshLockedUntil = 0;
|
|
3188
|
-
return null;
|
|
3189
|
-
}
|
|
3190
|
-
}
|
|
3191
|
-
const nextRefreshToken = typeof data.refresh_token === "string" && data.refresh_token.length > 0 ? data.refresh_token : this.config.refreshToken ?? "";
|
|
3192
|
-
if (nextRefreshToken) {
|
|
3193
|
-
this.setTokens(data.access_token, nextRefreshToken);
|
|
3194
|
-
} else {
|
|
3195
|
-
this.config.accessToken = data.access_token;
|
|
3196
|
-
this.persistTokens();
|
|
3197
|
-
}
|
|
3198
|
-
this.config.onTokenRefresh?.({
|
|
3199
|
-
accessToken: data.access_token,
|
|
3200
|
-
refreshToken: nextRefreshToken
|
|
3201
|
-
});
|
|
3202
|
-
this.refreshFailureCount = 0;
|
|
3203
|
-
this.refreshLockedUntil = 0;
|
|
3204
|
-
this.clearNoCookieSessionMark();
|
|
3205
|
-
return data.access_token;
|
|
3206
|
-
} catch (e) {
|
|
3207
|
-
const baseMsg = e instanceof Error ? e.message : "Token refresh failed";
|
|
3208
|
-
this.refreshFailureCount++;
|
|
3209
|
-
const backoffMs = Math.min(
|
|
3210
|
-
500 * 2 ** Math.max(0, this.refreshFailureCount - 1),
|
|
3211
|
-
3e4
|
|
3212
|
-
);
|
|
3213
|
-
this.refreshLockedUntil = Date.now() + backoffMs;
|
|
3214
|
-
if (failureKind === "permanent" && !this.config.refreshToken) {
|
|
3215
|
-
this.markNoCookieSession();
|
|
3216
|
-
}
|
|
3217
|
-
if (failureKind === "permanent") {
|
|
3218
|
-
if (!silent) {
|
|
3219
|
-
this.clearTokens();
|
|
3220
|
-
this.config.onTokenExpired?.();
|
|
3221
|
-
}
|
|
3222
|
-
const error2 = new AuthError(`${baseMsg}. Please login again.`);
|
|
3223
|
-
if (!silent) {
|
|
3224
|
-
this.emitError(error2);
|
|
3225
|
-
this.config.onAuthError?.(error2);
|
|
3226
|
-
}
|
|
3227
|
-
throw error2;
|
|
3228
|
-
}
|
|
3229
|
-
if (failureKind === "client_bug") {
|
|
3230
|
-
const error2 = new AuthError(
|
|
3231
|
-
`${baseMsg}. Client request invalid; tokens preserved.`
|
|
3232
|
-
);
|
|
3233
|
-
if (!silent) {
|
|
3234
|
-
this.emitError(error2);
|
|
3235
|
-
this.config.onAuthError?.(error2);
|
|
3236
|
-
}
|
|
3237
|
-
throw error2;
|
|
3238
|
-
}
|
|
3239
|
-
const error = new AuthError(
|
|
3240
|
-
`${baseMsg}. Transient failure; tokens preserved, will retry after backoff.`
|
|
3241
|
-
);
|
|
3242
|
-
if (!silent) {
|
|
3243
|
-
this.emitError(error);
|
|
3244
|
-
this.config.onTransientRefreshFailure?.(error);
|
|
3245
|
-
this.config.onAuthError?.(error);
|
|
3246
|
-
}
|
|
3247
|
-
throw error;
|
|
3248
|
-
} finally {
|
|
3249
|
-
cleanup();
|
|
3250
|
-
this.isRefreshing = false;
|
|
3251
|
-
this.refreshPromise = null;
|
|
2979
|
+
return { response, ok: response.ok, status: response.status };
|
|
3252
2980
|
}
|
|
3253
|
-
|
|
3254
|
-
|
|
2981
|
+
throw err;
|
|
2982
|
+
} finally {
|
|
2983
|
+
cleanup();
|
|
2984
|
+
}
|
|
2985
|
+
}
|
|
2986
|
+
async get(url, config) {
|
|
2987
|
+
const headers = await this.prepareHeaders(config);
|
|
2988
|
+
return this.doFetch(url, { method: "GET", headers }, config);
|
|
2989
|
+
}
|
|
2990
|
+
async post(url, data, config) {
|
|
2991
|
+
const headers = await this.prepareHeaders(config);
|
|
2992
|
+
if (data instanceof FormData) {
|
|
2993
|
+
headers.delete("Content-Type");
|
|
2994
|
+
}
|
|
2995
|
+
return this.doFetch(
|
|
2996
|
+
url,
|
|
2997
|
+
{
|
|
2998
|
+
method: "POST",
|
|
2999
|
+
headers,
|
|
3000
|
+
body: data instanceof FormData ? data : JSON.stringify(data)
|
|
3001
|
+
},
|
|
3002
|
+
config
|
|
3003
|
+
);
|
|
3004
|
+
}
|
|
3005
|
+
async put(url, data, config) {
|
|
3006
|
+
const headers = await this.prepareHeaders(config);
|
|
3007
|
+
if (data instanceof FormData) {
|
|
3008
|
+
headers.delete("Content-Type");
|
|
3009
|
+
}
|
|
3010
|
+
return this.doFetch(
|
|
3011
|
+
url,
|
|
3012
|
+
{
|
|
3013
|
+
method: "PUT",
|
|
3014
|
+
headers,
|
|
3015
|
+
body: data instanceof FormData ? data : JSON.stringify(data)
|
|
3016
|
+
},
|
|
3017
|
+
config
|
|
3018
|
+
);
|
|
3019
|
+
}
|
|
3020
|
+
async patch(url, data, config) {
|
|
3021
|
+
const headers = await this.prepareHeaders(config);
|
|
3022
|
+
return this.doFetch(
|
|
3023
|
+
url,
|
|
3024
|
+
{
|
|
3025
|
+
method: "PATCH",
|
|
3026
|
+
headers,
|
|
3027
|
+
body: JSON.stringify(data)
|
|
3028
|
+
},
|
|
3029
|
+
config
|
|
3030
|
+
);
|
|
3031
|
+
}
|
|
3032
|
+
async delete(url, config) {
|
|
3033
|
+
const headers = await this.prepareHeaders(config);
|
|
3034
|
+
return this.doFetch(url, { method: "DELETE", headers }, config);
|
|
3255
3035
|
}
|
|
3256
3036
|
/**
|
|
3257
|
-
*
|
|
3258
|
-
*
|
|
3259
|
-
*
|
|
3260
|
-
* - 메모리에 access token 이 이미 있으면 그대로 반환 (true).
|
|
3261
|
-
* - 없으면 `/v1/auth/re-issue` 를 cookie 만으로 호출. cookie 가 있으면 access token 회복.
|
|
3262
|
-
* - cookie 가 없거나(미로그인) 만료된 경우 조용히 false 반환 (콘솔 에러 없음).
|
|
3263
|
-
*
|
|
3264
|
-
* 비-브라우저 환경에서는 cookie 흐름이 없으므로 즉시 false 반환.
|
|
3037
|
+
* Raw fetch 요청 (SSE 스트리밍 등에 사용)
|
|
3038
|
+
* 인증 헤더가 자동으로 추가됩니다. timeout 은 호출자가 직접 signal 로 관리해야 합니다
|
|
3039
|
+
* (스트리밍 특성상 전역 timeout 을 강제하지 않음).
|
|
3265
3040
|
*/
|
|
3266
|
-
async
|
|
3267
|
-
|
|
3268
|
-
|
|
3269
|
-
|
|
3041
|
+
async fetchRaw(url, init) {
|
|
3042
|
+
const headers = await this.prepareHeaders();
|
|
3043
|
+
const mergedHeaders = new Headers(headers);
|
|
3044
|
+
if (init?.headers) {
|
|
3045
|
+
const extra = new Headers(init.headers);
|
|
3046
|
+
extra.forEach((value, key) => mergedHeaders.set(key, value));
|
|
3270
3047
|
}
|
|
3048
|
+
const origin = this.resolveOrigin(url);
|
|
3271
3049
|
try {
|
|
3272
|
-
const
|
|
3273
|
-
|
|
3274
|
-
|
|
3275
|
-
|
|
3050
|
+
const response = await fetch(`${origin}${url}`, {
|
|
3051
|
+
...init,
|
|
3052
|
+
credentials: fetchCredentialsForPath(url),
|
|
3053
|
+
headers: mergedHeaders
|
|
3054
|
+
});
|
|
3055
|
+
this.learnDirectOrigin(response);
|
|
3056
|
+
return response;
|
|
3057
|
+
} catch (err) {
|
|
3058
|
+
if (origin !== this.config.baseUrl && !isAbortError(err)) {
|
|
3059
|
+
this.directDisabled = true;
|
|
3060
|
+
}
|
|
3061
|
+
throw err;
|
|
3276
3062
|
}
|
|
3277
3063
|
}
|
|
3278
|
-
|
|
3279
|
-
|
|
3280
|
-
|
|
3281
|
-
|
|
3064
|
+
};
|
|
3065
|
+
|
|
3066
|
+
// src/core/validate.ts
|
|
3067
|
+
function checkType(value, type) {
|
|
3068
|
+
switch (type) {
|
|
3069
|
+
case "string":
|
|
3070
|
+
return typeof value === "string";
|
|
3071
|
+
case "number":
|
|
3072
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
3073
|
+
case "boolean":
|
|
3074
|
+
return typeof value === "boolean";
|
|
3075
|
+
case "array":
|
|
3076
|
+
return Array.isArray(value);
|
|
3077
|
+
case "object":
|
|
3078
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
3079
|
+
case "string-or-number":
|
|
3080
|
+
return typeof value === "string" || typeof value === "number" && Number.isFinite(value);
|
|
3081
|
+
}
|
|
3082
|
+
}
|
|
3083
|
+
function assertShape(value, shape, endpoint) {
|
|
3084
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
3085
|
+
throw new ApiError(
|
|
3086
|
+
502,
|
|
3087
|
+
`[${endpoint}] expected object, got ${typeof value}`,
|
|
3088
|
+
"SCHEMA_MISMATCH"
|
|
3089
|
+
);
|
|
3090
|
+
}
|
|
3091
|
+
const obj = value;
|
|
3092
|
+
for (const [key, spec] of Object.entries(shape)) {
|
|
3093
|
+
const present = key in obj;
|
|
3094
|
+
if (!present) {
|
|
3095
|
+
if (spec.optional) continue;
|
|
3096
|
+
throw new ApiError(
|
|
3097
|
+
502,
|
|
3098
|
+
`[${endpoint}] missing required field "${key}"`,
|
|
3099
|
+
"SCHEMA_MISMATCH"
|
|
3100
|
+
);
|
|
3101
|
+
}
|
|
3102
|
+
const fieldValue = obj[key];
|
|
3103
|
+
if (spec.optional && (fieldValue === null || fieldValue === void 0)) {
|
|
3104
|
+
continue;
|
|
3105
|
+
}
|
|
3106
|
+
if (!checkType(fieldValue, spec.type)) {
|
|
3107
|
+
throw new ApiError(
|
|
3108
|
+
502,
|
|
3109
|
+
`[${endpoint}] field "${key}" expected ${spec.type}, got ${typeof fieldValue}`,
|
|
3110
|
+
"SCHEMA_MISMATCH"
|
|
3111
|
+
);
|
|
3282
3112
|
}
|
|
3283
3113
|
}
|
|
3284
|
-
|
|
3285
|
-
|
|
3114
|
+
return value;
|
|
3115
|
+
}
|
|
3116
|
+
|
|
3117
|
+
// src/api/auth.ts
|
|
3118
|
+
var AuthAPI = class {
|
|
3119
|
+
constructor(http) {
|
|
3120
|
+
this.http = http;
|
|
3121
|
+
this.analytics = null;
|
|
3122
|
+
}
|
|
3123
|
+
/**
|
|
3124
|
+
* AnalyticsAPI 주입 — 로그인/가입/로그아웃 시 방문자 트래커에 member_id 를 전달하여
|
|
3125
|
+
* 게스트 방문자를 회원과 연결한다. ConnectBase 컨스트럭터에서 내부적으로 호출된다.
|
|
3126
|
+
*/
|
|
3127
|
+
_attachAnalytics(analytics) {
|
|
3128
|
+
this.analytics = analytics;
|
|
3129
|
+
}
|
|
3130
|
+
notifyVisitorTracker(memberId) {
|
|
3131
|
+
if (this.analytics) {
|
|
3132
|
+
this.analytics.setMemberId(memberId);
|
|
3133
|
+
return;
|
|
3134
|
+
}
|
|
3135
|
+
if (typeof window === "undefined") return;
|
|
3136
|
+
const bridge = window;
|
|
3137
|
+
if (memberId) {
|
|
3138
|
+
if (typeof bridge.__cbSetMember === "function") {
|
|
3139
|
+
bridge.__cbSetMember(memberId);
|
|
3140
|
+
}
|
|
3141
|
+
} else {
|
|
3142
|
+
if (typeof bridge.__cbClearMember === "function") {
|
|
3143
|
+
bridge.__cbClearMember();
|
|
3144
|
+
}
|
|
3145
|
+
}
|
|
3146
|
+
}
|
|
3147
|
+
/**
|
|
3148
|
+
* 앱의 인증 설정 조회
|
|
3149
|
+
* 어떤 로그인 방식이 허용되는지 확인합니다.
|
|
3150
|
+
*
|
|
3151
|
+
* @example
|
|
3152
|
+
* ```typescript
|
|
3153
|
+
* const settings = await client.auth.getAuthSettings()
|
|
3154
|
+
* if (settings.allow_id_password_login) {
|
|
3155
|
+
* // 로그인 폼 표시
|
|
3156
|
+
* } else if (settings.enabled_oauth_providers.includes('GOOGLE')) {
|
|
3157
|
+
* // 구글 소셜 로그인 버튼 표시
|
|
3158
|
+
* }
|
|
3159
|
+
* ```
|
|
3160
|
+
*/
|
|
3161
|
+
async getAuthSettings() {
|
|
3162
|
+
return this.http.get("/v1/public/auth-settings", {
|
|
3163
|
+
skipAuth: true
|
|
3164
|
+
});
|
|
3165
|
+
}
|
|
3166
|
+
/**
|
|
3167
|
+
* 앱 멤버 회원가입 (아이디/이메일 + 비밀번호 기반)
|
|
3168
|
+
* 앱에 새로운 멤버를 등록합니다.
|
|
3169
|
+
*
|
|
3170
|
+
* `login_id` 와 `email` 중 **최소 하나**는 있어야 합니다. 어느 쪽을 주느냐에 따라
|
|
3171
|
+
* 만들어지는 로그인 수단이 달라집니다 — 표는 {@link MemberSignUpRequest} 참고.
|
|
3172
|
+
*
|
|
3173
|
+
* `email` 을 함께 저장해야 나중에 {@link AuthAPI.requestPasswordReset} 로 비밀번호를
|
|
3174
|
+
* 복구할 수 있습니다. `login_id` 만으로 가입한 멤버는 복구 수단이 없습니다.
|
|
3175
|
+
*
|
|
3176
|
+
* 이메일을 넘겨도 **인증 메일이 자동 발송되지는 않습니다.** 발신 주소가 플랫폼 단일
|
|
3177
|
+
* 주소라 앱이 요청하지 않은 메일을 보내지 않는다는 정책입니다 — 필요하면 가입 직후
|
|
3178
|
+
* {@link AuthAPI.sendEmailVerification} 을 직접 호출하세요.
|
|
3179
|
+
*
|
|
3180
|
+
* @example
|
|
3181
|
+
* ```typescript
|
|
3182
|
+
* // 기존 방식 — 아이디만 (동작 그대로, 단 비밀번호 복구 불가)
|
|
3183
|
+
* const result = await client.auth.signUpMember({
|
|
3184
|
+
* login_id: 'myuser123',
|
|
3185
|
+
* password: 'password123',
|
|
3186
|
+
* nickname: 'John'
|
|
3187
|
+
* })
|
|
3188
|
+
*
|
|
3189
|
+
* // 아이디 + 복구용 이메일 (로그인은 여전히 login_id 로)
|
|
3190
|
+
* await client.auth.signUpMember({
|
|
3191
|
+
* login_id: 'myuser123',
|
|
3192
|
+
* email: 'john@example.com',
|
|
3193
|
+
* password: 'password123'
|
|
3194
|
+
* })
|
|
3195
|
+
*
|
|
3196
|
+
* // 이메일만 — 이메일이 곧 로그인 아이디
|
|
3197
|
+
* await client.auth.signUpMember({
|
|
3198
|
+
* email: 'john@example.com',
|
|
3199
|
+
* password: 'password123'
|
|
3200
|
+
* })
|
|
3201
|
+
* ```
|
|
3202
|
+
*/
|
|
3203
|
+
async signUpMember(data) {
|
|
3204
|
+
if (!data.login_id && !data.email) {
|
|
3205
|
+
throw new Error(
|
|
3206
|
+
"signUpMember requires at least one of login_id or email."
|
|
3207
|
+
);
|
|
3208
|
+
}
|
|
3209
|
+
const response = await this.http.post(
|
|
3210
|
+
"/v1/public/app-members/signup",
|
|
3211
|
+
data,
|
|
3212
|
+
{ skipAuth: true }
|
|
3213
|
+
);
|
|
3214
|
+
assertShape(
|
|
3215
|
+
response,
|
|
3216
|
+
{
|
|
3217
|
+
access_token: { type: "string" },
|
|
3218
|
+
refresh_token: { type: "string" },
|
|
3219
|
+
member_id: { type: "string-or-number" }
|
|
3220
|
+
},
|
|
3221
|
+
"auth.signUpMember"
|
|
3222
|
+
);
|
|
3223
|
+
this.http.setTokens(response.access_token, response.refresh_token);
|
|
3224
|
+
this.notifyVisitorTracker(response.member_id);
|
|
3225
|
+
return response;
|
|
3226
|
+
}
|
|
3227
|
+
/**
|
|
3228
|
+
* 앱 멤버 로그인 (아이디 또는 이메일 + 비밀번호)
|
|
3229
|
+
* 기존 멤버로 로그인합니다.
|
|
3230
|
+
*
|
|
3231
|
+
* `login_id` 가 1순위 조회 키이고, `email` 은 이메일로 가입한 멤버를 위한 별칭입니다.
|
|
3232
|
+
* 서버는 USERNAME 을 먼저 찾고 없을 때만 EMAIL 로 폴백하므로 **기존 `login_id` 호출은
|
|
3233
|
+
* 동작이 그대로**입니다. 둘 다 비어 있으면 400 입니다.
|
|
3234
|
+
*
|
|
3235
|
+
* @example
|
|
3236
|
+
* ```typescript
|
|
3237
|
+
* // 아이디로 로그인 (기존 방식)
|
|
3238
|
+
* const result = await client.auth.signInMember({
|
|
3239
|
+
* login_id: 'myuser123',
|
|
3240
|
+
* password: 'password123'
|
|
3241
|
+
* })
|
|
3242
|
+
*
|
|
3243
|
+
* // 이메일로 로그인
|
|
3244
|
+
* await client.auth.signInMember({
|
|
3245
|
+
* email: 'john@example.com',
|
|
3246
|
+
* password: 'password123'
|
|
3247
|
+
* })
|
|
3248
|
+
* ```
|
|
3249
|
+
*/
|
|
3250
|
+
async signInMember(data) {
|
|
3251
|
+
if (!data.login_id && !data.email) {
|
|
3252
|
+
throw new Error(
|
|
3253
|
+
"signInMember requires at least one of login_id or email."
|
|
3254
|
+
);
|
|
3255
|
+
}
|
|
3256
|
+
const response = await this.http.post(
|
|
3257
|
+
"/v1/public/app-members/signin",
|
|
3258
|
+
data,
|
|
3259
|
+
{ skipAuth: true }
|
|
3260
|
+
);
|
|
3261
|
+
assertShape(
|
|
3262
|
+
response,
|
|
3263
|
+
{
|
|
3264
|
+
access_token: { type: "string" },
|
|
3265
|
+
refresh_token: { type: "string" },
|
|
3266
|
+
member_id: { type: "string-or-number" }
|
|
3267
|
+
},
|
|
3268
|
+
"auth.signInMember"
|
|
3269
|
+
);
|
|
3270
|
+
this.http.setTokens(response.access_token, response.refresh_token);
|
|
3271
|
+
this.notifyVisitorTracker(response.member_id);
|
|
3272
|
+
return response;
|
|
3286
3273
|
}
|
|
3274
|
+
// ── 자격증명 복구/변경 ────────────────────────────────────────────────────
|
|
3275
|
+
//
|
|
3276
|
+
// # 메일 링크는 "앱이 운영하는 페이지"를 거친다
|
|
3277
|
+
//
|
|
3278
|
+
// 재설정/인증 메일의 링크는 이 API 를 직접 열지 않습니다. 브라우저 주소창으로는
|
|
3279
|
+
// `X-Public-Key` 헤더를 붙일 수 없기 때문입니다. 링크는 앱의 페이지(= SDK 가 이미
|
|
3280
|
+
// 초기화돼 있는 곳)로 가고, 그 페이지가 쿼리에서 `token` 을 꺼내 아래 confirm 메서드를
|
|
3281
|
+
// 호출하는 구조입니다.
|
|
3282
|
+
//
|
|
3283
|
+
// 그래서 `redirect_url` 로 넘길 주소는 **앱에 등록된 도메인이어야 합니다**
|
|
3284
|
+
// (자세한 규칙은 {@link MemberRedirectOption}). 도메인을 등록하지 않으면 링크가
|
|
3285
|
+
// 플랫폼 기본 페이지로 폴백합니다.
|
|
3287
3286
|
/**
|
|
3288
|
-
*
|
|
3289
|
-
*
|
|
3290
|
-
*
|
|
3287
|
+
* 비밀번호 재설정 메일을 보냅니다. (로그인 불필요)
|
|
3288
|
+
*
|
|
3289
|
+
* # 계정 열거 방지 — 응답으로는 아무것도 알 수 없다
|
|
3290
|
+
*
|
|
3291
|
+
* 가입되지 않은 이메일이든, 소셜 전용 계정(비밀번호 없음)이든, 정지된 멤버든
|
|
3292
|
+
* **똑같은 200 과 똑같은 문구**가 돌아옵니다. 메일이 실제로 나갔는지 여부는 응답으로
|
|
3293
|
+
* 판별할 수 없습니다 — "가입 여부 확인" 용도로 쓸 수 없다는 뜻이며, 의도된 설계입니다.
|
|
3294
|
+
* UI 에서도 "가입된 계정이라면 메일을 보냈습니다" 처럼 안내하세요.
|
|
3295
|
+
*
|
|
3296
|
+
* 메일 링크의 토큰은 **1시간** 만료이고 **1회만** 쓸 수 있습니다.
|
|
3297
|
+
*
|
|
3298
|
+
* @example
|
|
3299
|
+
* ```typescript
|
|
3300
|
+
* // 앱이 자체 재설정 페이지를 운영하는 경우 (도메인 등록 선행 필수)
|
|
3301
|
+
* await client.auth.requestPasswordReset({
|
|
3302
|
+
* email: 'john@example.com',
|
|
3303
|
+
* redirect_url: 'https://myapp.com/reset-password'
|
|
3304
|
+
* })
|
|
3305
|
+
* toast('가입된 계정이라면 재설정 링크를 보냈습니다')
|
|
3306
|
+
* ```
|
|
3291
3307
|
*/
|
|
3292
|
-
|
|
3293
|
-
|
|
3294
|
-
|
|
3295
|
-
|
|
3296
|
-
|
|
3297
|
-
|
|
3308
|
+
async requestPasswordReset(data) {
|
|
3309
|
+
return this.http.post(
|
|
3310
|
+
"/v1/public/app-members/password-reset/request",
|
|
3311
|
+
data,
|
|
3312
|
+
{ skipAuth: true }
|
|
3313
|
+
);
|
|
3298
3314
|
}
|
|
3299
3315
|
/**
|
|
3300
|
-
*
|
|
3301
|
-
* 그대로, 아니면 HTTP 요청과 같은 refresh(같은 single-flight, 같은 실패 처리 — 세션이 끝났으면 onTokenExpired)를 한다.
|
|
3302
|
-
* 세션이 다르거나 갱신에 실패하면 undefined.
|
|
3316
|
+
* 재설정 토큰으로 새 비밀번호를 확정합니다. (로그인 불필요)
|
|
3303
3317
|
*
|
|
3304
|
-
* `
|
|
3305
|
-
*
|
|
3318
|
+
* `redirect_url` 페이지의 `?token=` 쿼리 값을 그대로 넘기면 됩니다.
|
|
3319
|
+
*
|
|
3320
|
+
* 성공하면 **그 멤버의 모든 세션이 서버에서 폐기**됩니다. 다른 기기 로그인까지 전부
|
|
3321
|
+
* 끊기며, 이 SDK 인스턴스에 남아 있던 토큰도 함께 정리하므로 새 비밀번호로 다시
|
|
3322
|
+
* 로그인해야 합니다.
|
|
3323
|
+
*
|
|
3324
|
+
* 토큰이 만료(1시간)됐거나 이미 사용됐거나 위조/타앱 토큰이면 400 이 납니다. 사유는
|
|
3325
|
+
* 구분되지 않습니다 — 토큰을 탐색하는 단서를 주지 않기 위해서입니다.
|
|
3326
|
+
*
|
|
3327
|
+
* @example
|
|
3328
|
+
* ```typescript
|
|
3329
|
+
* const token = new URLSearchParams(location.search).get('token')
|
|
3330
|
+
* if (!token) return
|
|
3331
|
+
* try {
|
|
3332
|
+
* await client.auth.confirmPasswordReset({ token, new_password: 'newpass123' })
|
|
3333
|
+
* location.href = '/login'
|
|
3334
|
+
* } catch (e) {
|
|
3335
|
+
* // 만료, 이미 사용됨, 잘못된 링크가 모두 여기로 온다
|
|
3336
|
+
* alert('링크가 만료되었거나 이미 사용되었습니다. 재설정을 다시 요청해 주세요.')
|
|
3337
|
+
* }
|
|
3338
|
+
* ```
|
|
3306
3339
|
*/
|
|
3307
|
-
async
|
|
3308
|
-
|
|
3309
|
-
|
|
3310
|
-
|
|
3311
|
-
|
|
3312
|
-
|
|
3313
|
-
|
|
3314
|
-
|
|
3315
|
-
|
|
3316
|
-
return next && isSameMemberToken(next, token) ? next : void 0;
|
|
3317
|
-
} catch {
|
|
3318
|
-
return void 0;
|
|
3319
|
-
}
|
|
3320
|
-
}
|
|
3321
|
-
async prepareHeaders(config) {
|
|
3322
|
-
const headers = new Headers();
|
|
3323
|
-
headers.set("Content-Type", "application/json");
|
|
3324
|
-
const credential = this.getCredential();
|
|
3325
|
-
if (credential) {
|
|
3326
|
-
headers.set("X-Public-Key", credential);
|
|
3327
|
-
}
|
|
3328
|
-
if (!config?.skipAuth && !this.config.accessToken && this.config.publicKey && typeof window !== "undefined" && this.bootRestorePromise && (this.bootRestoreAlwaysAwait || this.hasSessionHint())) {
|
|
3329
|
-
try {
|
|
3330
|
-
await this.bootRestorePromise;
|
|
3331
|
-
} catch {
|
|
3332
|
-
}
|
|
3333
|
-
}
|
|
3334
|
-
if (!config?.skipAuth && this.config.accessToken) {
|
|
3335
|
-
let token = this.config.accessToken;
|
|
3336
|
-
if (this.isTokenExpired(token) && this.config.refreshToken) {
|
|
3337
|
-
const newToken = await this.refreshAccessToken();
|
|
3338
|
-
if (newToken) {
|
|
3339
|
-
token = newToken;
|
|
3340
|
-
}
|
|
3341
|
-
}
|
|
3342
|
-
if (!isConsolePlatformToken(token)) {
|
|
3343
|
-
headers.set("Authorization", `Bearer ${token}`);
|
|
3344
|
-
}
|
|
3345
|
-
} else if (!config?.skipAuth && this.config.publicKey && this.config.secretKey && !headers.has("Authorization")) {
|
|
3346
|
-
headers.set("Authorization", `Bearer ${this.config.secretKey}`);
|
|
3347
|
-
}
|
|
3348
|
-
if (!config?.skipAuth && this.config.secretKey) {
|
|
3349
|
-
headers.set("X-User-Secret-Key", this.config.secretKey);
|
|
3350
|
-
}
|
|
3351
|
-
if (config?.headers) {
|
|
3352
|
-
Object.entries(config.headers).forEach(([key, value]) => {
|
|
3353
|
-
headers.set(key, value);
|
|
3354
|
-
});
|
|
3355
|
-
}
|
|
3356
|
-
return headers;
|
|
3340
|
+
async confirmPasswordReset(data) {
|
|
3341
|
+
const response = await this.http.post(
|
|
3342
|
+
"/v1/public/app-members/password-reset/confirm",
|
|
3343
|
+
data,
|
|
3344
|
+
{ skipAuth: true }
|
|
3345
|
+
);
|
|
3346
|
+
this.http.clearTokens();
|
|
3347
|
+
this.notifyVisitorTracker(null);
|
|
3348
|
+
return response;
|
|
3357
3349
|
}
|
|
3358
3350
|
/**
|
|
3359
|
-
*
|
|
3351
|
+
* 로그인한 멤버가 현재 비밀번호를 확인하고 새 비밀번호로 바꿉니다. (AppMember 토큰 필요)
|
|
3360
3352
|
*
|
|
3361
|
-
*
|
|
3362
|
-
*
|
|
3363
|
-
*
|
|
3364
|
-
*
|
|
3353
|
+
* `confirmPasswordReset` 과 마찬가지로 성공 시 **전 세션이 폐기**되고 로컬 토큰도
|
|
3354
|
+
* 정리됩니다. 호출한 클라이언트도 재로그인이 필요합니다.
|
|
3355
|
+
*
|
|
3356
|
+
* @example
|
|
3357
|
+
* ```typescript
|
|
3358
|
+
* await client.auth.changePassword({
|
|
3359
|
+
* current_password: 'oldpass123',
|
|
3360
|
+
* new_password: 'newpass123'
|
|
3361
|
+
* })
|
|
3362
|
+
* // 세션이 끊겼으므로 로그인 화면으로
|
|
3363
|
+
* location.href = '/login'
|
|
3364
|
+
* ```
|
|
3365
3365
|
*/
|
|
3366
|
-
async
|
|
3367
|
-
|
|
3368
|
-
|
|
3369
|
-
|
|
3370
|
-
errorData = await response.json();
|
|
3371
|
-
} catch {
|
|
3372
|
-
bodyIsJson = false;
|
|
3373
|
-
}
|
|
3374
|
-
const retryAfterHeader = response.status === 429 ? response.headers.get("Retry-After") : null;
|
|
3375
|
-
let retryAfterSeconds;
|
|
3376
|
-
if (retryAfterHeader) {
|
|
3377
|
-
const asInt = Number.parseInt(retryAfterHeader, 10);
|
|
3378
|
-
if (Number.isFinite(asInt) && asInt >= 0) {
|
|
3379
|
-
retryAfterSeconds = asInt;
|
|
3380
|
-
} else {
|
|
3381
|
-
const dateMs = Date.parse(retryAfterHeader);
|
|
3382
|
-
if (Number.isFinite(dateMs)) {
|
|
3383
|
-
retryAfterSeconds = Math.max(
|
|
3384
|
-
0,
|
|
3385
|
-
Math.round((dateMs - Date.now()) / 1e3)
|
|
3386
|
-
);
|
|
3387
|
-
}
|
|
3388
|
-
}
|
|
3389
|
-
}
|
|
3390
|
-
const rawError = errorData.error;
|
|
3391
|
-
if (rawError && typeof rawError === "object" && "message" in rawError) {
|
|
3392
|
-
const structured = rawError;
|
|
3393
|
-
const details = {
|
|
3394
|
-
...structured.details && typeof structured.details === "object" ? structured.details : {}
|
|
3395
|
-
};
|
|
3396
|
-
if (retryAfterSeconds !== void 0) {
|
|
3397
|
-
details.retry_after_seconds = retryAfterSeconds;
|
|
3398
|
-
}
|
|
3399
|
-
const err2 = new ApiError(
|
|
3400
|
-
response.status,
|
|
3401
|
-
typeof structured.message === "string" && structured.message !== "" ? structured.message : "Unknown error",
|
|
3402
|
-
typeof structured.code === "string" ? structured.code : void 0,
|
|
3403
|
-
Object.keys(details).length > 0 ? details : void 0
|
|
3404
|
-
);
|
|
3405
|
-
return err2;
|
|
3406
|
-
}
|
|
3407
|
-
const flatMessage = typeof errorData.message === "string" && errorData.message !== "" ? errorData.message : void 0;
|
|
3408
|
-
const explicitCode = typeof errorData.code === "string" && errorData.code !== "" ? errorData.code : void 0;
|
|
3409
|
-
const errorIsCode = typeof rawError === "string" && /^[a-z][a-z0-9_]*$/.test(rawError);
|
|
3410
|
-
const message = flatMessage ?? (typeof rawError === "string" && rawError !== "" ? rawError : void 0) ?? (bodyIsJson ? void 0 : gatewayMessageFromStatus(response.status)) ?? (response.statusText !== "" ? response.statusText : "Unknown error");
|
|
3411
|
-
const code = explicitCode ?? (errorIsCode ? rawError : void 0) ?? gatewayCodeFromStatus(response.status);
|
|
3412
|
-
const legacyDetails = {};
|
|
3413
|
-
if (retryAfterSeconds !== void 0) {
|
|
3414
|
-
legacyDetails.retry_after_seconds = retryAfterSeconds;
|
|
3415
|
-
}
|
|
3416
|
-
if (typeof errorData.provider === "string") {
|
|
3417
|
-
legacyDetails.provider = errorData.provider;
|
|
3418
|
-
}
|
|
3419
|
-
if (typeof errorData.model === "string") {
|
|
3420
|
-
legacyDetails.model = errorData.model;
|
|
3421
|
-
}
|
|
3422
|
-
const err = new ApiError(
|
|
3423
|
-
response.status,
|
|
3424
|
-
message,
|
|
3425
|
-
code,
|
|
3426
|
-
Object.keys(legacyDetails).length > 0 ? legacyDetails : void 0
|
|
3366
|
+
async changePassword(data) {
|
|
3367
|
+
const response = await this.http.post(
|
|
3368
|
+
"/v1/public/app-members/me/password",
|
|
3369
|
+
data
|
|
3427
3370
|
);
|
|
3428
|
-
|
|
3371
|
+
this.http.clearTokens();
|
|
3372
|
+
this.notifyVisitorTracker(null);
|
|
3373
|
+
return response;
|
|
3429
3374
|
}
|
|
3430
|
-
|
|
3431
|
-
|
|
3432
|
-
|
|
3433
|
-
|
|
3434
|
-
|
|
3435
|
-
|
|
3436
|
-
|
|
3437
|
-
|
|
3438
|
-
|
|
3439
|
-
|
|
3375
|
+
/**
|
|
3376
|
+
* 로그인한 멤버에게 이메일 인증 메일을 보냅니다. (AppMember 토큰 필요)
|
|
3377
|
+
*
|
|
3378
|
+
* 가입 시 자동 발송되지 않으므로, 인증이 필요한 앱은 이 메서드를 **직접** 불러야 합니다
|
|
3379
|
+
* (예: 가입 직후, 또는 설정 화면의 "인증 메일 다시 보내기" 버튼).
|
|
3380
|
+
*
|
|
3381
|
+
* 메일 링크의 토큰은 **24시간** 만료이고 **1회만** 쓸 수 있습니다.
|
|
3382
|
+
*
|
|
3383
|
+
* 이메일 인증은 **로그인의 전제 조건이 아닙니다** — 인증하지 않아도 로그인은 됩니다.
|
|
3384
|
+
* 인증 여부로 기능을 제한할지는 앱이 `getMe()` 등으로 확인해 스스로 정합니다.
|
|
3385
|
+
*
|
|
3386
|
+
* @example
|
|
3387
|
+
* ```typescript
|
|
3388
|
+
* await client.auth.sendEmailVerification({
|
|
3389
|
+
* redirect_url: 'https://myapp.com/verify-email'
|
|
3390
|
+
* })
|
|
3391
|
+
*
|
|
3392
|
+
* // redirect_url 없이 — 플랫폼 기본 페이지 링크로 발송된다
|
|
3393
|
+
* await client.auth.sendEmailVerification()
|
|
3394
|
+
* ```
|
|
3395
|
+
*/
|
|
3396
|
+
async sendEmailVerification(data) {
|
|
3397
|
+
return this.http.post(
|
|
3398
|
+
"/v1/public/app-members/me/email-verification/request",
|
|
3399
|
+
data ?? {}
|
|
3400
|
+
);
|
|
3440
3401
|
}
|
|
3441
3402
|
/**
|
|
3442
|
-
*
|
|
3403
|
+
* 인증 토큰으로 이메일 인증을 확정합니다. (로그인 불필요)
|
|
3443
3404
|
*
|
|
3444
|
-
*
|
|
3445
|
-
*
|
|
3446
|
-
*
|
|
3447
|
-
* (
|
|
3405
|
+
* 메일 링크가 연 페이지에서 `?token=` 을 꺼내 그대로 넘깁니다. 링크를 누른 사람이 그
|
|
3406
|
+
* 앱에 로그인해 있지 않아도(다른 기기의 메일 앱에서 열어도) 동작합니다.
|
|
3407
|
+
*
|
|
3408
|
+
* 만료(24시간), 이미 사용됨, 위조 토큰은 모두 400 이며 사유가 구분되지 않습니다.
|
|
3409
|
+
*
|
|
3410
|
+
* @example
|
|
3411
|
+
* ```typescript
|
|
3412
|
+
* const token = new URLSearchParams(location.search).get('token')
|
|
3413
|
+
* if (!token) return
|
|
3414
|
+
* try {
|
|
3415
|
+
* const r = await client.auth.confirmEmailVerification({ token })
|
|
3416
|
+
* console.log(r.email, r.is_email_verified) // true
|
|
3417
|
+
* } catch {
|
|
3418
|
+
* alert('인증 링크가 만료되었거나 이미 사용되었습니다.')
|
|
3419
|
+
* }
|
|
3420
|
+
* ```
|
|
3448
3421
|
*/
|
|
3449
|
-
async
|
|
3450
|
-
const
|
|
3451
|
-
|
|
3452
|
-
|
|
3453
|
-
|
|
3454
|
-
|
|
3455
|
-
|
|
3456
|
-
|
|
3457
|
-
|
|
3458
|
-
|
|
3459
|
-
|
|
3460
|
-
|
|
3461
|
-
|
|
3462
|
-
|
|
3463
|
-
url,
|
|
3464
|
-
{ ...init, headers: retryHeaders },
|
|
3465
|
-
config
|
|
3466
|
-
);
|
|
3467
|
-
status = second.status;
|
|
3468
|
-
return await this.handleResponse(second.response);
|
|
3469
|
-
}
|
|
3470
|
-
}
|
|
3471
|
-
return await this.handleResponse(first.response);
|
|
3472
|
-
} finally {
|
|
3473
|
-
this.recentCalls.push({
|
|
3474
|
-
method: (init.method || "GET").toUpperCase(),
|
|
3475
|
-
path: sanitizePathForBreadcrumb(url),
|
|
3476
|
-
status,
|
|
3477
|
-
duration_ms: Date.now() - startedAt,
|
|
3478
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
3479
|
-
});
|
|
3480
|
-
}
|
|
3422
|
+
async confirmEmailVerification(data) {
|
|
3423
|
+
const response = await this.http.post(
|
|
3424
|
+
"/v1/public/app-members/email-verification/confirm",
|
|
3425
|
+
data,
|
|
3426
|
+
{ skipAuth: true }
|
|
3427
|
+
);
|
|
3428
|
+
assertShape(
|
|
3429
|
+
response,
|
|
3430
|
+
{
|
|
3431
|
+
member_id: { type: "string-or-number" }
|
|
3432
|
+
},
|
|
3433
|
+
"auth.confirmEmailVerification"
|
|
3434
|
+
);
|
|
3435
|
+
return response;
|
|
3481
3436
|
}
|
|
3482
3437
|
/**
|
|
3483
|
-
*
|
|
3438
|
+
* 현재 로그인한 멤버 정보 조회
|
|
3439
|
+
* custom_data를 포함한 멤버 정보를 반환합니다.
|
|
3484
3440
|
*
|
|
3485
|
-
*
|
|
3486
|
-
*
|
|
3487
|
-
*
|
|
3488
|
-
*
|
|
3489
|
-
*
|
|
3490
|
-
* 추가돼도 자동으로 제외된다(서버도 같은 경로를 421 로 되돌려보낸다).
|
|
3441
|
+
* @example
|
|
3442
|
+
* ```typescript
|
|
3443
|
+
* const me = await client.auth.getMe()
|
|
3444
|
+
* console.log('내 정보:', me.nickname, me.custom_data)
|
|
3445
|
+
* ```
|
|
3491
3446
|
*/
|
|
3492
|
-
|
|
3493
|
-
if (
|
|
3494
|
-
|
|
3495
|
-
}
|
|
3496
|
-
if (this.directBaseUrl && !this.directDisabled && fetchCredentialsForPath(url) === "omit") {
|
|
3497
|
-
return this.directBaseUrl;
|
|
3447
|
+
async getMe() {
|
|
3448
|
+
if (this.http.knowsNoSession()) {
|
|
3449
|
+
throw await this.http.rejectNoSession();
|
|
3498
3450
|
}
|
|
3499
|
-
|
|
3451
|
+
const response = await this.http.get(
|
|
3452
|
+
"/v1/public/app-members/me"
|
|
3453
|
+
);
|
|
3454
|
+
assertShape(
|
|
3455
|
+
response,
|
|
3456
|
+
{
|
|
3457
|
+
member_id: { type: "string-or-number" }
|
|
3458
|
+
},
|
|
3459
|
+
"auth.getMe"
|
|
3460
|
+
);
|
|
3461
|
+
return response;
|
|
3500
3462
|
}
|
|
3501
3463
|
/**
|
|
3502
|
-
*
|
|
3464
|
+
* 현재 로그인한 멤버의 custom_data 수정
|
|
3465
|
+
* PATCH 방식으로 기존 데이터에 머지됩니다. 값을 null로 설정하면 해당 키가 삭제됩니다.
|
|
3503
3466
|
*
|
|
3504
|
-
*
|
|
3505
|
-
*
|
|
3506
|
-
*
|
|
3507
|
-
*
|
|
3467
|
+
* @example
|
|
3468
|
+
* ```typescript
|
|
3469
|
+
* // 키 추가/수정
|
|
3470
|
+
* await client.auth.updateCustomData({
|
|
3471
|
+
* custom_data: { role: 'admin', level: 5 }
|
|
3472
|
+
* })
|
|
3508
3473
|
*
|
|
3509
|
-
*
|
|
3510
|
-
*
|
|
3511
|
-
*
|
|
3474
|
+
* // 키 삭제 (null 전달)
|
|
3475
|
+
* await client.auth.updateCustomData({
|
|
3476
|
+
* custom_data: { role: null }
|
|
3477
|
+
* })
|
|
3478
|
+
* ```
|
|
3512
3479
|
*/
|
|
3513
|
-
|
|
3514
|
-
|
|
3515
|
-
|
|
3516
|
-
|
|
3517
|
-
response.headers.get("X-CB-Realtime-Direct-Base")
|
|
3480
|
+
async updateCustomData(data) {
|
|
3481
|
+
return this.http.patch(
|
|
3482
|
+
"/v1/public/app-members/me/custom-data",
|
|
3483
|
+
data
|
|
3518
3484
|
);
|
|
3519
3485
|
}
|
|
3520
3486
|
/**
|
|
3521
|
-
*
|
|
3522
|
-
*
|
|
3487
|
+
* Admin: 다른 멤버의 정보를 수정합니다 (role / nickname / custom_data).
|
|
3488
|
+
*
|
|
3489
|
+
* 이 메서드는 RLS 의 `auth.role` 평가에 사용되는 `member.role` 필드를 set 할 수 있는
|
|
3490
|
+
* 유일한 SDK 경로입니다. 보안상 AppMember 자신의 self-update 는 허용되지 않습니다
|
|
3491
|
+
* (권한 상승 우회 차단) — 이 메서드는 cb_sk_ admin secret key 권한 컨텍스트에서만
|
|
3492
|
+
* 호출 가능합니다.
|
|
3493
|
+
*
|
|
3494
|
+
* 사전 조건:
|
|
3495
|
+
* - ConnectBase 인스턴스가 `publicKey` 와 `secretKey` 를 모두 가지고 있어야 함
|
|
3496
|
+
* - secretKey 의 user 가 해당 앱에 권한을 가지고 있어야 함 (서버에서 검증)
|
|
3497
|
+
*
|
|
3498
|
+
* @example
|
|
3499
|
+
* ```typescript
|
|
3500
|
+
* const cb = new ConnectBase({ publicKey: 'cb_pk_...', secretKey: 'cb_sk_...' })
|
|
3501
|
+
* await cb.auth.adminUpdateMember('member-uuid', { role: 'admin' })
|
|
3502
|
+
*
|
|
3503
|
+
* // role 해제
|
|
3504
|
+
* await cb.auth.adminUpdateMember('member-uuid', { role: '' })
|
|
3505
|
+
*
|
|
3506
|
+
* // 다중 필드
|
|
3507
|
+
* await cb.auth.adminUpdateMember('member-uuid', {
|
|
3508
|
+
* nickname: 'Alice',
|
|
3509
|
+
* role: 'editor',
|
|
3510
|
+
* custom_data: { level: 5 }
|
|
3511
|
+
* })
|
|
3512
|
+
*
|
|
3513
|
+
* // 역할 여러 개 (6.7.0+): role 은 주 역할(RLS auth.role), roles 는 추가 역할 목록을 **통째로 바꾼다**
|
|
3514
|
+
* // ([] 면 비우고, 빼면 그대로). auth.roles, hasRole(), 실시간 publisher_roles 는 role + roles 를 함께 본다.
|
|
3515
|
+
* await cb.auth.adminUpdateMember('member-uuid', { roles: ['performer'] })
|
|
3516
|
+
* // → { role: 'admin', roles: ['performer'], effective_roles: ['admin', 'performer'], ... }
|
|
3517
|
+
* ```
|
|
3523
3518
|
*/
|
|
3524
|
-
|
|
3525
|
-
|
|
3526
|
-
|
|
3527
|
-
|
|
3528
|
-
|
|
3529
|
-
} catch {
|
|
3530
|
-
}
|
|
3531
|
-
if (base && !this.directDisabled && !this.directBaseUrl && typeof advertised === "string" && advertised) {
|
|
3532
|
-
try {
|
|
3533
|
-
const next = new URL(advertised);
|
|
3534
|
-
if (next.protocol === "https:" && tail(next.hostname) === tail(base.hostname)) {
|
|
3535
|
-
this.directBaseUrl = next.origin;
|
|
3536
|
-
}
|
|
3537
|
-
} catch {
|
|
3538
|
-
}
|
|
3519
|
+
async adminUpdateMember(memberID, fields) {
|
|
3520
|
+
if (!this.http.getSecretKey()) {
|
|
3521
|
+
throw new Error(
|
|
3522
|
+
"adminUpdateMember requires a secretKey. Initialize ConnectBase with both publicKey and secretKey."
|
|
3523
|
+
);
|
|
3539
3524
|
}
|
|
3540
|
-
|
|
3541
|
-
|
|
3542
|
-
|
|
3543
|
-
|
|
3544
|
-
|
|
3545
|
-
|
|
3546
|
-
|
|
3547
|
-
|
|
3548
|
-
|
|
3525
|
+
return this.http.patch(
|
|
3526
|
+
`/v1/public/app-members/${encodeURIComponent(memberID)}`,
|
|
3527
|
+
fields
|
|
3528
|
+
);
|
|
3529
|
+
}
|
|
3530
|
+
/**
|
|
3531
|
+
* Admin: 다른 멤버를 삭제(탈퇴 처리)합니다. **되돌릴 수 없습니다.**
|
|
3532
|
+
*
|
|
3533
|
+
* `adminUpdateMember` 와 같은 권한 컨텍스트입니다 — `cb_pk_` 로 앱을 식별하고 함께 보낸
|
|
3534
|
+
* `cb_sk_` 의 사용자가 그 앱에 `app_member:write` 권한을 가져야 합니다. 브라우저 번들에
|
|
3535
|
+
* 시크릿 키를 넣지 마세요. 서버(함수·백엔드)에서만 호출합니다.
|
|
3536
|
+
*
|
|
3537
|
+
* 멤버 행과 함께 **로그인 수단(identities)** 이 지워집니다. 따라서 같은 소셜 계정으로 다시
|
|
3538
|
+
* 로그인하면 기존 member_id 로 되살아나지 않고 **새 member_id** 를 받습니다. 결제·구독·
|
|
3539
|
+
* 푸시 디바이스·방문 기록 등 멤버에 매달린 행도 함께 사라집니다.
|
|
3540
|
+
*
|
|
3541
|
+
* 앱이 자체 테이블(`cb.database`)에 보관한 데이터는 지우지 않습니다 — 그건 `service_role`
|
|
3542
|
+
* 로 앱이 직접 정리하세요.
|
|
3543
|
+
*
|
|
3544
|
+
* 이미 발급된 그 멤버의 access token 은 만료(최대 1시간)까지 서명이 유효합니다. 즉시
|
|
3545
|
+
* 차단이 필요하면 삭제 전에 정지(콘솔 `멤버 정지`)를 함께 쓰세요.
|
|
3546
|
+
*
|
|
3547
|
+
* @example
|
|
3548
|
+
* ```typescript
|
|
3549
|
+
* const cb = new ConnectBase({ publicKey: 'cb_pk_...', secretKey: 'cb_sk_...' })
|
|
3550
|
+
* await cb.auth.adminDeleteMember('member-uuid')
|
|
3551
|
+
* ```
|
|
3552
|
+
*/
|
|
3553
|
+
async adminDeleteMember(memberID) {
|
|
3554
|
+
if (!this.http.getSecretKey()) {
|
|
3555
|
+
throw new Error(
|
|
3556
|
+
"adminDeleteMember requires a secretKey. Initialize ConnectBase with both publicKey and secretKey."
|
|
3557
|
+
);
|
|
3549
3558
|
}
|
|
3559
|
+
return this.http.delete(
|
|
3560
|
+
`/v1/public/app-members/${encodeURIComponent(memberID)}`
|
|
3561
|
+
);
|
|
3550
3562
|
}
|
|
3551
3563
|
/**
|
|
3552
|
-
*
|
|
3564
|
+
* 로그인한 본인이 스스로 탈퇴합니다. **되돌릴 수 없습니다.**
|
|
3553
3565
|
*
|
|
3554
|
-
*
|
|
3555
|
-
*
|
|
3556
|
-
*
|
|
3557
|
-
*
|
|
3558
|
-
*
|
|
3559
|
-
*
|
|
3566
|
+
* App Store 심사 가이드라인 5.1.1(v)는 "앱 안에서 가입이 되면 앱 안에서 탈퇴도 가능해야
|
|
3567
|
+
* 한다"를 요구합니다 — 고객센터 안내로는 통과되지 않습니다. 이 메서드가 그 요구를 만족하는
|
|
3568
|
+
* 경로입니다.
|
|
3569
|
+
*
|
|
3570
|
+
* 확인 UI(“정말 탈퇴하시겠습니까?”)는 앱이 책임집니다. 서버는 확인 없이 즉시 삭제합니다.
|
|
3571
|
+
*
|
|
3572
|
+
* 성공하면 로컬 토큰이 정리되고 refresh 쿠키도 서버가 만료시킵니다 — `signOut()` 을 따로
|
|
3573
|
+
* 부를 필요가 없습니다.
|
|
3574
|
+
*
|
|
3575
|
+
* `adminDeleteMember` 와 동일하게 로그인 수단(identities)까지 지우므로, 같은 소셜 계정으로
|
|
3576
|
+
* 재가입하면 새 member_id 를 받습니다.
|
|
3560
3577
|
*
|
|
3561
|
-
*
|
|
3562
|
-
*
|
|
3563
|
-
*
|
|
3578
|
+
* @example
|
|
3579
|
+
* ```typescript
|
|
3580
|
+
* // 설정 > 회원 탈퇴 버튼
|
|
3581
|
+
* if (confirm('탈퇴하면 되돌릴 수 없습니다. 계속할까요?')) {
|
|
3582
|
+
* await cb.auth.deleteMyAccount()
|
|
3583
|
+
* location.href = '/'
|
|
3584
|
+
* }
|
|
3585
|
+
* ```
|
|
3564
3586
|
*/
|
|
3565
|
-
async
|
|
3566
|
-
|
|
3567
|
-
|
|
3568
|
-
|
|
3569
|
-
|
|
3587
|
+
async deleteMyAccount() {
|
|
3588
|
+
try {
|
|
3589
|
+
return await this.http.delete(
|
|
3590
|
+
"/v1/public/app-members/me"
|
|
3591
|
+
);
|
|
3592
|
+
} finally {
|
|
3593
|
+
this.http.clearTokens();
|
|
3594
|
+
this.notifyVisitorTracker(null);
|
|
3570
3595
|
}
|
|
3571
3596
|
}
|
|
3572
3597
|
/**
|
|
3573
|
-
*
|
|
3598
|
+
* 로그인한 회원의 Access Token(JWT)을 돌려줍니다. 로그인하지 않았거나 세션을 되살릴 수 없으면 `null`.
|
|
3574
3599
|
*
|
|
3575
|
-
* `
|
|
3576
|
-
*
|
|
3577
|
-
* `
|
|
3578
|
-
* `
|
|
3600
|
+
* 남은 시간이 `minValiditySeconds`(기본 300초) 보다 짧으면 먼저 갱신(refresh)해서 돌려줍니다. 브라우저에서
|
|
3601
|
+
* 메모리에 토큰이 없으면 HttpOnly 쿠키 세션 복구를 한 번 시도합니다. 회원(AppMember) 토큰만 돌려주며,
|
|
3602
|
+
* 콘솔 토큰이나 함수의 위임 토큰(`ctx.cbAdmin`)은 돌려주지 않습니다. 갱신할 수단이 없으면(refresh token 없이
|
|
3603
|
+
* `setTokens(token, '')` 로 받은 토큰) 아직 만료되지 않은 지금 토큰을 그대로 돌려줍니다.
|
|
3579
3604
|
*
|
|
3580
|
-
*
|
|
3605
|
+
* **같은 앱의 다른 사이트(iframe)에 로그인을 넘길 때** 씁니다. 받는 쪽은 `cb.setTokens(token, '')` 로 넣습니다.
|
|
3606
|
+
* 토큰은 그 회원 자신으로 앱 API 를 부를 수 있는 자격증명이니 정확한 origin 으로만 보내세요(`'*'` 금지).
|
|
3607
|
+
* refresh token 은 HttpOnly 쿠키라 넘길 수 없으므로 받는 쪽은 만료(약 1시간) 전에 다시 받아야 합니다.
|
|
3608
|
+
*
|
|
3609
|
+
* @example
|
|
3610
|
+
* ```typescript
|
|
3611
|
+
* // 부모(허브): 자식이 요청하면 그 origin 으로만 보낸다
|
|
3612
|
+
* const GAME_ORIGIN = 'https://my-game.web.connectbase.world'
|
|
3613
|
+
* window.addEventListener('message', async (e) => {
|
|
3614
|
+
* if (e.origin !== GAME_ORIGIN || e.data?.type !== 'cb:token-request') return
|
|
3615
|
+
* const token = await cb.auth.getAccessToken()
|
|
3616
|
+
* e.source?.postMessage({ type: 'cb:token', token }, { targetOrigin: GAME_ORIGIN })
|
|
3617
|
+
* })
|
|
3618
|
+
* ```
|
|
3581
3619
|
*/
|
|
3582
|
-
async
|
|
3583
|
-
const
|
|
3584
|
-
|
|
3585
|
-
|
|
3586
|
-
|
|
3587
|
-
|
|
3588
|
-
|
|
3589
|
-
|
|
3590
|
-
|
|
3591
|
-
|
|
3592
|
-
|
|
3593
|
-
|
|
3620
|
+
async getAccessToken(options) {
|
|
3621
|
+
const minValidity = Math.min(
|
|
3622
|
+
Math.max(0, options?.minValiditySeconds ?? 300),
|
|
3623
|
+
1800
|
|
3624
|
+
);
|
|
3625
|
+
let token = this.http.getAccessToken();
|
|
3626
|
+
if (!token) {
|
|
3627
|
+
await this.http.tryRestoreSessionFromCookie();
|
|
3628
|
+
token = this.http.getAccessToken();
|
|
3629
|
+
}
|
|
3630
|
+
if (!token || !isSameMemberToken(token, token)) {
|
|
3631
|
+
return null;
|
|
3594
3632
|
}
|
|
3633
|
+
const fresh = await this.http.freshTokenForMember(token, minValidity);
|
|
3634
|
+
if (fresh) {
|
|
3635
|
+
return fresh;
|
|
3636
|
+
}
|
|
3637
|
+
const current = this.http.getAccessToken();
|
|
3638
|
+
if (current && isSameMemberToken(current, token)) {
|
|
3639
|
+
return tokenExpiresWithin(current, 0) ? null : current;
|
|
3640
|
+
}
|
|
3641
|
+
return null;
|
|
3595
3642
|
}
|
|
3596
|
-
|
|
3597
|
-
|
|
3598
|
-
|
|
3599
|
-
|
|
3600
|
-
});
|
|
3601
|
-
const origin = this.resolveOrigin(url, config?.baseUrl);
|
|
3643
|
+
/**
|
|
3644
|
+
* 로그아웃
|
|
3645
|
+
*/
|
|
3646
|
+
async signOut() {
|
|
3602
3647
|
try {
|
|
3603
|
-
|
|
3604
|
-
fetch(`${origin}${url}`, {
|
|
3605
|
-
...init,
|
|
3606
|
-
credentials: fetchCredentialsForPath(url),
|
|
3607
|
-
signal
|
|
3608
|
-
}),
|
|
3609
|
-
signal
|
|
3610
|
-
);
|
|
3611
|
-
if (!config?.baseUrl) {
|
|
3612
|
-
this.learnDirectOrigin(response);
|
|
3613
|
-
}
|
|
3614
|
-
return { response, ok: response.ok, status: response.status };
|
|
3615
|
-
} catch (err) {
|
|
3616
|
-
if (!config?.baseUrl && origin !== this.config.baseUrl && !isAbortError(err)) {
|
|
3617
|
-
this.directDisabled = true;
|
|
3618
|
-
const response = await withAbort(
|
|
3619
|
-
fetch(`${this.config.baseUrl}${url}`, {
|
|
3620
|
-
...init,
|
|
3621
|
-
credentials: fetchCredentialsForPath(url),
|
|
3622
|
-
signal
|
|
3623
|
-
}),
|
|
3624
|
-
signal
|
|
3625
|
-
);
|
|
3626
|
-
return { response, ok: response.ok, status: response.status };
|
|
3627
|
-
}
|
|
3628
|
-
throw err;
|
|
3648
|
+
await this.http.post("/v1/auth/logout");
|
|
3629
3649
|
} finally {
|
|
3630
|
-
|
|
3650
|
+
this.http.clearTokens();
|
|
3651
|
+
this.notifyVisitorTracker(null);
|
|
3631
3652
|
}
|
|
3632
3653
|
}
|
|
3633
|
-
|
|
3634
|
-
|
|
3635
|
-
|
|
3636
|
-
|
|
3637
|
-
|
|
3638
|
-
|
|
3639
|
-
|
|
3640
|
-
|
|
3641
|
-
|
|
3642
|
-
|
|
3643
|
-
|
|
3644
|
-
|
|
3645
|
-
|
|
3646
|
-
|
|
3647
|
-
|
|
3648
|
-
|
|
3649
|
-
|
|
3654
|
+
// ── 활성 세션(로그인된 기기) 관리 ────────────────────────────────────────
|
|
3655
|
+
//
|
|
3656
|
+
// 대상은 언제나 **로그인한 본인**이다. 세 메서드 모두 사용자 식별자를 받지 않는다 —
|
|
3657
|
+
// 누구의 세션인지는 서버가 검증된 토큰에서 정하고, 요청은 정할 수 없다.
|
|
3658
|
+
//
|
|
3659
|
+
// 폐기는 되돌릴 수 없다. 다만 이미 발급된 액세스 토큰은 만료(최대 1시간)까지 유효하므로,
|
|
3660
|
+
// 끊긴 기기가 곧바로 모든 호출에 실패하지는 않는다. 즉시 차단이 필요하면 앱이 서버
|
|
3661
|
+
// 측에서 회원을 정지시켜야 한다.
|
|
3662
|
+
/**
|
|
3663
|
+
* 로그인된 기기(활성 세션) 목록을 조회합니다.
|
|
3664
|
+
*
|
|
3665
|
+
* 현재 세션이 맨 앞에 오고, 나머지는 최근 사용 순입니다. 응답에는 토큰도 평문 IP 도
|
|
3666
|
+
* 담기지 않습니다.
|
|
3667
|
+
*
|
|
3668
|
+
* **`current` 를 화면에 반드시 표시하세요.** 구분이 없으면 사용자가 자기가 쓰고 있는
|
|
3669
|
+
* 기기를 끊고 영문도 모른 채 로그아웃됩니다. refresh 쿠키가 없는 환경에서는 서버가
|
|
3670
|
+
* 현재 세션을 특정하지 못해 `current` 가 어느 항목에도 붙지 않을 수 있습니다.
|
|
3671
|
+
*
|
|
3672
|
+
* @example
|
|
3673
|
+
* ```typescript
|
|
3674
|
+
* const { sessions } = await cb.auth.listSessions()
|
|
3675
|
+
* for (const s of sessions) {
|
|
3676
|
+
* console.log(s.browser, s.os, s.location, s.current ? '(이 기기)' : '')
|
|
3677
|
+
* }
|
|
3678
|
+
* ```
|
|
3679
|
+
*/
|
|
3680
|
+
async listSessions() {
|
|
3681
|
+
const response = await this.http.get(
|
|
3682
|
+
"/v1/public/app-members/me/sessions"
|
|
3650
3683
|
);
|
|
3651
|
-
|
|
3652
|
-
|
|
3653
|
-
const headers = await this.prepareHeaders(config);
|
|
3654
|
-
if (data instanceof FormData) {
|
|
3655
|
-
headers.delete("Content-Type");
|
|
3656
|
-
}
|
|
3657
|
-
return this.doFetch(
|
|
3658
|
-
url,
|
|
3684
|
+
assertShape(
|
|
3685
|
+
response,
|
|
3659
3686
|
{
|
|
3660
|
-
|
|
3661
|
-
headers,
|
|
3662
|
-
body: data instanceof FormData ? data : JSON.stringify(data)
|
|
3687
|
+
sessions: { type: "array" }
|
|
3663
3688
|
},
|
|
3664
|
-
|
|
3689
|
+
"auth.listSessions"
|
|
3665
3690
|
);
|
|
3691
|
+
return response;
|
|
3666
3692
|
}
|
|
3667
|
-
|
|
3668
|
-
|
|
3669
|
-
|
|
3670
|
-
|
|
3671
|
-
|
|
3672
|
-
|
|
3673
|
-
|
|
3674
|
-
|
|
3675
|
-
|
|
3676
|
-
|
|
3693
|
+
/**
|
|
3694
|
+
* 기기 하나를 로그아웃시킵니다. `sessionId` 는 `listSessions()` 가 돌려준 `session_id`.
|
|
3695
|
+
*
|
|
3696
|
+
* 남의 세션 식별자를 넣으면 404 입니다 — 존재 여부조차 구분해 알려주지 않습니다.
|
|
3697
|
+
* 이미 끝난 세션도 같은 404 입니다.
|
|
3698
|
+
*
|
|
3699
|
+
* **현재 세션을 지목하면 그 자리에서 로그아웃됩니다.** 서버가 refresh 쿠키를 함께
|
|
3700
|
+
* 만료시키므로 로컬 토큰도 정리합니다 — 이 경우 앱은 로그인 화면으로 보내야 합니다.
|
|
3701
|
+
* 그렇지 않은 기기를 끊는 것은 현재 세션에 영향을 주지 않습니다.
|
|
3702
|
+
*
|
|
3703
|
+
* @example
|
|
3704
|
+
* ```typescript
|
|
3705
|
+
* const target = sessions.find((s) => !s.current)
|
|
3706
|
+
* if (target) await cb.auth.revokeSession(target.session_id)
|
|
3707
|
+
* ```
|
|
3708
|
+
*/
|
|
3709
|
+
async revokeSession(sessionId) {
|
|
3710
|
+
const current = await this.isCurrentSession(sessionId);
|
|
3711
|
+
const response = await this.http.delete(
|
|
3712
|
+
`/v1/public/app-members/me/sessions/${encodeURIComponent(sessionId)}`
|
|
3677
3713
|
);
|
|
3714
|
+
if (current) {
|
|
3715
|
+
this.http.clearTokens();
|
|
3716
|
+
this.notifyVisitorTracker(null);
|
|
3717
|
+
}
|
|
3718
|
+
return response;
|
|
3678
3719
|
}
|
|
3679
|
-
|
|
3680
|
-
|
|
3681
|
-
|
|
3720
|
+
/**
|
|
3721
|
+
* **현재 기기만 남기고** 나머지 기기에서 모두 로그아웃합니다.
|
|
3722
|
+
*
|
|
3723
|
+
* 자기 세션까지 포함한 전체 로그아웃은 `signOut()` 입니다 — 자격증명 유출 대응처럼
|
|
3724
|
+
* 모든 기기를 내보내야 하는 상황에서는 그쪽을 쓰세요.
|
|
3725
|
+
*
|
|
3726
|
+
* refresh 쿠키가 없어 서버가 현재 세션을 특정하지 못하면 이 호출은 **실패합니다**
|
|
3727
|
+
* (400). 기준점 없이 진행하면 사용자가 의도하지 않은 자기 세션 종료가 함께 일어나기
|
|
3728
|
+
* 때문입니다. 그 경우 `signOut()` 후 재로그인을 안내하세요.
|
|
3729
|
+
*
|
|
3730
|
+
* 반환되는 `revoked` 는 토큰 수가 아니라 **끊긴 기기 수** 입니다.
|
|
3731
|
+
*
|
|
3732
|
+
* @example
|
|
3733
|
+
* ```typescript
|
|
3734
|
+
* const { revoked } = await cb.auth.revokeOtherSessions()
|
|
3735
|
+
* toast(`${revoked}개 기기에서 로그아웃했습니다`)
|
|
3736
|
+
* ```
|
|
3737
|
+
*/
|
|
3738
|
+
async revokeOtherSessions() {
|
|
3739
|
+
return this.http.delete(
|
|
3740
|
+
"/v1/public/app-members/me/sessions"
|
|
3741
|
+
);
|
|
3682
3742
|
}
|
|
3683
3743
|
/**
|
|
3684
|
-
*
|
|
3685
|
-
*
|
|
3686
|
-
* (스트리밍 특성상 전역 timeout 을 강제하지 않음).
|
|
3744
|
+
* 폐기 대상이 현재 세션인지 미리 확인한다. 목록 조회가 실패하면 false 로 떨어져
|
|
3745
|
+
* 폐기 자체는 진행한다 — 판정 실패로 사용자의 로그아웃 요청을 막을 이유가 없다.
|
|
3687
3746
|
*/
|
|
3688
|
-
async
|
|
3689
|
-
const headers = await this.prepareHeaders();
|
|
3690
|
-
const mergedHeaders = new Headers(headers);
|
|
3691
|
-
if (init?.headers) {
|
|
3692
|
-
const extra = new Headers(init.headers);
|
|
3693
|
-
extra.forEach((value, key) => mergedHeaders.set(key, value));
|
|
3694
|
-
}
|
|
3695
|
-
const origin = this.resolveOrigin(url);
|
|
3747
|
+
async isCurrentSession(sessionId) {
|
|
3696
3748
|
try {
|
|
3697
|
-
const
|
|
3698
|
-
|
|
3699
|
-
|
|
3700
|
-
|
|
3701
|
-
|
|
3702
|
-
|
|
3703
|
-
return response;
|
|
3704
|
-
} catch (err) {
|
|
3705
|
-
if (origin !== this.config.baseUrl && !isAbortError(err)) {
|
|
3706
|
-
this.directDisabled = true;
|
|
3707
|
-
}
|
|
3708
|
-
throw err;
|
|
3749
|
+
const { sessions } = await this.listSessions();
|
|
3750
|
+
return sessions.some(
|
|
3751
|
+
(s) => s.session_id === sessionId && s.current === true
|
|
3752
|
+
);
|
|
3753
|
+
} catch {
|
|
3754
|
+
return false;
|
|
3709
3755
|
}
|
|
3710
3756
|
}
|
|
3711
3757
|
};
|
|
@@ -3867,6 +3913,21 @@ var DatabaseAPI = class {
|
|
|
3867
3913
|
getPublicPrefix() {
|
|
3868
3914
|
return "/v1/public";
|
|
3869
3915
|
}
|
|
3916
|
+
/**
|
|
3917
|
+
* 테이블과 컬럼의 생성, 수정, 삭제(스키마 변경)는 서버가 Secret Key(`cb_sk_`)를 요구한다(`401 SECRET_KEY_REQUIRED`).
|
|
3918
|
+
* Public Key 는 브라우저 번들에 공개되는 값이라 스키마 변경 자격증명이 될 수 없고, service_role(`ctx.cbAdmin`)과
|
|
3919
|
+
* 멤버 토큰으로도 열리지 않는다. Secret Key 없이 부르면 왕복 없이 같은 코드로 무엇이 필요한지 알린다
|
|
3920
|
+
* (platform-issue 01a1f735-ab96: 문서가 Public Key 로 된다고 안내해 실측이 필요했다).
|
|
3921
|
+
*/
|
|
3922
|
+
assertSchemaWriteCredential(method) {
|
|
3923
|
+
if (this.http.hasPublicKey() && !this.http.hasSecretKey()) {
|
|
3924
|
+
throw new ApiError(
|
|
3925
|
+
401,
|
|
3926
|
+
`cb.database.${method}() \uB294 Secret Key(cb_sk_)\uAC00 \uD544\uC694\uD569\uB2C8\uB2E4. \uD14C\uC774\uBE14\uACFC \uCEEC\uB7FC\uC758 \uC0DD\uC131, \uC218\uC815, \uC0AD\uC81C\uB294 Public Key(cb_pk_)\uB098 ctx.cbAdmin(service_role), \uD68C\uC6D0 \uB85C\uADF8\uC778\uC73C\uB85C\uB294 \uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4. \uC11C\uBC84\uB098 CI \uC5D0\uC11C new ConnectBase({ publicKey, secretKey }) \uB85C \uBD80\uB974\uAC70\uB098, \uCF58\uC194\uC774\uB098 MCP \uC5D0\uC11C \uD14C\uC774\uBE14\uC744 \uB9CC\uB4DC\uC138\uC694.`,
|
|
3927
|
+
"SECRET_KEY_REQUIRED"
|
|
3928
|
+
);
|
|
3929
|
+
}
|
|
3930
|
+
}
|
|
3870
3931
|
// ============ Table Methods ============
|
|
3871
3932
|
/**
|
|
3872
3933
|
* 테이블 목록 조회
|
|
@@ -3896,6 +3957,7 @@ var DatabaseAPI = class {
|
|
|
3896
3957
|
* 생성된 테이블 메타데이터가 필요하면 이어서 `getTables()` 로 조회하세요.
|
|
3897
3958
|
*/
|
|
3898
3959
|
async createTable(data) {
|
|
3960
|
+
this.assertSchemaWriteCredential("createTable");
|
|
3899
3961
|
const prefix = this.getPublicPrefix();
|
|
3900
3962
|
const body = {
|
|
3901
3963
|
title: data.name,
|
|
@@ -3912,6 +3974,7 @@ var DatabaseAPI = class {
|
|
|
3912
3974
|
* `name` 은 서버의 `title` 로, `accessLevel` 은 `access_level` 로 매핑됩니다.
|
|
3913
3975
|
*/
|
|
3914
3976
|
async updateTable(tableId, data) {
|
|
3977
|
+
this.assertSchemaWriteCredential("updateTable");
|
|
3915
3978
|
const prefix = this.getPublicPrefix();
|
|
3916
3979
|
const body = {};
|
|
3917
3980
|
if (data.name !== void 0) body.title = data.name;
|
|
@@ -3924,6 +3987,7 @@ var DatabaseAPI = class {
|
|
|
3924
3987
|
* 테이블 삭제
|
|
3925
3988
|
*/
|
|
3926
3989
|
async deleteTable(tableId) {
|
|
3990
|
+
this.assertSchemaWriteCredential("deleteTable");
|
|
3927
3991
|
const prefix = this.getPublicPrefix();
|
|
3928
3992
|
await this.http.delete(`${prefix}/tables/${tableId}`);
|
|
3929
3993
|
}
|
|
@@ -4044,6 +4108,7 @@ var DatabaseAPI = class {
|
|
|
4044
4108
|
* 생성 결과 컬럼을 얻으려면 이어서 `getColumns(tableId)` 로 조회하세요.
|
|
4045
4109
|
*/
|
|
4046
4110
|
async createColumn(tableId, data) {
|
|
4111
|
+
this.assertSchemaWriteCredential("createColumn");
|
|
4047
4112
|
const prefix = this.getPublicPrefix();
|
|
4048
4113
|
await this.http.post(`${prefix}/tables/${tableId}/columns`, data);
|
|
4049
4114
|
}
|
|
@@ -4053,6 +4118,7 @@ var DatabaseAPI = class {
|
|
|
4053
4118
|
* 서버는 `{message}` 만 돌려주므로 반환 타입은 `void` 입니다.
|
|
4054
4119
|
*/
|
|
4055
4120
|
async updateColumn(tableId, columnName, data) {
|
|
4121
|
+
this.assertSchemaWriteCredential("updateColumn");
|
|
4056
4122
|
const prefix = this.getPublicPrefix();
|
|
4057
4123
|
await this.http.patch(
|
|
4058
4124
|
`${prefix}/tables/${tableId}/columns/${columnName}`,
|
|
@@ -4063,6 +4129,7 @@ var DatabaseAPI = class {
|
|
|
4063
4129
|
* 컬럼 삭제
|
|
4064
4130
|
*/
|
|
4065
4131
|
async deleteColumn(tableId, columnName) {
|
|
4132
|
+
this.assertSchemaWriteCredential("deleteColumn");
|
|
4066
4133
|
const prefix = this.getPublicPrefix();
|
|
4067
4134
|
await this.http.delete(`${prefix}/tables/${tableId}/columns/${columnName}`);
|
|
4068
4135
|
}
|
|
@@ -5788,15 +5855,16 @@ var FunctionsAPI = class {
|
|
|
5788
5855
|
/**
|
|
5789
5856
|
* 서버리스 함수 실행
|
|
5790
5857
|
*
|
|
5791
|
-
* @param functionId - 함수 ID
|
|
5858
|
+
* @param functionId - 함수 ID 또는 같은 앱의 함수 이름 (이름은 퍼블릭 키 경로에서만, 앱 안에서 유일)
|
|
5792
5859
|
* @param payload - 함수에 전달할 데이터 (선택)
|
|
5793
5860
|
* @param timeout - 실행 타임아웃 (초, 선택)
|
|
5794
5861
|
* @returns 함수 실행 결과
|
|
5795
5862
|
*
|
|
5796
5863
|
* @example
|
|
5797
5864
|
* ```typescript
|
|
5798
|
-
* // 기본 실행
|
|
5865
|
+
* // 기본 실행 — 함수 ID 또는 함수 이름
|
|
5799
5866
|
* const result = await cb.functions.invoke('function-id')
|
|
5867
|
+
* const byName = await cb.functions.invoke('send-welcome-email')
|
|
5800
5868
|
*
|
|
5801
5869
|
* // 데이터와 함께 실행
|
|
5802
5870
|
* const result = await cb.functions.invoke('function-id', {
|
|
@@ -5818,7 +5886,7 @@ var FunctionsAPI = class {
|
|
|
5818
5886
|
request.timeout = timeout;
|
|
5819
5887
|
}
|
|
5820
5888
|
return this.http.post(
|
|
5821
|
-
`${prefix}/functions/${functionId}/invoke`,
|
|
5889
|
+
`${prefix}/functions/${encodeURIComponent(functionId)}/invoke`,
|
|
5822
5890
|
request
|
|
5823
5891
|
);
|
|
5824
5892
|
}
|
|
@@ -5872,7 +5940,7 @@ var FunctionsAPI = class {
|
|
|
5872
5940
|
* 서버리스 함수 실행 (비동기 래퍼)
|
|
5873
5941
|
* 결과만 반환하고 메타데이터는 제외
|
|
5874
5942
|
*
|
|
5875
|
-
* @param functionId - 함수 ID
|
|
5943
|
+
* @param functionId - 함수 ID 또는 같은 앱의 함수 이름
|
|
5876
5944
|
* @param payload - 함수에 전달할 데이터 (선택)
|
|
5877
5945
|
* @returns 함수 실행 결과 데이터
|
|
5878
5946
|
*
|
|
@@ -13818,8 +13886,8 @@ var SupportAPI = class {
|
|
|
13818
13886
|
}
|
|
13819
13887
|
};
|
|
13820
13888
|
function detectSdkVersion() {
|
|
13821
|
-
if ("6.
|
|
13822
|
-
return "6.
|
|
13889
|
+
if ("6.26.0") {
|
|
13890
|
+
return "6.26.0";
|
|
13823
13891
|
}
|
|
13824
13892
|
return "unknown";
|
|
13825
13893
|
}
|