summaryrefslogtreecommitdiff
path: root/app/routes/home.tsx
blob: 9bea992b4c6ca6847785906d651c5320a7973c8f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import { useEffect, useRef, useState } from "react";
import { Form, redirect, useNavigation } from "react-router";
import type { Route } from "./+types/home";
import { createPost, deletePost, listPosts, listCredentials } from "~/lib/db.server";
import { renderMarkdown } from "~/lib/md.server";
import { getSession, commitSession } from "~/lib/session.server";

export async function loader({ request }: Route.LoaderArgs) {
  const session = await getSession(request.headers.get("Cookie"));
  const isAuthenticated = session.get("authenticated") === true;
  const hasCredentials = listCredentials().length > 0;
  const posts = listPosts();
  return {
    posts: posts.map((p) => ({ ...p, html: renderMarkdown(p.content) })),
    isAuthenticated,
    hasCredentials,
  };
}

export async function action({ request }: Route.ActionArgs) {
  const session = await getSession(request.headers.get("Cookie"));
  if (session.get("authenticated") !== true) {
    throw new Response("Unauthorized", { status: 401 });
  }

  const form = await request.formData();
  const intent = String(form.get("intent") ?? "create");

  if (intent === "delete") {
    const id = String(form.get("id") ?? "");
    if (id) deletePost(id);
    return redirect("/", {
      headers: { "Set-Cookie": await commitSession(session) },
    });
  }

  const content = String(form.get("content") ?? "").trim();
  if (!content) return { error: "内容を入力してください", content };
  if (content.length > 10000) return { error: "投稿が長すぎます(最大10,000文字)", content };

  createPost({ id: crypto.randomUUID(), content });
  return redirect("/", {
    headers: { "Set-Cookie": await commitSession(session) },
  });
}

function bufferToB64url(buf: ArrayBuffer): string {
  const bytes = new Uint8Array(buf);
  let binary = "";
  for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
  return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
}

function b64urlToBuffer(b64url: string): ArrayBuffer {
  const base64 = b64url.replace(/-/g, "+").replace(/_/g, "/");
  const pad = "=".repeat((4 - (base64.length % 4)) % 4);
  const binary = atob(base64 + pad);
  const bytes = new Uint8Array(binary.length);
  for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
  return bytes.buffer;
}

export default function Home({ loaderData, actionData }: Route.ComponentProps) {
  const { posts, isAuthenticated, hasCredentials } = loaderData;
  const navigation = useNavigation();
  const isSubmitting = navigation.state === "submitting";
  const formRef = useRef<HTMLFormElement>(null);
  const wasSubmitting = useRef(false);
  const [loginStatus, setLoginStatus] = useState<"idle" | "loading" | "error">("idle");
  const [loginError, setLoginError] = useState("");

  async function handleLogin() {
    setLoginStatus("loading");
    setLoginError("");
    try {
      const optRes = await fetch("/api/passkey?intent=login-options", { method: "POST" });
      if (!optRes.ok) throw new Error("オプション取得に失敗しました");
      const options = await optRes.json();

      const credential = await navigator.credentials.get({
        publicKey: {
          challenge: b64urlToBuffer(options.challenge as string),
          rpId: options.rpId as string,
          allowCredentials: (options.allowCredentials as Array<{ id: string; transports?: string[] }> ?? []).map((c) => ({
            id: b64urlToBuffer(c.id),
            type: "public-key" as const,
            transports: c.transports as AuthenticatorTransport[] | undefined,
          })),
          userVerification: "required" as UserVerificationRequirement,
          timeout: 60000,
        },
      }) as PublicKeyCredential | null;

      if (!credential) throw new Error("認証に失敗しました");

      const assertion = credential.response as AuthenticatorAssertionResponse;
      const verRes = await fetch("/api/passkey?intent=login-verify", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          id: credential.id,
          rawId: bufferToB64url(credential.rawId),
          response: {
            clientDataJSON: bufferToB64url(assertion.clientDataJSON),
            authenticatorData: bufferToB64url(assertion.authenticatorData),
            signature: bufferToB64url(assertion.signature),
            userHandle: assertion.userHandle ? bufferToB64url(assertion.userHandle) : undefined,
          },
          authenticatorAttachment: credential.authenticatorAttachment ?? undefined,
          clientExtensionResults: credential.getClientExtensionResults(),
          type: "public-key",
        }),
      });
      if (!verRes.ok) {
        const err = await verRes.json();
        throw new Error(err.error ?? "認証に失敗しました");
      }

      window.location.href = "/";
    } catch (e) {
      setLoginStatus("error");
      setLoginError(e instanceof Error ? e.message : "エラーが発生しました");
    }
  }

  useEffect(() => {
    if (navigation.state === "submitting") wasSubmitting.current = true;
    if (wasSubmitting.current && navigation.state === "idle" && !actionData?.error) {
      formRef.current?.reset();
      wasSubmitting.current = false;
    }
  }, [navigation.state, actionData?.error]);

  return (
    <div className="wrap">
      <header className="site-header">
        <h1>log</h1>
        <nav className="header-nav">
          {isAuthenticated ? (
            <Form method="post" action="/auth/logout">
              <button type="submit" className="logout-btn">ログアウト</button>
            </Form>
          ) : hasCredentials ? (
            <>
              <button className="auth-link" onClick={handleLogin} disabled={loginStatus === "loading"}>
                {loginStatus === "loading" ? "認証中…" : "ログイン"}
              </button>
              {loginStatus === "error" && (
                <span className="error-msg" style={{ marginLeft: ".5rem", fontSize: ".85em" }}>{loginError}</span>
              )}
            </>
          ) : (
            <a href="/auth/register" className="auth-link">登録</a>
          )}
        </nav>
      </header>

      {isAuthenticated && (
        <div className="compose">
          <Form method="post" ref={formRef}>
            <input type="hidden" name="intent" value="create" />
            <textarea
              name="content"
              placeholder="Markdown で投稿..."
              rows={4}
              defaultValue={actionData?.content ?? ""}
              autoFocus
            />
            {actionData?.error && (
              <p className="error-msg">{actionData.error}</p>
            )}
            <div className="compose-row">
              <span className="hint">markdown</span>
              <button type="submit" disabled={isSubmitting}>
                {isSubmitting ? "投稿中…" : "投稿"}
              </button>
            </div>
          </Form>
        </div>
      )}

      <div className="feed">
        {posts.length === 0 && (
          <p className="empty">まだ投稿がありません</p>
        )}
        {posts.map((post) => (
          <article key={post.id} className="post">
            <div className="post-header">
              <time className="post-meta" dateTime={post.created_at + "Z"}>
                {formatDate(post.created_at)}
              </time>
              {isAuthenticated && (
                <Form method="post">
                  <input type="hidden" name="intent" value="delete" />
                  <input type="hidden" name="id" value={post.id} />
                  <button
                    type="submit"
                    className="delete-btn"
                    onClick={(e) => {
                      if (!confirm("この投稿を削除しますか?")) e.preventDefault();
                    }}
                  >
                    削除
                  </button>
                </Form>
              )}
            </div>
            <div
              className="prose"
              dangerouslySetInnerHTML={{ __html: post.html }}
            />
          </article>
        ))}
      </div>
    </div>
  );
}

function formatDate(isoUtc: string): string {
  return new Date(isoUtc + "Z").toLocaleString("ja-JP", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    timeZone: "Asia/Tokyo",
  });
}