summaryrefslogtreecommitdiff
path: root/app/routes/auth.register.tsx
blob: 7d8fb5d86d74801a6e4d5e4d3ec9ca9d98bfa2cf (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
229
230
231
232
import { useState } from "react";
import { redirect } from "react-router";
import {
  generateRegistrationOptions,
  verifyRegistrationResponse,
  type RegistrationResponseJSON,
  type AuthenticatorTransportFuture,
} from "@simplewebauthn/server";
import type { Route } from "./+types/auth.register";
import { getSession, commitSession } from "~/lib/session.server";
import { saveCredential } from "~/lib/db.server";
import { rpID, rpName, origin } from "~/lib/passkey.server";

export async function loader({ request }: Route.LoaderArgs) {
  const session = await getSession(request.headers.get("Cookie"));
  if (session.get("authenticated")) return redirect("/");
  return {};
}

export async function action({ request }: Route.ActionArgs) {
  const url = new URL(request.url);
  const intent = url.searchParams.get("intent");
  const session = await getSession(request.headers.get("Cookie"));

  if (intent === "options") {
    const body = await request.json() as { token?: string };
    const registerToken = process.env.REGISTER_TOKEN;
    if (!registerToken || body.token !== registerToken) {
      return Response.json({ error: "トークンが違います" }, { status: 403 });
    }

    const options = await generateRegistrationOptions({
      rpName,
      rpID,
      userID: new Uint8Array([109, 105, 99, 114, 111, 98, 108, 111, 103]), // "microblog"
      userName: "admin",
      userDisplayName: "admin",
      attestationType: "none",
      authenticatorSelection: {
        residentKey: "required",
        userVerification: "required",
      },
    });
    // 必須フィールドのみ送信(@simplewebauthn/browser を使わず直接 API を叩くため)
    const minimalOptions = {
      rp: options.rp,
      user: options.user,
      challenge: options.challenge,
      pubKeyCredParams: options.pubKeyCredParams.filter(
        (p) => p.alg === -7 || p.alg === -257
      ),
    };
    session.set("challenge", options.challenge);
    return Response.json(minimalOptions, {
      headers: { "Set-Cookie": await commitSession(session) },
    });
  }

  if (intent === "verify") {
    const challenge = session.get("challenge") as string | undefined;
    if (!challenge) return Response.json({ error: "セッション切れです" }, { status: 400 });

    const body = (await request.json()) as RegistrationResponseJSON;
    let verification;
    try {
      verification = await verifyRegistrationResponse({
        response: body,
        expectedChallenge: challenge,
        expectedOrigin: origin,
        expectedRPID: rpID,
      });
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      console.error("[passkey] verifyRegistrationResponse failed:", msg);
      return Response.json({ error: msg }, { status: 400 });
    }

    if (!verification.verified || !verification.registrationInfo) {
      return Response.json({ error: "登録に失敗しました" }, { status: 400 });
    }

    const { credential } = verification.registrationInfo;
    saveCredential({
      id: credential.id,
      publicKey: credential.publicKey,
      counter: credential.counter,
      transports: (body.response as { transports?: AuthenticatorTransportFuture[] }).transports,
    });

    session.unset("challenge");
    session.set("authenticated", true);
    return redirect("/", {
      headers: { "Set-Cookie": await commitSession(session) },
    });
  }

  return Response.json({ error: "不正なリクエスト" }, { status: 400 });
}

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;
}

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, "");
}

export default function Register() {
  const [token, setToken] = useState("");
  const [status, setStatus] = useState<"idle" | "loading" | "error">("idle");
  const [errorMsg, setErrorMsg] = useState("");
  const [step, setStep] = useState("");

  async function handleRegister() {
    const tick = () => new Promise<void>((r) => setTimeout(r, 50));
    setStatus("loading");
    setErrorMsg("");
    setStep("");
    try {
      setStep("1a. fetch 中…"); await tick();
      const optRes = await fetch("/auth/register?intent=options", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ token }),
      });
      setStep("1b. fetch 完了 status=" + optRes.status); await tick();
      if (!optRes.ok) {
        const err = await optRes.json();
        throw new Error(err.error ?? "オプション取得に失敗しました");
      }
      const optJSON = await optRes.json();
      setStep("1c. JSON パース OK"); await tick();

      const userId = b64urlToBuffer(optJSON.user.id);
      const challenge = b64urlToBuffer(optJSON.challenge);
      setStep("2. credentials.create() 呼び出し中…"); await tick();

      // rp.id / authenticatorSelection / attestation を省略して最小構成で試す
      const credential = await navigator.credentials.create({
        publicKey: {
          rp: { name: optJSON.rp.name },
          user: {
            id: userId,
            name: optJSON.user.name,
            displayName: optJSON.user.displayName ?? optJSON.user.name,
          },
          challenge,
          pubKeyCredParams: optJSON.pubKeyCredParams,
        },
      }) as PublicKeyCredential | null;

      if (!credential) throw new Error("クレデンシャルの作成に失敗しました");
      setStep("3. credential 取得 OK → サーバー送信中…"); await tick();

      const attestation = credential.response as AuthenticatorAttestationResponse;
      const regResponse: RegistrationResponseJSON = {
        id: credential.id,
        rawId: bufferToB64url(credential.rawId),
        response: {
          clientDataJSON: bufferToB64url(attestation.clientDataJSON),
          attestationObject: bufferToB64url(attestation.attestationObject),
          transports: attestation.getTransports
            ? (attestation.getTransports() as AuthenticatorTransportFuture[])
            : [],
        },
        authenticatorAttachment: credential.authenticatorAttachment ?? undefined,
        clientExtensionResults: credential.getClientExtensionResults(),
        type: "public-key",
      };

      const verRes = await fetch("/auth/register?intent=verify", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(regResponse),
      });
      if (!verRes.ok) {
        const err = await verRes.json();
        throw new Error(err.error ?? "登録に失敗しました");
      }

      window.location.href = "/";
    } catch (e) {
      setStatus("error");
      setErrorMsg(e instanceof Error ? `${e.name}: ${e.message}` : String(e));
    }
  }

  return (
    <div className="wrap">
      <header className="site-header">
        <h1>log</h1>
      </header>
      <div className="auth-box">
        <h2>パスキーを登録 [debug]</h2>
        <p>登録トークンを入力してパスキーを作成します。</p>
        <input
          type="password"
          placeholder="登録トークン"
          value={token}
          onChange={(e) => setToken(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && handleRegister()}
          style={{
            width: "100%",
            marginBottom: ".75rem",
            padding: ".5rem .75rem",
            border: "1px solid #d1d5db",
            borderRadius: "4px",
            fontSize: ".875rem",
            fontFamily: "ui-monospace, monospace",
          }}
        />
        <button className="btn" onClick={handleRegister} disabled={status === "loading" || !token}>
          {status === "loading" ? "登録中…" : "パスキーを登録"}
        </button>
        {step && (
          <p style={{ marginTop: ".75rem", fontSize: ".8rem", color: "#6b7280" }}>{step}</p>
        )}
        {status === "error" && (
          <p className="error-msg" style={{ marginTop: ".5rem" }}>{errorMsg}</p>
        )}
      </div>
    </div>
  );
}