Jacksuyu commited on
Commit
374bf33
·
1 Parent(s): e9b9a8f

Fix anon identity in embedded Space with header fallback

Browse files
app/api/me/nickname/route.ts CHANGED
@@ -28,7 +28,7 @@ export async function POST(request: NextRequest) {
28
 
29
  const res = NextResponse.json({ ok: true, nickname });
30
  res.cookies.set("nickname", nickname, {
31
- sameSite: "lax",
32
  secure: process.env.NODE_ENV === "production",
33
  path: "/",
34
  maxAge: 60 * 60 * 24 * 365,
 
28
 
29
  const res = NextResponse.json({ ok: true, nickname });
30
  res.cookies.set("nickname", nickname, {
31
+ sameSite: process.env.NODE_ENV === "production" ? "none" : "lax",
32
  secure: process.env.NODE_ENV === "production",
33
  path: "/",
34
  maxAge: 60 * 60 * 24 * 365,
components/IdeaDetailClient.tsx CHANGED
@@ -1,6 +1,7 @@
1
  "use client";
2
 
3
  import { useMemo, useState } from "react";
 
4
 
5
  type LinkItem = {
6
  id: string;
@@ -101,7 +102,7 @@ export function IdeaDetailClient({
101
  setIdea((prev) => ({ ...prev, upvotesCount: prev.upvotesCount + (next ? 1 : -1) }));
102
 
103
  const method = next ? "POST" : "DELETE";
104
- const response = await fetch(`/api/ideas/${idea.id}/upvote`, { method });
105
  if (!response.ok) {
106
  setVoted(!next);
107
  setIdea((prev) => ({ ...prev, upvotesCount: prev.upvotesCount + (next ? -1 : 1) }));
@@ -109,7 +110,7 @@ export function IdeaDetailClient({
109
  }
110
 
111
  async function saveNickname() {
112
- const response = await fetch("/api/me/nickname", {
113
  method: "POST",
114
  headers: { "Content-Type": "application/json" },
115
  body: JSON.stringify({ nickname: nickInput }),
@@ -130,7 +131,7 @@ export function IdeaDetailClient({
130
  const body = commentInput.trim();
131
  if (!body) return;
132
 
133
- const response = await fetch(`/api/ideas/${idea.id}/comments`, {
134
  method: "POST",
135
  headers: { "Content-Type": "application/json" },
136
  body: JSON.stringify({ body }),
@@ -148,7 +149,7 @@ export function IdeaDetailClient({
148
  }
149
 
150
  async function claim(taskId: string) {
151
- const response = await fetch(`/api/tasks/${taskId}/claim`, { method: "POST" });
152
  if (!response.ok) return;
153
 
154
  const data = await response.json();
@@ -156,7 +157,7 @@ export function IdeaDetailClient({
156
  }
157
 
158
  async function unclaim(taskId: string) {
159
- const response = await fetch(`/api/tasks/${taskId}/unclaim`, { method: "POST" });
160
  if (!response.ok) return;
161
 
162
  const data = await response.json();
@@ -164,7 +165,7 @@ export function IdeaDetailClient({
164
  }
165
 
166
  async function setStatus(taskId: string, status: TaskItem["status"]) {
167
- const response = await fetch(`/api/tasks/${taskId}/status`, {
168
  method: "POST",
169
  headers: { "Content-Type": "application/json" },
170
  body: JSON.stringify({ status }),
@@ -180,7 +181,7 @@ export function IdeaDetailClient({
180
  if (!url) return;
181
  const label = window.prompt("Label (optional)") || undefined;
182
 
183
- const response = await fetch(`/api/tasks/${taskId}/links`, {
184
  method: "POST",
185
  headers: { "Content-Type": "application/json" },
186
  body: JSON.stringify({ url, label }),
@@ -196,7 +197,7 @@ export function IdeaDetailClient({
196
  }
197
 
198
  async function removeLink(taskId: string, linkId: string) {
199
- const response = await fetch(`/api/task-links/${linkId}`, { method: "DELETE" });
200
  if (!response.ok) return;
201
 
202
  setIdea((prev) => ({
 
1
  "use client";
2
 
3
  import { useMemo, useState } from "react";
4
+ import { fetchWithAnon } from "@/lib/client-anon";
5
 
6
  type LinkItem = {
7
  id: string;
 
102
  setIdea((prev) => ({ ...prev, upvotesCount: prev.upvotesCount + (next ? 1 : -1) }));
103
 
104
  const method = next ? "POST" : "DELETE";
105
+ const response = await fetchWithAnon(`/api/ideas/${idea.id}/upvote`, { method });
106
  if (!response.ok) {
107
  setVoted(!next);
108
  setIdea((prev) => ({ ...prev, upvotesCount: prev.upvotesCount + (next ? -1 : 1) }));
 
110
  }
111
 
112
  async function saveNickname() {
113
+ const response = await fetchWithAnon("/api/me/nickname", {
114
  method: "POST",
115
  headers: { "Content-Type": "application/json" },
116
  body: JSON.stringify({ nickname: nickInput }),
 
131
  const body = commentInput.trim();
132
  if (!body) return;
133
 
134
+ const response = await fetchWithAnon(`/api/ideas/${idea.id}/comments`, {
135
  method: "POST",
136
  headers: { "Content-Type": "application/json" },
137
  body: JSON.stringify({ body }),
 
149
  }
150
 
151
  async function claim(taskId: string) {
152
+ const response = await fetchWithAnon(`/api/tasks/${taskId}/claim`, { method: "POST" });
153
  if (!response.ok) return;
154
 
155
  const data = await response.json();
 
157
  }
158
 
159
  async function unclaim(taskId: string) {
160
+ const response = await fetchWithAnon(`/api/tasks/${taskId}/unclaim`, { method: "POST" });
161
  if (!response.ok) return;
162
 
163
  const data = await response.json();
 
165
  }
166
 
167
  async function setStatus(taskId: string, status: TaskItem["status"]) {
168
+ const response = await fetchWithAnon(`/api/tasks/${taskId}/status`, {
169
  method: "POST",
170
  headers: { "Content-Type": "application/json" },
171
  body: JSON.stringify({ status }),
 
181
  if (!url) return;
182
  const label = window.prompt("Label (optional)") || undefined;
183
 
184
+ const response = await fetchWithAnon(`/api/tasks/${taskId}/links`, {
185
  method: "POST",
186
  headers: { "Content-Type": "application/json" },
187
  body: JSON.stringify({ url, label }),
 
197
  }
198
 
199
  async function removeLink(taskId: string, linkId: string) {
200
+ const response = await fetchWithAnon(`/api/task-links/${linkId}`, { method: "DELETE" });
201
  if (!response.ok) return;
202
 
203
  setIdea((prev) => ({
components/SubmitForm.tsx CHANGED
@@ -2,6 +2,7 @@
2
 
3
  import { useRouter } from "next/navigation";
4
  import { useMemo, useState } from "react";
 
5
 
6
  function parseErrorMessage(error: unknown): string {
7
  if (typeof error === "string") return error;
@@ -31,7 +32,7 @@ export function SubmitForm() {
31
  setLoading(true);
32
 
33
  try {
34
- const response = await fetch("/api/ideas", {
35
  method: "POST",
36
  headers: { "Content-Type": "application/json" },
37
  body: JSON.stringify({
 
2
 
3
  import { useRouter } from "next/navigation";
4
  import { useMemo, useState } from "react";
5
+ import { fetchWithAnon } from "@/lib/client-anon";
6
 
7
  function parseErrorMessage(error: unknown): string {
8
  if (typeof error === "string") return error;
 
32
  setLoading(true);
33
 
34
  try {
35
+ const response = await fetchWithAnon("/api/ideas", {
36
  method: "POST",
37
  headers: { "Content-Type": "application/json" },
38
  body: JSON.stringify({
lib/client-anon.ts ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const STORAGE_KEY = "anon_id";
2
+
3
+ function fallbackId(): string {
4
+ return `anon_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
5
+ }
6
+
7
+ export function getOrCreateClientAnonId(): string {
8
+ if (typeof window === "undefined") return "";
9
+
10
+ try {
11
+ const existing = window.localStorage.getItem(STORAGE_KEY);
12
+ if (existing) return existing;
13
+
14
+ const created = typeof crypto !== "undefined" && "randomUUID" in crypto ? crypto.randomUUID() : fallbackId();
15
+ window.localStorage.setItem(STORAGE_KEY, created);
16
+ return created;
17
+ } catch {
18
+ return "";
19
+ }
20
+ }
21
+
22
+ export function withAnonHeaders(init: RequestInit = {}): RequestInit {
23
+ const headers = new Headers(init.headers || {});
24
+ const anonId = getOrCreateClientAnonId();
25
+
26
+ if (anonId) {
27
+ headers.set("x-anon-id", anonId);
28
+ }
29
+
30
+ return {
31
+ ...init,
32
+ headers,
33
+ credentials: "include",
34
+ };
35
+ }
36
+
37
+ export function fetchWithAnon(input: RequestInfo | URL, init: RequestInit = {}) {
38
+ return fetch(input, withAnonHeaders(init));
39
+ }
lib/identity.ts CHANGED
@@ -1,8 +1,19 @@
1
  import { cookies, headers } from "next/headers";
2
 
 
 
 
 
3
  export async function getAnonId(): Promise<string> {
4
  const store = await cookies();
5
- return store.get("anon_id")?.value ?? "";
 
 
 
 
 
 
 
6
  }
7
 
8
  export async function getNickname(): Promise<string> {
 
1
  import { cookies, headers } from "next/headers";
2
 
3
+ function looksLikeAnonId(value: string): boolean {
4
+ return value.length >= 8 && value.length <= 128;
5
+ }
6
+
7
  export async function getAnonId(): Promise<string> {
8
  const store = await cookies();
9
+ const cookieAnon = store.get("anon_id")?.value ?? "";
10
+ if (looksLikeAnonId(cookieAnon)) return cookieAnon;
11
+
12
+ const h = await headers();
13
+ const headerAnon = h.get("x-anon-id")?.trim() ?? "";
14
+ if (looksLikeAnonId(headerAnon)) return headerAnon;
15
+
16
+ return "";
17
  }
18
 
19
  export async function getNickname(): Promise<string> {
middleware.ts CHANGED
@@ -8,7 +8,7 @@ export function middleware(request: NextRequest) {
8
  if (!anon) {
9
  response.cookies.set("anon_id", crypto.randomUUID(), {
10
  httpOnly: true,
11
- sameSite: "lax",
12
  secure: process.env.NODE_ENV === "production",
13
  path: "/",
14
  maxAge: 60 * 60 * 24 * 365,
 
8
  if (!anon) {
9
  response.cookies.set("anon_id", crypto.randomUUID(), {
10
  httpOnly: true,
11
+ sameSite: process.env.NODE_ENV === "production" ? "none" : "lax",
12
  secure: process.env.NODE_ENV === "production",
13
  path: "/",
14
  maxAge: 60 * 60 * 24 * 365,