Skip to content

Commit 03e0e9a

Browse files
committed
✨ Enable to get CSRF token from window._csrf if exists
あとfetchをgetProfileに変えた
1 parent 85d31eb commit 03e0e9a

File tree

2 files changed

+15
-16
lines changed

2 files changed

+15
-16
lines changed

rest/page-data.ts

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,11 +48,7 @@ export async function importPages(
4848
);
4949
formData.append("name", "undefined");
5050

51-
if (!csrf) {
52-
const result = await getCSRFToken(sid);
53-
if (!result.ok) return result;
54-
csrf = result.value;
55-
}
51+
csrf ??= await getCSRFToken(sid);
5652

5753
const path = `https://scrapbox.io/api/page-data/import/${project}.json`;
5854
const res = await fetch(

rest/utils.ts

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,12 @@
11
import type { ErrorLike } from "../deps/scrapbox.ts";
2+
import { getProfile } from "./profile.ts";
3+
4+
// scrapbox.io内なら`window._csrf`にCSRF tokenが入っている
5+
declare global {
6+
interface Window {
7+
__csrf?: string;
8+
}
9+
}
210

311
/** HTTP headerのCookieに入れる文字列を作る
412
*
@@ -12,17 +20,12 @@ export type Result<T, E> = { ok: true; value: T } | { ok: false; value: E };
1220
* @param sid - connect.sidに入っている文字列。不正な文字列を入れてもCSRF tokenを取得できるみたい
1321
*/
1422
export async function getCSRFToken(
15-
sid: string,
16-
): Promise<Result<string, ErrorLike>> {
17-
const res = await fetch("https://scrapbox.io/api/users/me", {
18-
headers: { Cookie: cookie(sid) },
19-
});
20-
if (!res.ok) {
21-
const value = (await res.json()) as ErrorLike;
22-
return { ok: false, value };
23-
}
24-
const { csrfToken } = (await res.json()) as { csrfToken: string };
25-
return { ok: true, value: csrfToken };
23+
sid?: string,
24+
): Promise<string> {
25+
if (window.__csrf) return window.__csrf;
26+
27+
const user = await getProfile(sid ? { sid } : undefined);
28+
return user.csrfToken;
2629
}
2730

2831
// cf. https://blog.uhy.ooo/entry/2021-04-09/typescript-is-any-as/#%E3%83%A6%E3%83%BC%E3%82%B6%E3%83%BC%E5%AE%9A%E7%BE%A9%E5%9E%8B%E3%82%AC%E3%83%BC%E3%83%89%E3%81%AE%E5%BC%95%E6%95%B0%E3%81%AE%E5%9E%8B%E3%82%92%E3%81%A9%E3%81%86%E3%81%99%E3%82%8B%E3%81%8B

0 commit comments

Comments
 (0)