@0xchain/token 1.1.0-beta.61 → 1.1.0-beta.63

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.
@@ -0,0 +1,12 @@
1
+ /**
2
+ * 计算写 cookie 时的 secure 属性。
3
+ *
4
+ * 关键点:客户端(浏览器)以当前页面协议为准——https 页面就必须写 secure cookie,
5
+ * 否则会与服务端写入的 secure 同名 cookie 冲突,导航/刷新后客户端读不到。
6
+ * 这能让本地通过 https 代理调试时与线上行为一致。
7
+ *
8
+ * 服务端(无 window)无法感知页面协议,沿用 NODE_ENV==='production' 判断,
9
+ * 与既有线上行为保持一致。
10
+ */
11
+ export declare function resolveCookieSecure(): boolean;
12
+ //# sourceMappingURL=cookieSecure.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cookieSecure.d.ts","sourceRoot":"","sources":["../src/cookieSecure.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,wBAAgB,mBAAmB,IAAI,OAAO,CAU7C"}
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Cookie 唯一真相源。
3
+ *
4
+ * 设计原则:domain / path / sameSite / secure 这套属性只在这里定义一次,
5
+ * set / get / remove 全部基于同一套属性。这样可以从机制上杜绝
6
+ * “写入带 secure、删除不带 secure 导致删不掉”这类属性漂移引发的
7
+ * cookie 时有时无问题。
8
+ */
9
+ export declare const COOKIE_DOMAIN = ".ichatgo.ai";
10
+ export declare const COOKIE_PATH = "/";
11
+ export declare const COOKIE_SAME_SITE: "lax";
12
+ export declare const REFRESH_TOKEN_COOKIE_DAYS = 7;
13
+ export declare const DEFAULT_ACCESS_TOKEN_TTL_SECONDS = 3600;
14
+ /** js-cookie:number 表示「天数」,须用 Date 表示绝对过期时间 */
15
+ export declare function expiresFromSeconds(seconds: number): Date;
16
+ export declare const cookieStore: {
17
+ get(key: string): string;
18
+ set(key: string, value: string, expires: Date | number): void;
19
+ /**
20
+ * 删除必须与写入属性完全一致(domain/path/sameSite/secure),
21
+ * 否则浏览器无法命中目标 cookie,删除会“静默失败”。
22
+ */
23
+ remove(key: string): void;
24
+ };
25
+ //# sourceMappingURL=cookieStore.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cookieStore.d.ts","sourceRoot":"","sources":["../src/cookieStore.ts"],"names":[],"mappings":"AAGA;;;;;;;GAOG;AACH,eAAO,MAAM,aAAa,gBAAgB,CAAA;AAC1C,eAAO,MAAM,WAAW,MAAM,CAAA;AAC9B,eAAO,MAAM,gBAAgB,EAAG,KAAc,CAAA;AAE9C,eAAO,MAAM,yBAAyB,IAAI,CAAA;AAC1C,eAAO,MAAM,gCAAgC,OAAO,CAAA;AAYpD,+CAA+C;AAC/C,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAExD;AAED,eAAO,MAAM,WAAW;aACb,MAAM,GAAG,MAAM;aAGf,MAAM,SAAS,MAAM,WAAW,IAAI,GAAG,MAAM,GAAG,IAAI;IAG7D;;;OAGG;gBACS,MAAM,GAAG,IAAI;CAG1B,CAAA"}
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { NextResponse } from 'next/server';
2
2
  import { ITokenManager, ITokenManagerResponse } from './type';
3
+ export { decodeJwtPayload, isJwtExpired } from './jwt';
3
4
  /**
4
5
  * 设置|更新token到cookie
5
6
  * @param response NextResponse
@@ -11,6 +12,7 @@ export declare const getToken: (key?: string) => string;
11
12
  /** 兼容 OAuth 直出与 { data: token } 包装 */
12
13
  export declare function normalizeTokenPayload(res: unknown): ITokenManagerResponse | null;
13
14
  export declare const removeAllToken: () => void;
15
+ export declare const removeTokenByKey: (key?: string) => void;
14
16
  export declare const isTokenExpired: () => Promise<boolean>;
15
17
  declare const TokenManager: ITokenManager;
16
18
  export default TokenManager;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE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.js CHANGED
@@ -1,86 +1,160 @@
1
1
  import Cookies from "js-cookie";
2
+ function resolveCookieSecure() {
3
+ if (typeof window !== "undefined" && window.location) {
4
+ return window.location.protocol === "https:";
5
+ }
6
+ const authUrl = process.env.NEXT_PUBLIC_AUTH_URL || "";
7
+ const appUrl = process.env.NEXT_PUBLIC_APP_URL || "";
8
+ if (authUrl.startsWith("https://") || appUrl.startsWith("https://")) {
9
+ return true;
10
+ }
11
+ return process.env.NODE_ENV === "production";
12
+ }
2
13
  const COOKIE_DOMAIN = ".ichatgo.ai";
3
14
  const COOKIE_PATH = "/";
4
15
  const COOKIE_SAME_SITE = "lax";
5
- const COOKIE_SECURE = process.env.NODE_ENV === "production";
6
16
  const REFRESH_TOKEN_COOKIE_DAYS = 7;
17
+ const DEFAULT_ACCESS_TOKEN_TTL_SECONDS = 3600;
18
+ function baseAttributes() {
19
+ return {
20
+ domain: COOKIE_DOMAIN,
21
+ path: COOKIE_PATH,
22
+ sameSite: COOKIE_SAME_SITE,
23
+ secure: resolveCookieSecure()
24
+ };
25
+ }
7
26
  function expiresFromSeconds(seconds) {
8
27
  return new Date(Date.now() + Math.max(seconds, 0) * 1e3);
9
28
  }
29
+ const cookieStore = {
30
+ get(key) {
31
+ return Cookies.get(key) || "";
32
+ },
33
+ set(key, value, expires) {
34
+ Cookies.set(key, value, { ...baseAttributes(), expires });
35
+ },
36
+ /**
37
+ * 删除必须与写入属性完全一致(domain/path/sameSite/secure),
38
+ * 否则浏览器无法命中目标 cookie,删除会“静默失败”。
39
+ */
40
+ remove(key) {
41
+ Cookies.remove(key, baseAttributes());
42
+ }
43
+ };
44
+ function base64UrlDecode(input) {
45
+ const normalized = input.replace(/-/g, "+").replace(/_/g, "/");
46
+ const padLength = (4 - normalized.length % 4) % 4;
47
+ const padded = normalized + "=".repeat(padLength);
48
+ if (typeof atob === "function") {
49
+ const binary = atob(padded);
50
+ const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
51
+ return new TextDecoder().decode(bytes);
52
+ }
53
+ return Buffer.from(padded, "base64").toString("utf8");
54
+ }
55
+ function decodeJwtPayload(token) {
56
+ if (!token) return null;
57
+ const parts = token.split(".");
58
+ if (parts.length < 2) return null;
59
+ try {
60
+ const payloadJson = base64UrlDecode(parts[1]);
61
+ return JSON.parse(payloadJson);
62
+ } catch {
63
+ return null;
64
+ }
65
+ }
66
+ function getJwtExpiryMs(token) {
67
+ const payload = decodeJwtPayload(token);
68
+ if (typeof payload?.exp === "number") {
69
+ return payload.exp * 1e3;
70
+ }
71
+ return void 0;
72
+ }
73
+ function isJwtExpired(payload, options) {
74
+ if (!payload?.exp) return false;
75
+ const skew = options?.skewSeconds ?? 15;
76
+ const now = Math.floor(Date.now() / 1e3);
77
+ return payload.exp <= now + skew;
78
+ }
10
79
  const cookieSetToken = (data) => {
11
- const expiresIn = data?.expires_in ?? 3600;
80
+ const nextAccessToken = data?.access_token || getToken("access_token");
81
+ const nextRefreshToken = data?.refresh_token || getToken("refresh_token");
82
+ const nextIdToken = data?.id_token || getToken("id_token");
83
+ if (!nextAccessToken) {
84
+ return;
85
+ }
86
+ const expiresIn = data?.expires_in ?? DEFAULT_ACCESS_TOKEN_TTL_SECONDS;
12
87
  const accessExpires = expiresFromSeconds(expiresIn);
13
- Cookies.set("access_token", data?.access_token, {
14
- expires: accessExpires,
15
- domain: COOKIE_DOMAIN,
16
- sameSite: COOKIE_SAME_SITE,
17
- secure: COOKIE_SECURE,
18
- path: COOKIE_PATH
19
- });
20
- Cookies.set("refresh_token", data?.refresh_token, {
21
- expires: REFRESH_TOKEN_COOKIE_DAYS,
22
- domain: COOKIE_DOMAIN,
23
- sameSite: COOKIE_SAME_SITE,
24
- secure: COOKIE_SECURE,
25
- path: COOKIE_PATH
26
- });
27
- Cookies.set("id_token", data?.id_token, {
28
- expires: accessExpires,
29
- domain: COOKIE_DOMAIN,
30
- sameSite: COOKIE_SAME_SITE,
31
- secure: COOKIE_SECURE,
32
- path: COOKIE_PATH
33
- });
34
- Cookies.set("token_expire", (Date.now() + expiresIn * 1e3).toString(), {
35
- expires: accessExpires,
36
- domain: COOKIE_DOMAIN,
37
- sameSite: COOKIE_SAME_SITE,
38
- secure: COOKIE_SECURE,
39
- path: COOKIE_PATH
40
- });
88
+ cookieStore.set("access_token", nextAccessToken, accessExpires);
89
+ if (nextRefreshToken) {
90
+ cookieStore.set("refresh_token", nextRefreshToken, REFRESH_TOKEN_COOKIE_DAYS);
91
+ }
92
+ if (nextIdToken) {
93
+ cookieStore.set("id_token", nextIdToken, accessExpires);
94
+ }
95
+ cookieStore.set(
96
+ "token_expire",
97
+ (Date.now() + expiresIn * 1e3).toString(),
98
+ accessExpires
99
+ );
41
100
  };
42
101
  const setToken = (res, response) => {
43
102
  if (!response) {
44
103
  cookieSetToken(res);
45
104
  return null;
46
- } else {
47
- response.cookies.set("access_token", res?.access_token, {
48
- httpOnly: false,
49
- maxAge: res?.expires_in,
50
- domain: COOKIE_DOMAIN,
51
- sameSite: COOKIE_SAME_SITE,
52
- secure: COOKIE_SECURE,
53
- path: COOKIE_PATH
54
- });
55
- response.cookies.set("refresh_token", res?.refresh_token, {
105
+ }
106
+ const nextAccessToken = res?.access_token;
107
+ const nextRefreshToken = res?.refresh_token;
108
+ const nextIdToken = res?.id_token;
109
+ const expiresIn = typeof res?.expires_in === "number" && res.expires_in > 0 ? res.expires_in : DEFAULT_ACCESS_TOKEN_TTL_SECONDS;
110
+ if (!nextAccessToken) {
111
+ return response;
112
+ }
113
+ const secure = resolveCookieSecure();
114
+ response.cookies.set("access_token", nextAccessToken, {
115
+ httpOnly: false,
116
+ maxAge: expiresIn,
117
+ domain: COOKIE_DOMAIN,
118
+ sameSite: COOKIE_SAME_SITE,
119
+ secure,
120
+ path: COOKIE_PATH
121
+ });
122
+ if (nextRefreshToken) {
123
+ response.cookies.set("refresh_token", nextRefreshToken, {
56
124
  httpOnly: false,
57
- maxAge: 60 * 60 * 24 * 7,
125
+ maxAge: 60 * 60 * 24 * REFRESH_TOKEN_COOKIE_DAYS,
58
126
  domain: COOKIE_DOMAIN,
59
127
  sameSite: COOKIE_SAME_SITE,
60
- secure: COOKIE_SECURE,
128
+ secure,
61
129
  path: COOKIE_PATH
62
130
  });
63
- response.cookies.set("id_token", res?.id_token, {
131
+ }
132
+ if (nextIdToken) {
133
+ response.cookies.set("id_token", nextIdToken, {
64
134
  httpOnly: false,
65
- maxAge: res?.expires_in,
135
+ maxAge: expiresIn,
66
136
  domain: COOKIE_DOMAIN,
67
137
  sameSite: COOKIE_SAME_SITE,
68
- secure: COOKIE_SECURE,
138
+ secure,
69
139
  path: COOKIE_PATH
70
140
  });
71
- response.cookies.set("token_expire", (Date.now() + res?.expires_in * 1e3).toString(), {
141
+ }
142
+ response.cookies.set(
143
+ "token_expire",
144
+ (Date.now() + expiresIn * 1e3).toString(),
145
+ {
72
146
  httpOnly: false,
73
- maxAge: res?.expires_in,
147
+ maxAge: expiresIn,
74
148
  domain: COOKIE_DOMAIN,
75
149
  sameSite: COOKIE_SAME_SITE,
76
- secure: COOKIE_SECURE,
150
+ secure,
77
151
  path: COOKIE_PATH
78
- });
79
- }
152
+ }
153
+ );
80
154
  return response;
81
155
  };
82
156
  const getToken = (key) => {
83
- return Cookies.get(key || "id_token") || "";
157
+ return cookieStore.get(key || "id_token");
84
158
  };
85
159
  function normalizeTokenPayload(res) {
86
160
  if (!res || typeof res !== "object") return null;
@@ -98,14 +172,14 @@ function normalizeTokenPayload(res) {
98
172
  return null;
99
173
  }
100
174
  const removeAllToken = () => {
101
- Cookies.remove("id_token", { path: COOKIE_PATH, domain: COOKIE_DOMAIN });
102
- Cookies.remove("access_token", { path: COOKIE_PATH, domain: COOKIE_DOMAIN });
103
- Cookies.remove("refresh_token", { path: COOKIE_PATH, domain: COOKIE_DOMAIN });
104
- Cookies.remove(`sign_session`, { domain: COOKIE_DOMAIN });
105
- Cookies.remove("token_expire", { path: COOKIE_PATH, domain: COOKIE_DOMAIN });
175
+ cookieStore.remove("id_token");
176
+ cookieStore.remove("access_token");
177
+ cookieStore.remove("refresh_token");
178
+ cookieStore.remove("sign_session");
179
+ cookieStore.remove("token_expire");
106
180
  };
107
181
  const removeTokenByKey = (key) => {
108
- Cookies.remove(key || "id_token", { path: COOKIE_PATH, domain: COOKIE_DOMAIN });
182
+ cookieStore.remove(key || "id_token");
109
183
  };
110
184
  const isTokenExpired = async () => {
111
185
  let t;
@@ -114,26 +188,30 @@ const isTokenExpired = async () => {
114
188
  if (typeof window === "undefined") {
115
189
  try {
116
190
  const { cookies } = await import("next/headers");
117
- const cookieStore = await cookies();
118
- const tokenExpire = cookieStore.get("token_expire")?.value;
119
- refreshToken = cookieStore.get("refresh_token")?.value;
120
- accessToken = cookieStore.get("access_token")?.value;
191
+ const nextCookies = await cookies();
192
+ const tokenExpire = nextCookies.get("token_expire")?.value;
193
+ refreshToken = nextCookies.get("refresh_token")?.value;
194
+ accessToken = nextCookies.get("access_token")?.value;
121
195
  t = tokenExpire ? Number(tokenExpire) : void 0;
122
196
  } catch {
123
197
  return false;
124
198
  }
125
199
  } else {
126
- const rawExpire = Cookies.get("token_expire");
200
+ const rawExpire = cookieStore.get("token_expire");
127
201
  t = rawExpire ? Number(rawExpire) : void 0;
128
- refreshToken = Cookies.get("refresh_token");
129
- accessToken = Cookies.get("access_token");
202
+ refreshToken = cookieStore.get("refresh_token");
203
+ accessToken = cookieStore.get("access_token");
130
204
  }
131
205
  const nearExpiry = (expireAt) => expireAt - Date.now() < 5 * 60 * 1e3;
132
206
  if (accessToken) {
207
+ const jwtExpiry = getJwtExpiryMs(accessToken);
208
+ if (jwtExpiry) {
209
+ return nearExpiry(jwtExpiry);
210
+ }
133
211
  if (t && !Number.isNaN(t)) {
134
212
  return nearExpiry(t);
135
213
  }
136
- return false;
214
+ return Boolean(refreshToken);
137
215
  }
138
216
  if (refreshToken) {
139
217
  return true;
@@ -151,10 +229,13 @@ const TokenManager = {
151
229
  isTokenExpired
152
230
  };
153
231
  export {
232
+ decodeJwtPayload,
154
233
  TokenManager as default,
155
234
  getToken,
235
+ isJwtExpired,
156
236
  isTokenExpired,
157
237
  normalizeTokenPayload,
158
238
  removeAllToken,
239
+ removeTokenByKey,
159
240
  setToken
160
241
  };
package/dist/jwt.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ export type JwtPayload = Record<string, unknown> & {
2
+ exp?: number;
3
+ };
4
+ export declare function decodeJwtPayload(token?: string | null): JwtPayload | null;
5
+ /** JWT exp 字段转毫秒时间戳;无法解析时返回 undefined */
6
+ export declare function getJwtExpiryMs(token?: string | null): number | undefined;
7
+ export declare function isJwtExpired(payload: JwtPayload | null, options?: {
8
+ skewSeconds?: number;
9
+ }): boolean;
10
+ //# sourceMappingURL=jwt.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jwt.d.ts","sourceRoot":"","sources":["../src/jwt.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG;IACjD,GAAG,CAAC,EAAE,MAAM,CAAC;CACd,CAAC;AAeF,wBAAgB,gBAAgB,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,UAAU,GAAG,IAAI,CAUzE;AAED,yCAAyC;AACzC,wBAAgB,cAAc,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM,GAAG,SAAS,CAMxE;AAED,wBAAgB,YAAY,CAC1B,OAAO,EAAE,UAAU,GAAG,IAAI,EAC1B,OAAO,CAAC,EAAE;IAAE,WAAW,CAAC,EAAE,MAAM,CAAA;CAAE,GACjC,OAAO,CAKT"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0xchain/token",
3
- "version": "1.1.0-beta.61",
3
+ "version": "1.1.0-beta.63",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",