⚡️⚡️⚡️ Self-hosted collaborative bookmark manager to collect, read, annotate, and fully preserve what matters, all in one place.
TypeScript bookmarkbookmark-managercollaborationnextjsreact-nativeread-it-laterself-hostedtypescript
feat(mobile): add sign in with apple to iOS
daniel31x135c0786e695ef
diff --git a/apps/mobile/app.json b/apps/mobile/app.jsonindex a424a602..90d7b132 100644--- a/apps/mobile/app.json+++ b/apps/mobile/app.json@@ -83,6 +83,7 @@"./plugins/with-daynight-transparent-nav","expo-font","expo-web-browser",+ "expo-apple-authentication",["@sentry/react-native/expo",{diff --git a/apps/mobile/app/login.tsx b/apps/mobile/app/login.tsxindex 80e372ce..3d31cd76 100644--- a/apps/mobile/app/login.tsx+++ b/apps/mobile/app/login.tsx@@ -2,10 +2,22 @@ import { Button } from "@/components/ui/Button";import Input from "@/components/ui/Input";import { rawTheme, ThemeName } from "@/lib/colors";import useAuthStore from "@/store/auth";+import {+ isAtLeastInstanceVersion,+ type Config,+} from "@linkwarden/router/config";+import * as AppleAuthentication from "expo-apple-authentication";import { Redirect, router } from "expo-router";import { useColorScheme } from "nativewind";import { useEffect, useState } from "react";-import { View, Text, Dimensions, TouchableOpacity, Image } from "react-native";+import {+ Dimensions,+ Image,+ Platform,+ Text,+ TouchableOpacity,+ View,+} from "react-native";import Svg, { Path } from "react-native-svg";import {KeyboardStickyView,@@ -13,32 +25,40 @@ import {} from "react-native-keyboard-controller";import { SafeAreaView } from "react-native-safe-area-context";+const cloudInstance = "https://cloud.linkwarden.app";+export default function HomeScreen() {- const { auth, signIn } = useAuthStore();+ const { auth, signIn, signInWithApple } = useAuthStore();const { colorScheme } = useColorScheme();const [method, setMethod] = useState<"password" | "token">("password");const [isLoading, setIsLoading] = useState(false);+ const [appleEnabled, setAppleEnabled] = useState(+ Platform.OS === "ios" && (auth.instance || cloudInstance) === cloudInstance+ );+ const [isCheckingApple, setIsCheckingApple] = useState(false);const [form, setForm] = useState({user: "",password: "",token: "",- instance: auth.instance || "https://cloud.linkwarden.app",+ instance: auth.instance || cloudInstance,});const [showInstanceField, setShowInstanceField] = useState(- form.instance !== "https://cloud.linkwarden.app"+ form.instance !== cloudInstance);+ const instance = form.instance.trim().replace(/\/+$/, "");+useEffect(() => {setForm((prev) => ({...prev,- instance: auth.instance || "https://cloud.linkwarden.app",+ instance: auth.instance || cloudInstance,}));}, [auth.instance]);useEffect(() => {- setShowInstanceField(form.instance !== "https://cloud.linkwarden.app");+ setShowInstanceField(form.instance !== cloudInstance);}, [form.instance]);useEffect(() => {@@ -50,6 +70,49 @@ export default function HomeScreen() {}));}, [method]);+ useEffect(() => {+ if (Platform.OS !== "ios" || !instance) {+ setAppleEnabled(false);+ return;+ }++ setAppleEnabled(instance === cloudInstance);+ setIsCheckingApple(true);+ let active = true;+ const timer = setTimeout(async () => {+ try {+ const [configRes, loginsRes] = await Promise.all([+ fetch(`${instance}/api/v1/config`),+ fetch(`${instance}/api/v1/logins`),+ ]);++ if (!active || !configRes.ok || !loginsRes.ok) return;++ const config = ((await configRes.json())?.response ??+ null) as Config | null;+ const logins = await loginsRes.json().catch(() => null);+ const hasApple =+ logins?.buttonAuths?.some(+ (b: { method?: string }) => b.method === "apple"+ ) === true;++ if (active)+ setAppleEnabled(+ hasApple &&+ isAtLeastInstanceVersion(config?.INSTANCE_VERSION, "v2.15.0")+ );+ } catch {+ } finally {+ if (active) setIsCheckingApple(false);+ }+ }, 400);++ return () => {+ active = false;+ clearTimeout(timer);+ };+ }, [instance]);+if (auth.status === "authenticated") {return <Redirect href="/dashboard" />;}@@ -181,6 +244,24 @@ export default function HomeScreen() {><Text className="text-white text-xl">Login</Text></Button>+ {appleEnabled && (+ <AppleAuthentication.AppleAuthenticationButton+ buttonType={+ AppleAuthentication.AppleAuthenticationButtonType.CONTINUE+ }+ buttonStyle={+ colorScheme === "dark"+ ? AppleAuthentication.AppleAuthenticationButtonStyle.WHITE+ : AppleAuthentication.AppleAuthenticationButtonStyle.BLACK+ }+ cornerRadius={8}+ style={{ width: "100%", height: 48 }}+ onPress={() => {+ if (isCheckingApple) return;+ signInWithApple(instance);+ }}+ />+ )}<TouchableOpacityclassName="w-fit mx-auto"onPress={() => router.replace("/register")}diff --git a/apps/mobile/app/register.tsx b/apps/mobile/app/register.tsxindex cd24a176..a1c79e18 100644--- a/apps/mobile/app/register.tsx+++ b/apps/mobile/app/register.tsx@@ -6,6 +6,7 @@ import {isAtLeastInstanceVersion,type Config,} from "@linkwarden/router/config";+import * as AppleAuthentication from "expo-apple-authentication";import { Redirect, router } from "expo-router";import { useColorScheme } from "nativewind";import { useEffect, useState } from "react";@@ -14,6 +15,7 @@ import {Alert,Dimensions,Image,+ Platform,Text,TouchableOpacity,View,@@ -46,13 +48,18 @@ const timeout = () =>);export default function RegisterScreen() {- const { auth, signUp, requestVerificationEmail } = useAuthStore();+ const { auth, signUp, signInWithApple, requestVerificationEmail } =+ useAuthStore();const { colorScheme } = useColorScheme();const [isLoading, setIsLoading] = useState(false);const [isConfigLoading, setIsConfigLoading] = useState(false);const [config, setConfig] = useState<Config | null>(null);const [configInstance, setConfigInstance] = useState("");const [configError, setConfigError] = useState("");+ const [appleEnabled, setAppleEnabled] = useState(+ Platform.OS === "ios" && (auth.instance || cloudInstance) === cloudInstance+ );+ const [isCheckingApple, setIsCheckingApple] = useState(false);const [sentTo, setSentTo] = useState<{email: string;instance: string;@@ -79,7 +86,7 @@ export default function RegisterScreen() {const emailSignUp = currentConfig?.EMAIL_PROVIDER === true;const supportsMobileSignup =instance === cloudInstance ||- isAtLeastInstanceVersion(currentConfig?.INSTANCE_VERSION, "v2.14.3");+ isAtLeastInstanceVersion(currentConfig?.INSTANCE_VERSION, "v2.15.0");const instanceName =instance === cloudInstance ? "cloud.linkwarden.app" : instance;@@ -163,6 +170,48 @@ export default function RegisterScreen() {};}, [instance]);+ useEffect(() => {+ if (Platform.OS !== "ios" || !instance) {+ setAppleEnabled(false);+ return;+ }++ setAppleEnabled(instance === cloudInstance);+ setIsCheckingApple(true);+ let active = true;+ const timer = setTimeout(async () => {+ try {+ const [configRes, loginsRes] = await Promise.all([+ fetch(`${instance}/api/v1/config`),+ fetch(`${instance}/api/v1/logins`),+ ]);++ if (!active || !configRes.ok || !loginsRes.ok) return;++ const config = ((await configRes.json())?.response ?? null) as Config | null;+ const logins = await loginsRes.json().catch(() => null);+ const hasApple =+ logins?.buttonAuths?.some(+ (b: { method?: string }) => b.method === "apple"+ ) === true;++ if (active)+ setAppleEnabled(+ hasApple &&+ isAtLeastInstanceVersion(config?.INSTANCE_VERSION, "v2.15.0")+ );+ } catch {+ } finally {+ if (active) setIsCheckingApple(false);+ }+ }, 400);++ return () => {+ active = false;+ clearTimeout(timer);+ };+ }, [instance]);+if (auth.status === "authenticated") {return <Redirect href="/dashboard" />;}@@ -388,6 +437,26 @@ export default function RegisterScreen() {><Text className="text-white text-xl">Sign Up</Text></Button>+ {appleEnabled && (+ <AppleAuthentication.AppleAuthenticationButton+ buttonType={+ AppleAuthentication.AppleAuthenticationButtonType.CONTINUE+ }+ buttonStyle={+ colorScheme === "dark"+ ? AppleAuthentication.AppleAuthenticationButtonStyle+ .WHITE+ : AppleAuthentication.AppleAuthenticationButtonStyle+ .BLACK+ }+ cornerRadius={8}+ style={{ width: "100%", height: 48 }}+ onPress={() => {+ if (isCheckingApple) return;+ signInWithApple(instance);+ }}+ />+ )}<TouchableOpacityclassName="w-fit mx-auto"onPress={() => router.replace("/login")}diff --git a/apps/mobile/package.json b/apps/mobile/package.jsonindex d9975898..619ae58f 100644--- a/apps/mobile/package.json+++ b/apps/mobile/package.json@@ -30,6 +30,7 @@"@tanstack/react-query-persist-client": "^5.51.15","class-variance-authority": "^0.7.1","expo": "~54.0.0",+ "expo-apple-authentication": "~8.0.7","expo-application": "~7.0.8","expo-blur": "~15.0.8","expo-build-properties": "~1.0.10",diff --git a/apps/mobile/store/auth.ts b/apps/mobile/store/auth.tsindex e143b617..e97c5205 100644--- a/apps/mobile/store/auth.ts+++ b/apps/mobile/store/auth.ts@@ -1,5 +1,6 @@import { create } from "zustand";import * as SecureStore from "expo-secure-store";+import * as AppleAuthentication from "expo-apple-authentication";import { router } from "expo-router";import { MobileAuth } from "@linkwarden/types/global";import { Alert } from "react-native";@@ -27,6 +28,7 @@ type AuthStore = {instance: string,token?: string) => Promise<void>;+ signInWithApple: (instance: string) => Promise<void>;signUp: (form: SignUpForm) => Promise<boolean>;requestVerificationEmail: (email: string,@@ -216,6 +218,66 @@ const useAuthStore = create<AuthStore>((set) => ({}}},+ signInWithApple: async (instance) => {+ let credential: AppleAuthentication.AppleAuthenticationCredential;+ try {+ credential = await AppleAuthentication.signInAsync({+ requestedScopes: [+ AppleAuthentication.AppleAuthenticationScope.FULL_NAME,+ AppleAuthentication.AppleAuthenticationScope.EMAIL,+ ],+ });+ } catch (err: any) {+ if (err?.code === "ERR_REQUEST_CANCELED") return;+ Alert.alert("Error", "Could not sign in with Apple.");+ return;+ }++ if (!credential.identityToken) {+ Alert.alert("Error", "Apple did not return an identity token.");+ return;+ }++ const name = [credential.fullName?.givenName, credential.fullName?.familyName]+ .filter(Boolean)+ .join(" ")+ .trim();++ try {+ const res = await Promise.race([+ fetch(`${instance}/api/v1/auth/mobile/apple`, {+ method: "POST",+ body: JSON.stringify({+ identityToken: credential.identityToken,+ name: name || undefined,+ }),+ headers: { "Content-Type": "application/json" },+ }),+ timeout(),+ ]);+ const data = await res.json().catch(() => null);++ if (res.ok) {+ const session = data.response.token;+ await SecureStore.setItemAsync("TOKEN", session);+ await SecureStore.setItemAsync("INSTANCE", instance);+ set({ auth: { session, instance, status: "authenticated" } });+ router.replace("/(tabs)/dashboard");+ } else {+ Alert.alert(+ "Error",+ data?.response || "Could not sign in with Apple."+ );+ }+ } catch (err: any) {+ Alert.alert(+ err?.message === "TIMEOUT" ? "Request timed out" : "Network error",+ err?.message === "TIMEOUT"+ ? "Unable to reach the server in time. Please check your network configuration and try again."+ : "Could not connect to the server. Please check your network configuration and try again."+ );+ }+ },signOut: async () => {await SecureStore.deleteItemAsync("TOKEN");await SecureStore.deleteItemAsync("INSTANCE");diff --git a/apps/web/lib/api/apple.ts b/apps/web/lib/api/apple.tsindex 3dc24883..4ed71116 100644--- a/apps/web/lib/api/apple.ts+++ b/apps/web/lib/api/apple.ts@@ -1,7 +1,11 @@import { createSign } from "crypto";import { readFileSync } from "fs";+import { createRemoteJWKSet, jwtVerify } from "jose";import * as process from "process";+const appleIssuer = "https://appleid.apple.com";+const appleJwks = createRemoteJWKSet(new URL(`${appleIssuer}/auth/keys`));+const appleClientSecretMaxAge = 60 * 60 * 24 * 30; // 30 daysconst appleClientSecretRenewBuffer = 60 * 60; // 1 hourlet appleClientSecret:@@ -74,6 +78,25 @@ function createAppleClientSecret() {};}+export async function verifyAppleIdentityToken(+ identityToken: string,+ audience: string+) {+ const { payload } = await jwtVerify(identityToken, appleJwks, {+ issuer: appleIssuer,+ audience,+ });++ if (!payload.sub) throw Error("Apple identity token is missing the subject.");++ return payload as {+ sub: string;+ email?: string;+ email_verified?: boolean | string;+ is_private_email?: boolean | string;+ };+}+export function getAppleClientSecret() {if (process.env.APPLE_TEAM_ID &&diff --git a/apps/web/package.json b/apps/web/package.jsonindex b2e1d24c..37eeef28 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -1,6 +1,6 @@{"name": "@linkwarden/web",- "version": "v2.14.1",+ "version": "v2.15.0","main": "index.js","repository": "https://github.com/linkwarden/linkwarden.git","author": "Daniel31X13 <[email protected]>",diff --git a/apps/web/pages/api/v1/auth/mobile/apple.ts b/apps/web/pages/api/v1/auth/mobile/apple.tsnew file mode 100644index 00000000..2afd3bd0--- /dev/null+++ b/apps/web/pages/api/v1/auth/mobile/apple.ts@@ -0,0 +1,90 @@+import { verifyAppleIdentityToken } from "@/lib/api/apple";+import createSession from "@/lib/api/controllers/session/createSession";+import { prisma } from "@linkwarden/prisma";+import type { NextApiRequest, NextApiResponse } from "next";++const newSsoUsersDisabled = process.env.DISABLE_NEW_SSO_USERS === "true";+const appleBundleId = process.env.APPLE_BUNDLE_ID || "app.linkwarden";++export default async function appleMobileAuth(+ req: NextApiRequest,+ res: NextApiResponse+) {+ if (req.method !== "POST")+ return res.status(405).json({ response: "Method not allowed." });++ if (process.env.NEXT_PUBLIC_APPLE_ENABLED !== "true")+ return res+ .status(400)+ .json({ response: "Apple sign-in is not enabled on this instance." });++ const { identityToken, name, sessionName } = req.body ?? {};++ if (typeof identityToken !== "string" || !identityToken)+ return res.status(400).json({ response: "Missing identity token." });++ let claims;+ try {+ claims = await verifyAppleIdentityToken(identityToken, appleBundleId);+ } catch {+ return res.status(401).json({ response: "Invalid Apple identity token." });+ }++ const email = claims.email?.toLowerCase();++ let account = await prisma.account.findFirst({+ where: { provider: "apple", providerAccountId: claims.sub },+ include: { user: true },+ });++ let user = account?.user;++ if (!user && email) {+ user = (await prisma.user.findUnique({ where: { email } })) ?? undefined;++ if (user)+ await prisma.account.create({+ data: {+ userId: user.id,+ type: "oauth",+ provider: "apple",+ providerAccountId: claims.sub,+ },+ });+ }++ if (!user) {+ if (newSsoUsersDisabled)+ return res.status(403).json({ response: "Sign ups are disabled." });++ const fullName = typeof name === "string" && name.trim() ? name.trim() : "";++ user = await prisma.user.create({+ data: {+ name: fullName,+ email,+ emailVerified: new Date(),+ username: "user" + Math.round(Math.random() * 1000000000),+ accounts: {+ create: {+ type: "oauth",+ provider: "apple",+ providerAccountId: claims.sub,+ },+ },+ dashboardSections: {+ createMany: {+ data: [+ { order: 0, type: "STATS" },+ { order: 1, type: "RECENT_LINKS" },+ { order: 2, type: "PINNED_LINKS" },+ ],+ },+ },+ },+ });+ }++ const token = await createSession(user.id, sessionName);+ return res.status(token.status).json({ response: token.response });+}diff --git a/yarn.lock b/yarn.lockindex 8ab22a58..c6b711a0 100644--- a/yarn.lock+++ b/yarn.lock@@ -5255,6 +5255,7 @@ __metadata:"@types/react-test-renderer": "npm:^19.1.0"class-variance-authority: "npm:^0.7.1"expo: "npm:~54.0.0"+ expo-apple-authentication: "npm:~8.0.7"expo-application: "npm:~7.0.8"expo-blur: "npm:~15.0.8"expo-build-properties: "npm:~1.0.10"@@ -12692,6 +12693,16 @@ __metadata:languageName: nodelinkType: hard+"expo-apple-authentication@npm:~8.0.7":+ version: 8.0.8+ resolution: "expo-apple-authentication@npm:8.0.8"+ peerDependencies:+ expo: "*"+ react-native: "*"+ checksum: 10c0/6b5179de9a6d4340a35c8487781919f05f9b8170e98fcce5bf7de4e68b9df84b0a77991851b0210c1976d5673070378d8f89562d6d2f37371307e642a25446b1+ languageName: node+ linkType: hard+"expo-application@npm:~7.0.8":version: 7.0.8resolution: "expo-application@npm:7.0.8"