@the-seeker/changes-react 0.2.1 → 0.3.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/README.md CHANGED
@@ -38,7 +38,7 @@ export function App() {
38
38
  |---|---|---|
39
39
  | `changesKey` | 필수 | 공개 키 |
40
40
  | `appVersion` | 없음 | 앱 버전을 알면 "네이티브 모드"(아래 표시 규칙)로 동작합니다 |
41
- | `user` | 없음 | `{ userId?, name? }`. `userId`가 있으면 투표·댓글이 기기 대신 사용자에 묶입니다. `name`은 프로젝트가 작성자 이름을 허용할 때만 쓰입니다 |
41
+ | `user` | 없음 | `{ userId?, name?, ssoToken? }` 또는 `null`. SSO는 아래 절을 참고하세요. `userId`는 기존 사용자 식별 방식이며 `name`은 작성자 이름 허용 시에만 쓰입니다 |
42
42
  | `locale` | `"auto"` | `"auto"`는 브라우저 언어(ko/en) → 프로젝트 기본 언어 순서로 고릅니다 |
43
43
  | `baseUrl` | `https://devstage.app` | 서버 주소. 0.1.x처럼 이전 주소를 계속 쓰려면 `"https://crm.theseeker.io"`를 넘기세요(두 주소 모두 같은 API를 제공합니다) |
44
44
  | `storage` | `localStorage` | `{ getItem, setItem }`(동기·비동기 모두 가능). SSR에서 안전하며 접근이 막히면 메모리로 대체합니다 |
@@ -49,6 +49,30 @@ export function App() {
49
49
  | `onError` | 없음 | 설정·목록 로딩 실패 코드(`ORIGIN_NOT_ALLOWED`, `CHANGES_NOT_FOUND`, `NETWORK_ERROR` 등) |
50
50
  | `fetchImpl` | 전역 `fetch` | 테스트나 특수 런타임용 전송 계층 |
51
51
 
52
+ ## SSO 방문자 식별 (0.3.0)
53
+
54
+ 연결된 사이트에서 SSO를 켠 뒤, **고객 서버에서 서명한** 짧은 수명의 JWS를 전달합니다. 서명 비밀키를 브라우저에 넣지 마세요.
55
+
56
+ ```tsx
57
+ <ChangesProvider changesKey="chg_…" user={session ? { ssoToken: session.changesJws } : null}>
58
+ <ChangelogButton />
59
+ </ChangesProvider>
60
+ ```
61
+
62
+ 첫 방문자 식별 요청(릴리스·댓글·로드맵 읽기, 투표·이벤트 등) 전에 `POST /api/changes/sso`로
63
+ `{ key, token }`을 교환하고 이후 요청에는 `X-Devstage-Visitor`를 보냅니다. JWS는 일반 요청 본문에 포함하지 않습니다.
64
+ 같은 Provider 안에서 같은 토큰 값은 교환을 공유하며, 값이 바뀌면 다시 교환합니다. 로그아웃은 `user={null}`
65
+ 또는 `ssoToken` 생략으로 토큰을 비웁니다. Provider를 새로 마운트하면 새 교환이 필요합니다.
66
+
67
+ 방문자 bearer는 **메모리에만** 보관하며 `localStorage`나 주입한 `storage`에 저장하지 않습니다.
68
+ 기존 설치 ID·표시 상태 저장은 유지됩니다. `401 VISITOR_INVALID`는 저장된 방문자 토큰을 버리고 한 번만
69
+ 재교환·재시도합니다. `SSO_DISABLED`·`SSO_REJECTED`는 익명 쓰기로 우회하지 않고 기존 오류 결과로 반환합니다.
70
+ 기존 익명 투표는 SSO 사용자에게 병합하지 않습니다.
71
+
72
+ 저수준 `createChangesClient`에도 `user`와 `visitorStore?: VisitorTokenStore`를 넘길 수 있습니다.
73
+ `VisitorTokenStore`는 `get(key)`와 `set(key, string | null)`을 제공하며 동기·비동기 구현을 지원합니다.
74
+ 웹에서는 `createMemoryVisitorStore()`를 사용하세요.
75
+
52
76
  ## 컴포넌트
53
77
 
54
78
  - `ChangelogButton` — 체인지로그 모달을 엽니다. 배지는 마지막으로 목록을 연 뒤 게시된 릴리스 수입니다.
@@ -1,3 +1,4 @@
1
+ import type { VisitorTokenStore } from "./types";
1
2
  import type { Platform, User, Voter, ClientInfo, Failure, Result, Releases, RoadmapStage } from "./types";
2
3
  export type FetchInit = Readonly<{
3
4
  method: "GET" | "POST";
@@ -21,7 +22,8 @@ export type ChangesClientOptions = Readonly<{
21
22
  locale?: string;
22
23
  appId?: string;
23
24
  appHeader?: string;
24
- user?: User;
25
+ user?: User | null;
26
+ visitorStore?: VisitorTokenStore;
25
27
  fetchImpl: FetchImpl;
26
28
  }>;
27
29
  export type ListOptions = Readonly<{
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.DEFAULT_BASE_URL = void 0;
4
4
  exports.createChangesClient = createChangesClient;
5
5
  const zod_1 = require("zod");
6
+ const sso_1 = require("./sso");
6
7
  const types_1 = require("./types");
7
8
  const types_2 = require("./types");
8
9
  exports.DEFAULT_BASE_URL = "https://devstage.app";
@@ -27,14 +28,35 @@ function createChangesClient(options) {
27
28
  const { key, platform, fetchImpl, user } = options;
28
29
  const baseUrl = (options.baseUrl ?? exports.DEFAULT_BASE_URL).replace(/\/+$/, "");
29
30
  const appHeaders = options.appId && platform !== "web" ? { "X-TheSeeker-App": options.appHeader ?? options.appId } : {};
30
- const identity = (voter) => ({ ...voter, ...user });
31
+ const identity = (voter) => ({
32
+ ...voter,
33
+ ...(user?.userId === undefined ? {} : { userId: user.userId }),
34
+ ...(user?.name === undefined ? {} : { name: user.name }),
35
+ });
36
+ const visitor = (0, sso_1.createVisitorSession)({
37
+ scope: `${baseUrl}:${key}`,
38
+ key,
39
+ token: user?.ssoToken ?? null,
40
+ store: options.visitorStore ?? (0, sso_1.createMemoryVisitorStore)(),
41
+ exchange: async () => {
42
+ const result = await transport(`${baseUrl}/api/changes/sso`, {
43
+ method: "POST",
44
+ headers: { ...appHeaders, "Content-Type": "application/json" },
45
+ body: JSON.stringify({ key, token: user?.ssoToken }),
46
+ });
47
+ if (!result.ok)
48
+ return result;
49
+ const parsed = await parse(result.response, sso_1.visitorSessionSchema);
50
+ return parsed.ok ? { ok: true, body: parsed.body.visitorToken } : parsed;
51
+ },
52
+ });
31
53
  const url = (path, query = {}) => {
32
54
  const values = { key, ...query };
33
55
  const pairs = Object.entries(values).filter((entry) => entry[1] !== undefined);
34
56
  return `${baseUrl}/api/changes/${path}?${pairs.map(([name, value]) => `${encodeURIComponent(name)}=${encodeURIComponent(value)}`).join("&")}`;
35
57
  };
36
58
  // Transport boundary: arbitrary rejected values must become a result, not escape to host apps.
37
- async function request(path, init) {
59
+ async function transport(path, init) {
38
60
  try {
39
61
  return { ok: true, response: await fetchImpl(path, init) };
40
62
  }
@@ -42,6 +64,35 @@ function createChangesClient(options) {
42
64
  return { ok: false, code: "NETWORK_ERROR" };
43
65
  }
44
66
  }
67
+ async function request(path, init) {
68
+ if (user?.ssoToken === undefined || /\/api\/changes\/(config|requests)(\?|$)/.test(path))
69
+ return transport(path, init);
70
+ try {
71
+ for (let attempt = 0; attempt < 2; attempt += 1) {
72
+ const token = await visitor.get();
73
+ if (!token.ok)
74
+ return token;
75
+ const result = await transport(path, {
76
+ ...init,
77
+ headers: { ...init.headers, ...(token.body === null ? {} : { "X-Devstage-Visitor": token.body }) },
78
+ });
79
+ if (!result.ok || result.response.status !== 401 || token.body === null)
80
+ return result;
81
+ const raw = await result.response.json();
82
+ const error = errorSchema.safeParse(raw);
83
+ const response = { status: result.response.status, headers: result.response.headers, json: async () => raw };
84
+ if (!error.success || error.data.error !== "VISITOR_INVALID")
85
+ return { ok: true, response };
86
+ await visitor.invalidate(token.body);
87
+ if (attempt === 1)
88
+ return { ok: false, code: "VISITOR_INVALID" };
89
+ }
90
+ }
91
+ catch {
92
+ return { ok: false, code: "NETWORK_ERROR" };
93
+ }
94
+ return { ok: false, code: "VISITOR_INVALID" };
95
+ }
45
96
  async function parse(response, schema) {
46
97
  let raw;
47
98
  try {
@@ -0,0 +1,23 @@
1
+ import { z } from "zod";
2
+ import type { Result, VisitorTokenStore } from "./types";
3
+ export declare const visitorSessionSchema: z.ZodObject<{
4
+ visitorToken: z.ZodString;
5
+ expiresAt: z.ZodString;
6
+ visitor: z.ZodObject<{
7
+ name: z.ZodNullable<z.ZodString>;
8
+ emailMasked: z.ZodNullable<z.ZodString>;
9
+ }, z.core.$strip>;
10
+ }, z.core.$strip>;
11
+ type Exchange = () => Promise<Result<string>>;
12
+ export declare function createMemoryVisitorStore(): VisitorTokenStore;
13
+ export declare function createVisitorSession(options: Readonly<{
14
+ scope: string;
15
+ key: string;
16
+ token: string | null;
17
+ store: VisitorTokenStore;
18
+ exchange: Exchange;
19
+ }>): {
20
+ get(): Promise<Result<string | null>>;
21
+ invalidate(rejected: string): Promise<void>;
22
+ };
23
+ export {};
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.visitorSessionSchema = void 0;
4
+ exports.createMemoryVisitorStore = createMemoryVisitorStore;
5
+ exports.createVisitorSession = createVisitorSession;
6
+ const zod_1 = require("zod");
7
+ exports.visitorSessionSchema = zod_1.z.object({
8
+ visitorToken: zod_1.z.string().min(1),
9
+ expiresAt: zod_1.z.string().datetime(),
10
+ visitor: zod_1.z.object({ name: zod_1.z.string().nullable(), emailMasked: zod_1.z.string().nullable() }),
11
+ });
12
+ const stores = new WeakMap();
13
+ function createMemoryVisitorStore() {
14
+ const values = new Map();
15
+ return {
16
+ get: (key) => values.get(key) ?? null,
17
+ set: (key, value) => {
18
+ if (value === null)
19
+ values.delete(key);
20
+ else
21
+ values.set(key, value);
22
+ },
23
+ };
24
+ }
25
+ function createVisitorSession(options) {
26
+ const { store, token, exchange } = options;
27
+ const storageKey = `tsch:visitor:${options.key}`;
28
+ let scopes = stores.get(store);
29
+ if (scopes === undefined) {
30
+ scopes = new Map();
31
+ stores.set(store, scopes);
32
+ }
33
+ const previous = scopes.get(options.scope);
34
+ const entry = previous?.entry.token === token ? previous.entry : { token, pending: null, clear: Promise.resolve(true) };
35
+ const changed = previous?.entry !== entry;
36
+ const state = previous ?? { entry, writes: Promise.resolve(true) };
37
+ const write = (value) => {
38
+ // Serialize adapter writes so a late exchange cannot restore a logged-out bearer.
39
+ state.writes = state.writes
40
+ .then(async () => {
41
+ if (state.entry !== entry)
42
+ return true;
43
+ await store.set(storageKey, value);
44
+ return true;
45
+ })
46
+ .catch(() => false);
47
+ return state.writes;
48
+ };
49
+ state.entry = entry;
50
+ scopes.set(options.scope, state);
51
+ if (changed)
52
+ entry.clear = write(null);
53
+ async function acquire() {
54
+ if (!(await entry.clear))
55
+ return { ok: false, code: "NETWORK_ERROR" };
56
+ if (state.entry !== entry)
57
+ return { ok: false, code: "SSO_REJECTED" };
58
+ if (token === null)
59
+ return { ok: true, body: null };
60
+ const result = await exchange();
61
+ if (!result.ok)
62
+ return result;
63
+ if (state.entry !== entry)
64
+ return { ok: false, code: "SSO_REJECTED" };
65
+ return (await write(result.body)) ? result : { ok: false, code: "NETWORK_ERROR" };
66
+ }
67
+ return {
68
+ get() {
69
+ if (state.entry !== entry)
70
+ return Promise.resolve({ ok: false, code: "SSO_REJECTED" });
71
+ entry.pending ?? (entry.pending = acquire().then((result) => {
72
+ if (!result.ok)
73
+ entry.pending = null;
74
+ return result;
75
+ }));
76
+ return entry.pending;
77
+ },
78
+ async invalidate(rejected) {
79
+ if (state.entry !== entry)
80
+ return;
81
+ if ((await store.get(storageKey)) !== rejected)
82
+ return;
83
+ entry.pending = null;
84
+ entry.clear = write(null);
85
+ await entry.clear;
86
+ },
87
+ };
88
+ }
@@ -401,6 +401,9 @@ export declare const errorCodeSchema: z.ZodEnum<{
401
401
  NETWORK_ERROR: "NETWORK_ERROR";
402
402
  HTTP_ERROR: "HTTP_ERROR";
403
403
  INVALID_RESPONSE: "INVALID_RESPONSE";
404
+ SSO_DISABLED: "SSO_DISABLED";
405
+ SSO_REJECTED: "SSO_REJECTED";
406
+ VISITOR_INVALID: "VISITOR_INVALID";
404
407
  }>;
405
408
  export type ErrorCode = z.infer<typeof errorCodeSchema>;
406
409
  export type Failure = Readonly<{
@@ -419,6 +422,11 @@ export type Voter = Readonly<{
419
422
  export type User = Readonly<{
420
423
  userId?: string;
421
424
  name?: string;
425
+ ssoToken?: string;
426
+ }>;
427
+ export type VisitorTokenStore = Readonly<{
428
+ get: (key: string) => Promise<string | null> | string | null;
429
+ set: (key: string, value: string | null) => Promise<void> | void;
422
430
  }>;
423
431
  export type ClientInfo = Readonly<{
424
432
  platform: Platform;
@@ -159,6 +159,9 @@ exports.errorCodeSchema = zod_1.z.enum([
159
159
  "NETWORK_ERROR",
160
160
  "HTTP_ERROR",
161
161
  "INVALID_RESPONSE",
162
+ "SSO_DISABLED",
163
+ "SSO_REJECTED",
164
+ "VISITOR_INVALID",
162
165
  ]);
163
166
  exports.stateSchema = zod_1.z
164
167
  .object({
package/dist/index.d.ts CHANGED
@@ -5,6 +5,7 @@ export * from "./core/decide";
5
5
  export * from "./core/cache";
6
6
  export * from "./core/versions";
7
7
  export * from "./core/rating";
8
+ export { createMemoryVisitorStore } from "./core/sso";
8
9
  export { ChangesProvider } from "./web/Provider";
9
10
  export type { ChangesProviderProps } from "./web/Provider";
10
11
  export { useChanges, ChangesProviderMissingError } from "./web/useChanges";
package/dist/index.js CHANGED
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.DEFAULT_TEXTS = exports.localStorageAdapter = exports.Blocks = exports.CommentsThread = exports.ReleaseCard = exports.ChangelogDialog = exports.ChangelogList = exports.ChangelogButton = exports.WhatsNewModal = exports.ChangesProviderMissingError = exports.useChanges = exports.ChangesProvider = void 0;
17
+ exports.DEFAULT_TEXTS = exports.localStorageAdapter = exports.Blocks = exports.CommentsThread = exports.ReleaseCard = exports.ChangelogDialog = exports.ChangelogList = exports.ChangelogButton = exports.WhatsNewModal = exports.ChangesProviderMissingError = exports.useChanges = exports.ChangesProvider = exports.createMemoryVisitorStore = void 0;
18
18
  __exportStar(require("./core/types"), exports);
19
19
  __exportStar(require("./core/client"), exports);
20
20
  __exportStar(require("./core/storage"), exports);
@@ -22,6 +22,8 @@ __exportStar(require("./core/decide"), exports);
22
22
  __exportStar(require("./core/cache"), exports);
23
23
  __exportStar(require("./core/versions"), exports);
24
24
  __exportStar(require("./core/rating"), exports);
25
+ var sso_1 = require("./core/sso");
26
+ Object.defineProperty(exports, "createMemoryVisitorStore", { enumerable: true, get: function () { return sso_1.createMemoryVisitorStore; } });
25
27
  var Provider_1 = require("./web/Provider");
26
28
  Object.defineProperty(exports, "ChangesProvider", { enumerable: true, get: function () { return Provider_1.ChangesProvider; } });
27
29
  var useChanges_1 = require("./web/useChanges");
@@ -7,7 +7,7 @@ import type { ColorScheme } from "./theme";
7
7
  export type ChangesProviderProps = Readonly<{
8
8
  changesKey: string;
9
9
  appVersion?: string;
10
- user?: User;
10
+ user?: User | null;
11
11
  locale?: LocalePreference;
12
12
  baseUrl?: string;
13
13
  storage?: ChangesStorage;
@@ -6,6 +6,7 @@ const react_1 = require("react");
6
6
  const client_1 = require("../core/client");
7
7
  const decide_1 = require("../core/decide");
8
8
  const storage_1 = require("../core/storage");
9
+ const sso_1 = require("../core/sso");
9
10
  const ChangelogDialog_1 = require("./ChangelogDialog");
10
11
  const context_1 = require("./context");
11
12
  const controls_css_1 = require("./controls-css");
@@ -34,6 +35,8 @@ function ChangesProvider(props) {
34
35
  const { autoPresent = true, colorScheme = "auto", children } = props;
35
36
  const userId = props.user?.userId;
36
37
  const userName = props.user?.name;
38
+ const ssoToken = props.user?.ssoToken;
39
+ const [visitorStore] = (0, react_1.useState)(sso_1.createMemoryVisitorStore);
37
40
  const [model, setModel] = (0, react_1.useState)(() => (0, model_1.initialModel)(locale === "auto" ? "ko" : locale));
38
41
  const injected = (0, react_1.useRef)({ storage: props.storage, fetchImpl: props.fetchImpl, onError: props.onError });
39
42
  (0, react_1.useEffect)(() => {
@@ -42,12 +45,17 @@ function ChangesProvider(props) {
42
45
  const start = (0, react_1.useCallback)(async (guard) => {
43
46
  const { storage: given, fetchImpl, onError } = injected.current;
44
47
  const storage = given ?? (0, storage_2.localStorageAdapter)();
45
- const user = { ...(userId ? { userId } : {}), ...(userName ? { name: userName } : {}) };
48
+ const user = {
49
+ ...(userId ? { userId } : {}),
50
+ ...(userName ? { name: userName } : {}),
51
+ ...(ssoToken === undefined ? {} : { ssoToken }),
52
+ };
46
53
  const client = (0, client_1.createChangesClient)({
47
54
  key: changesKey,
48
55
  platform: "web",
49
56
  fetchImpl: fetchImpl ?? browserFetch,
50
57
  user,
58
+ visitorStore,
51
59
  ...(baseUrl ? { baseUrl } : {}),
52
60
  ...(appVersion ? { appVersion } : {}),
53
61
  });
@@ -69,7 +77,7 @@ function ChangesProvider(props) {
69
77
  setModel((current) => ({ ...current, ...loaded, overrides: {}, runtime }));
70
78
  if (loaded.error !== null)
71
79
  onError?.(loaded.error);
72
- }, [changesKey, baseUrl, appVersion, userId, userName, locale, showOnFirstLaunch, forceShow]);
80
+ }, [changesKey, baseUrl, appVersion, userId, userName, ssoToken, visitorStore, locale, showOnFirstLaunch, forceShow]);
73
81
  (0, react_1.useEffect)(() => {
74
82
  const guard = { active: true };
75
83
  void start(guard);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@the-seeker/changes-react",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "files": [
@@ -20,13 +20,14 @@
20
20
  "zod": "^4"
21
21
  },
22
22
  "devDependencies": {
23
- "typescript": "^5",
24
- "vitest": "^5.1.1",
23
+ "@types/node": "^24.19.4",
25
24
  "@types/react": "^19",
26
25
  "@types/react-dom": "^19",
26
+ "jsdom": "^29",
27
27
  "react": "19.2.3",
28
28
  "react-dom": "19.2.3",
29
- "jsdom": "^29"
29
+ "typescript": "^5",
30
+ "vitest": "^5.1.1"
30
31
  },
31
32
  "scripts": {
32
33
  "build": "tsc -p tsconfig.build.json",