Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(web): add Sign in with Apple (#744)

Gener68c58d7db4de
diff --git a/DESIGN.md b/DESIGN.md
index 1f2029ee0..81be1302d 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -76,6 +76,7 @@ Rules:
- **Pick tokens by intent, not by lightness.** Don't reach for `muted` because it "looks the right gray" — reach for it because the content is genuinely secondary.
- **Don't signal state by color alone.** Pair color with an icon, label, or weight change so colorblind users and high-contrast modes still read the state.
- **Accents stay desaturated.** Any new accent must be pulled 20–30% toward gray before it ships. Saturated leftovers from templates are bugs (see Do's & Don'ts).
+- **External identity buttons keep their mandated brand treatment.** Sign in with Apple is the narrow exception: use the semantic `apple-signin*` tokens, which resolve to Apple's required black-on-light and white-on-dark appearances. Never reuse those tokens elsewhere.
### Typography
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index afe14c812..7cfe81a59 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -455,6 +455,9 @@ importers:
input-otp:
specifier: ^1.5.0
+ jose:
+ specifier: ^6.2.12
+ version: 6.2.12
katex:
specifier: ^0.18.5
version: 0.18.5
@@ -6950,8 +6953,8 @@ packages:
resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==}
hasBin: true
- resolution: {integrity: sha512-A5NPn7g8EAzGU3IzRs+Yiq8K5n3ypYS75M5+KKiVHdUexfpWK1kP4ZMq7QnTGDoMj6TJ1dtcEJjW60yZDXS4hg==}
+ resolution: {integrity: sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==}
resolution: {integrity: sha512-WZzeDOEtTOBK4Mdsar0IqEU5sMr3vSV2RqkAIzUEV2BHnUfKGyswWFPFwK5EeDo93K3FohSHbLAjj0s1Wzd+dg==}
@@ -10609,14 +10612,14 @@ snapshots:
'@bcoe/[email protected]': {}
dependencies:
'@better-auth/utils': 0.4.2
'@better-fetch/fetch': 1.3.1
'@opentelemetry/semantic-conventions': 1.43.0
'@standard-schema/spec': 1.1.0
better-call: 1.4.0([email protected])
- jose: 6.2.11
+ jose: 6.2.12
kysely: 0.29.5
nanostores: 1.5.3
zod: 4.5.4
@@ -10624,38 +10627,38 @@ snapshots:
'@cloudflare/workers-types': 5.20260907.1
'@opentelemetry/api': 1.9.1
dependencies:
'@better-auth/utils': 0.4.2
optionalDependencies:
dependencies:
'@better-auth/utils': 0.4.2
optionalDependencies:
kysely: 0.29.5
dependencies:
'@better-auth/utils': 0.4.2
dependencies:
'@better-auth/utils': 0.4.2
dependencies:
'@better-auth/utils': 0.4.2
dependencies:
'@better-auth/utils': 0.4.2
'@better-fetch/fetch': 1.3.1
@@ -11709,7 +11712,7 @@ snapshots:
express: 5.2.1
express-rate-limit: 8.7.0([email protected])
hono: 4.13.5
- jose: 6.2.11
+ jose: 6.2.12
json-schema-typed: 8.0.2
pkce-challenge: 5.0.1
raw-body: 3.0.2
@@ -13538,7 +13541,7 @@ snapshots:
magicast: 0.5.4
obug: 2.1.4
tinyrainbow: 3.1.1
transitivePeerDependencies:
- supports-color
@@ -13554,7 +13557,7 @@ snapshots:
obug: 2.1.4
std-env: 4.2.0
tinyrainbow: 3.1.1
'@vitest/[email protected]':
dependencies:
@@ -13911,20 +13914,20 @@ snapshots:
dependencies:
- '@better-auth/memory-adapter': 1.7.3(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])
- '@better-auth/mongo-adapter': 1.7.3(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])
- '@better-auth/prisma-adapter': 1.7.3(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])
- '@better-auth/telemetry': 1.7.3(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])(@better-fetch/[email protected])
+ '@better-auth/memory-adapter': 1.7.3(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])
+ '@better-auth/mongo-adapter': 1.7.3(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])
+ '@better-auth/prisma-adapter': 1.7.3(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])
+ '@better-auth/telemetry': 1.7.3(@better-auth/[email protected](@better-auth/[email protected])(@better-fetch/[email protected])(@cloudflare/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])([email protected])([email protected]))(@better-auth/[email protected])(@better-fetch/[email protected])
'@better-auth/utils': 0.4.2
'@better-fetch/fetch': 1.3.1
'@noble/ciphers': 2.4.0
'@noble/hashes': 2.4.0
better-call: 1.4.0([email protected])
defu: 6.1.7
- jose: 6.2.11
+ jose: 6.2.12
kysely: 0.29.5
nanostores: 1.5.3
zod: 4.5.4
@@ -15021,8 +15024,8 @@ snapshots:
'@next/eslint-plugin-next': 16.3.4([email protected]([email protected]))
eslint: 9.39.5([email protected])
eslint-import-resolver-node: 0.3.10
+ eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))
+ eslint-plugin-import: 2.32.0([email protected])([email protected]([email protected]))
eslint-plugin-jsx-a11y: 6.10.2([email protected]([email protected]))
eslint-plugin-react: 7.37.5([email protected]([email protected]))
eslint-plugin-react-hooks: 7.1.1([email protected]([email protected]))
@@ -15044,7 +15047,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@nolyfill/is-core-module': 1.0.39
debug: 4.4.3
@@ -15055,21 +15058,21 @@ snapshots:
tinyglobby: 0.2.17
unrs-resolver: 1.12.2
optionalDependencies:
+ eslint-plugin-import: 2.32.0([email protected])([email protected]([email protected]))
transitivePeerDependencies:
- supports-color
dependencies:
debug: 3.2.7
optionalDependencies:
eslint: 9.39.5([email protected])
eslint-import-resolver-node: 0.3.10
+ eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))
transitivePeerDependencies:
- supports-color
dependencies:
'@rtsao/scc': 1.1.0
array-includes: 3.1.9
@@ -15080,7 +15083,7 @@ snapshots:
doctrine: 2.1.0
eslint: 9.39.5([email protected])
eslint-import-resolver-node: 0.3.10
hasown: 2.0.4
is-core-module: 2.16.2
is-glob: 4.0.3
@@ -16281,7 +16284,7 @@ snapshots:
diff --git a/src/desktop/src-tauri/src/native_oauth.rs b/src/desktop/src-tauri/src/native_oauth.rs
index e8b158a1e..8fd58c256 100644
--- a/src/desktop/src-tauri/src/native_oauth.rs
+++ b/src/desktop/src-tauri/src/native_oauth.rs
@@ -231,7 +231,7 @@ impl Record {
if !token(&a.id, 43, 43)
|| !token(&a.state, 43, 43)
|| !token(&a.verifier, 43, 43)
- || !matches!(a.provider.as_str(), "github" | "google")
+ || !matches!(a.provider.as_str(), "github" | "google" | "apple")
|| !safe_redirect(&a.redirect_path)
|| a.expires_at > now.saturating_add(ATTEMPT_TTL)
|| a.candidates.len() > MAX_CANDIDATES
@@ -267,7 +267,7 @@ impl Record {
platform: &str,
now: u64,
) -> Result<Registration, &'static str> {
- if !matches!(provider, "github" | "google")
+ if !matches!(provider, "github" | "google" | "apple")
|| !safe_redirect(redirect_path)
|| !matches!(platform, "macos" | "windows" | "linux" | "ios" | "android")
{
@@ -689,10 +689,21 @@ mod tests {
assert!(r.open("old", &good, false).is_err());
r.open(&p.attempt_id, &good, false).unwrap();
assert!(r.open(&p.attempt_id, &good, false).is_err());
- assert!(r.prepare("apple", "/c/me", "macos", NOW).is_err());
+ assert!(r.prepare("apple", "/c/me", "macos", NOW).is_ok());
assert!(r.prepare("google", "/c/me", "ios", NOW).is_ok());
assert!(r.prepare("google", "/c/me", "android", NOW).is_ok());
assert!(r.prepare("google", "/c/me", "web", NOW).is_err());
+ assert!(r.prepare("twitter", "/c/me", "macos", NOW).is_err());
+ }
+
+ #[test]
+ fn apple_uses_the_existing_bridge_on_all_five_platforms() {
+ for platform in ["macos", "windows", "linux", "ios", "android"] {
+ let mut record = Record::new().unwrap();
+ let registration = record.prepare("apple", "/c/me", platform, NOW).unwrap();
+ assert_eq!(registration.provider, "apple");
+ assert_eq!(record.snapshot().unwrap().provider, "apple");
+ }
}
#[test]
diff --git a/src/shared/src/db/queries/user.ts b/src/shared/src/db/queries/user.ts
index 87e9c3227..6b6e2f9d9 100644
--- a/src/shared/src/db/queries/user.ts
+++ b/src/shared/src/db/queries/user.ts
@@ -1,6 +1,6 @@
import { eq, inArray, sql, and, ne, isNull } from "drizzle-orm";
import { nanoid } from "nanoid";
-import { user } from "../schema";
+import { account, user } from "../schema";
import type { Database } from "../index";
import { escapeLikePattern } from "../../utils/sql-like";
import { computeDiscriminator } from "../../lib/discriminator";
@@ -219,6 +219,33 @@ export async function getUserByEmail(
return (rows[0] as PublicUser | undefined) ?? null;
}
+/**
+ * Auth-internal lookup for a stable OAuth identity. Better Auth 1.7 keys
+ * social accounts by `(providerId, accountId)`; callers must supply the
+ * provider-verified immutable subject, never an email address.
+ */
+export async function getUserByProviderAccount(
+ db: Database,
+ providerId: string,
+ accountId: string
+): Promise<PublicUser | null> {
+ const rows = await db
+ .select(publicUserColumns)
+ .from(account)
+ .innerJoin(user, eq(account.userId, user.id))
+ .where(
+ and(
+ eq(account.providerId, providerId),
+ eq(account.accountId, accountId)
+ )
+ )
+ .limit(2);
+ if (rows.length > 1) {
+ throw new Error("multiple users share one provider account identity");
+ }
+ return (rows[0] as PublicUser | undefined) ?? null;
+}
+
/** Public — bare-name fallback path (e.g. friend-request-by-username with no `#tag`). */
export async function getUserByNameCaseInsensitive(
db: Database,
diff --git a/src/shared/src/db/schema.ts b/src/shared/src/db/schema.ts
index 887bf464b..924504b89 100644
--- a/src/shared/src/db/schema.ts
+++ b/src/shared/src/db/schema.ts
@@ -96,7 +96,7 @@ export const verification = sqliteTable("verification", {
updatedAt: text("updatedAt").notNull().$defaultFn(() => new Date().toISOString()),
});
-export const NATIVE_OAUTH_PROVIDERS = ["github", "google"] as const;
+export const NATIVE_OAUTH_PROVIDERS = ["github", "google", "apple"] as const;
export type NativeOauthProvider = (typeof NATIVE_OAUTH_PROVIDERS)[number];
export const NATIVE_OAUTH_PLATFORMS = [
@@ -188,7 +188,7 @@ export const nativeOauthAttempt = sqliteTable(
),
check(
"ck_native_oauth_attempt_enums",
- sql`${t.provider} IN ('github', 'google')
+ sql`${t.provider} IN ('github', 'google', 'apple')
AND ${t.platform} IN ('macos', 'windows', 'linux', 'ios', 'android')
AND ${t.status} IN ('pending', 'opened', 'ready', 'exchanging', 'consumed', 'failed', 'cancelled', 'replaced')
AND (${t.authKind} IS NULL OR ${t.authKind} IN ('signin', 'signup'))
diff --git a/src/shared/src/lib/native-oauth-contract.test.ts b/src/shared/src/lib/native-oauth-contract.test.ts
index a21ccdd60..780d08f24 100644
--- a/src/shared/src/lib/native-oauth-contract.test.ts
+++ b/src/shared/src/lib/native-oauth-contract.test.ts
@@ -15,6 +15,11 @@ describe("native OAuth contract drift", () => {
expect(nativeOauthProviderSchema.options).toEqual([
...NATIVE_OAUTH_PROVIDERS,
]);
+ expect(nativeOauthProviderSchema.options).toEqual([
+ "github",
+ "google",
+ "apple",
+ ]);
expect(nativeOauthPlatformSchema.options).toEqual([
...NATIVE_OAUTH_PLATFORMS,
]);
diff --git a/src/shared/src/lib/native-oauth-contract.ts b/src/shared/src/lib/native-oauth-contract.ts
index 4b5f5ccea..7aba97148 100644
--- a/src/shared/src/lib/native-oauth-contract.ts
+++ b/src/shared/src/lib/native-oauth-contract.ts
@@ -6,7 +6,7 @@ const SHA256_HEX = /^[0-9a-f]{64}$/;
const BASE64URL_32_BYTES = /^[A-Za-z0-9_-]{43}$/;
const HANDOFF_CODE = /^[A-Za-z0-9_-]{32,128}$/;
-export const nativeOauthProviderSchema = z.enum(["github", "google"]);
+export const nativeOauthProviderSchema = z.enum(["github", "google", "apple"]);
export const nativeOauthPlatformSchema = z.enum([
"macos",
"windows",
diff --git a/src/shared/test/queries/user.test.ts b/src/shared/test/queries/user.test.ts
index 5cb1baab8..605fc47a3 100644
--- a/src/shared/test/queries/user.test.ts
+++ b/src/shared/test/queries/user.test.ts
@@ -18,6 +18,7 @@ function createSelectLimitMock(rows: any[]) {
const chain: any = {};
chain.select = vi.fn(() => chain);
chain.from = vi.fn(() => chain);
+ chain.innerJoin = vi.fn(() => chain);
chain.where = vi.fn(() => chain);
chain.limit = vi.fn(() => Promise.resolve(rows));
return chain;
@@ -69,6 +70,7 @@ describe("user exports", () => {
it("exports getUserPublic", () => { expect(typeof userQueries.getUserPublic).toBe("function"); });
it("exports getUserSelf", () => { expect(typeof userQueries.getUserSelf).toBe("function"); });
it("exports getUserByEmail", () => { expect(typeof userQueries.getUserByEmail).toBe("function"); });
+ it("exports getUserByProviderAccount", () => { expect(typeof userQueries.getUserByProviderAccount).toBe("function"); });
it("exports createUser", () => { expect(typeof userQueries.createUser).toBe("function"); });
it("exports updateUser", () => { expect(typeof userQueries.updateUser).toBe("function"); });
});
@@ -98,6 +100,44 @@ describe("getUserByEmail", () => {
it("returns user", async () => { const u = { id: "u_1" }; expect(await userQueries.getUserByEmail(createSelectMock([u]), "[email protected]")).toEqual(u); });
});
+describe("getUserByProviderAccount", () => {
+ it("returns the user joined through the exact provider and account keys", async () => {
+ const user = { id: "u_apple", email: "[email protected]" };
+ const chain = createSelectLimitMock([user]);
+
+ await expect(
+ userQueries.getUserByProviderAccount(chain, "apple", "stable-sub"),
+ ).resolves.toEqual(user);
+ expect(chain.innerJoin).toHaveBeenCalledOnce();
+ expect(chain.limit).toHaveBeenCalledWith(2);
+ const condition = chain.where.mock.calls[0][0];
+ expect(conditionReferencesColumn(condition, "providerId")).toBe(true);
+ expect(conditionReferencesColumn(condition, "accountId")).toBe(true);
+ expect(conditionContainsString(condition, "apple")).toBe(true);
+ expect(conditionContainsString(condition, "stable-sub")).toBe(true);
+ });
+
+ it("returns null when the identity has never been seen", async () => {
+ await expect(
+ userQueries.getUserByProviderAccount(
+ createSelectLimitMock([]),
+ "apple",
+ "new-sub"
+ ),
+ ).resolves.toBeNull();
+ });
+
+ it("fails closed when duplicate provider identities exist", async () => {
+ await expect(
+ userQueries.getUserByProviderAccount(
+ createSelectLimitMock([{ id: "u_1" }, { id: "u_2" }]),
+ "apple",
+ "duplicate-sub"
+ ),
+ ).rejects.toThrow("multiple users share one provider account identity");
+ });
+});
+
describe("createUser", () => {
it("creates user", async () => {
const u = { id: "u_1" };
diff --git a/src/web/.dev.vars.example b/src/web/.dev.vars.example
index 1654539cf..88ca68089 100644
--- a/src/web/.dev.vars.example
+++ b/src/web/.dev.vars.example
@@ -21,5 +21,12 @@ GITHUB_CLIENT_SECRET=
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
+# Sign in with Apple (Services ID + Sign in with Apple private key)
+# Leave all four values empty to disable the provider locally.
+APPLE_CLIENT_ID=
+APPLE_TEAM_ID=
+APPLE_KEY_ID=
+APPLE_PRIVATE_KEY=
+
# Device Code Flow — comma-separated allowed client IDs
DEVICE_CLIENT_IDS=alook-cli
diff --git a/src/web/cloudflare-env.d.ts b/src/web/cloudflare-env.d.ts
index 369d7b156..61254e336 100644
--- a/src/web/cloudflare-env.d.ts
+++ b/src/web/cloudflare-env.d.ts
@@ -1,5 +1,5 @@
/* eslint-disable */
-// Generated by Wrangler by running `wrangler types --config=wrangler.toml --env-file=.dev.vars.example --env-interface=CloudflareEnv cloudflare-env.d.ts` (hash: 986b72653b9a5a083072e908394b8e5c)
+// Generated by Wrangler by running `wrangler types --config=wrangler.toml --env-file=.dev.vars.example --env-interface=CloudflareEnv cloudflare-env.d.ts` (hash: 53b69659a969e5ead1c93192f0067aae)
// Runtime types generated with [email protected] 2026-09-07 nodejs_compat
interface __BaseEnv_CloudflareEnv {
CACHE_KV: KVNamespace;
@@ -21,6 +21,10 @@ interface __BaseEnv_CloudflareEnv {
GITHUB_CLIENT_SECRET: string;
GOOGLE_CLIENT_ID: string;
GOOGLE_CLIENT_SECRET: string;
+ APPLE_CLIENT_ID: string;
+ APPLE_TEAM_ID: string;
+ APPLE_KEY_ID: string;
+ APPLE_PRIVATE_KEY: string;
DEVICE_CLIENT_IDS: string;
NEXT_CACHE_DO_QUEUE: DurableObjectNamespace<import("./custom-worker").DOQueueHandler>;
WORKER_SELF_REFERENCE: Service<typeof import("./custom-worker").default>;
@@ -41,7 +45,7 @@ type StringifyValues<EnvType extends Record<string, unknown>> = {
[Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string;
};
declare namespace NodeJS {
- interface ProcessEnv extends StringifyValues<Pick<Cloudflare.Env, "RUNTIME_MODEL_OPTIONS" | "MIN_CLI_VERSION" | "BLOG_DISCOVERY_REQUIRED" | "BETTER_AUTH_SECRET" | "BETTER_AUTH_URL" | "ENCRYPTION_KEY" | "GITHUB_CLIENT_ID" | "GITHUB_CLIENT_SECRET" | "GOOGLE_CLIENT_ID" | "GOOGLE_CLIENT_SECRET" | "DEVICE_CLIENT_IDS">> {}
+ interface ProcessEnv extends StringifyValues<Pick<Cloudflare.Env, "RUNTIME_MODEL_OPTIONS" | "MIN_CLI_VERSION" | "BLOG_DISCOVERY_REQUIRED" | "BETTER_AUTH_SECRET" | "BETTER_AUTH_URL" | "ENCRYPTION_KEY" | "GITHUB_CLIENT_ID" | "GITHUB_CLIENT_SECRET" | "GOOGLE_CLIENT_ID" | "GOOGLE_CLIENT_SECRET" | "APPLE_CLIENT_ID" | "APPLE_TEAM_ID" | "APPLE_KEY_ID" | "APPLE_PRIVATE_KEY" | "DEVICE_CLIENT_IDS">> {}
}
// Begin runtime types
diff --git a/src/web/migrations/0095_native_oauth_attempt.sql b/src/web/migrations/0095_native_oauth_attempt.sql
index 8eeefe80f..a2c4a730b 100644
--- a/src/web/migrations/0095_native_oauth_attempt.sql
+++ b/src/web/migrations/0095_native_oauth_attempt.sql
@@ -40,7 +40,7 @@ CREATE TABLE native_oauth_attempt (
)
),
CONSTRAINT ck_native_oauth_attempt_enums CHECK (
- provider IN ('github', 'google')
+ provider IN ('github', 'google', 'apple')
AND platform IN ('macos', 'windows', 'linux', 'ios', 'android')
AND status IN (
'pending', 'opened', 'ready', 'exchanging',
diff --git a/src/web/package.json b/src/web/package.json
index 2be9c632c..4eaf95107 100644
--- a/src/web/package.json
+++ b/src/web/package.json
@@ -72,8 +72,8 @@
"@tanstack/react-virtual": "^3.14.10",
"@tauri-apps/plugin-clipboard-manager": "^2.3.3",
"@tiptap/extension-image": "^3.31.3",
- "@tiptap/extension-list": "^3.31.3",
"@tiptap/extension-link": "^3.31.3",
+ "@tiptap/extension-list": "^3.31.3",
"@tiptap/extension-mention": "^3.31.3",
"@tiptap/extension-placeholder": "^3.31.3",
"@tiptap/extension-text-align": "^3.31.3",
@@ -94,6 +94,7 @@
"idb": "^8.0.3",
"idb-keyval": "^6.3.0",
"input-otp": "^1.5.0",
+ "jose": "^6.2.12",
"katex": "^0.18.5",
"lucide-react": "^1.41.0",
"mdast-util-find-and-replace": "^3.0.2",
diff --git a/src/web/src/app/(auth)/sign-in/apple-sign-in-artwork.ts b/src/web/src/app/(auth)/sign-in/apple-sign-in-artwork.ts
new file mode 100644
index 000000000..6614df2ac
--- /dev/null
+++ b/src/web/src/app/(auth)/sign-in/apple-sign-in-artwork.ts
@@ -0,0 +1,8 @@
+// Unmodified medium left-aligned SVGs for custom Apple logo-and-text buttons.
+// Source package: https://devimages-cdn.apple.com/design/resources/download/Logo-Sign-in-with-Apple.dmg
+// Files: Sign in with Apple - Left Aligned/SVG/* - Medium.svg
+// SHA-256: black 0f56330a7a4fe2db06ec79fdbfed1eec1d434557f052add6d848daa31877f380
+// SHA-256: white f43d1ed5be59bcffdf4c20b5e29f8de041858678f549515377d0ba4f5ebd115e
+export const APPLE_LEFT_ALIGNED_LOGO_BLACK = "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyB3aWR0aD0iMzFweCIgaGVpZ2h0PSI0NHB4IiB2aWV3Qm94PSIwIDAgMzEgNDQiIHZlcnNpb249IjEuMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+CiAgICA8IS0tIEdlbmVyYXRvcjogU2tldGNoIDYxICg4OTU4MSkgLSBodHRwczovL3NrZXRjaC5jb20gLS0+CiAgICA8dGl0bGU+TGVmdCBCbGFjayBMb2dvIE1lZGl1bTwvdGl0bGU+CiAgICA8ZGVzYz5DcmVhdGVkIHdpdGggU2tldGNoLjwvZGVzYz4KICAgIDxnIGlkPSJMZWZ0LUJsYWNrLUxvZ28tTWVkaXVtIiBzdHJva2U9Im5vbmUiIHN0cm9rZS13aWR0aD0iMSIgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj4KICAgICAgICA8cmVjdCBpZD0iUmVjdGFuZ2xlIiBmaWxsPSIjRkZGRkZGIiB4PSIwIiB5PSIwIiB3aWR0aD0iMzEiIGhlaWdodD0iNDQiPjwvcmVjdD4KICAgICAgICA8cGF0aCBkPSJNMTUuNzA5OTQ5MSwxNC44ODQ2MTU0IEMxNi41Njc1NDYxLDE0Ljg4NDYxNTQgMTcuNjQyNTYyLDE0LjMwNDgzMTUgMTguMjgyNzQsMTMuNTMxNzg2NCBDMTguODYyNTIzOCwxMi44MzEyMTQyIDE5LjI4NTI4MjksMTEuODUyODI5IDE5LjI4NTI4MjksMTAuODc0NDQzNyBDMTkuMjg1MjgyOSwxMC43NDE1NzY2IDE5LjI3MzIwNDEsMTAuNjA4NzA5NSAxOS4yNDkwNDY0LDEwLjUgQzE4LjI5NDgxODgsMTAuNTM2MjM2NSAxNy4xNDczMjk5LDExLjE0MDE3OCAxNi40NTg4MzY2LDExLjk0OTQ1OTYgQzE1LjkxNTI4OTMsMTIuNTY1NDggMTUuNDIwMDU3MiwxMy41MzE3ODY0IDE1LjQyMDA1NzIsMTQuNTIyMjUwNSBDMTUuNDIwMDU3MiwxNC42NjcxOTY0IDE1LjQ0NDIxNDksMTQuODEyMTQyNCAxNS40NTYyOTM3LDE0Ljg2MDQ1NzcgQzE1LjUxNjY4NzksMTQuODcyNTM2NiAxNS42MTMzMTg1LDE0Ljg4NDYxNTQgMTUuNzA5OTQ5MSwxNC44ODQ2MTU0IFogTTEyLjY5MDI0MTYsMjkuNSBDMTMuODYxODg4MSwyOS41IDE0LjM4MTI3NzgsMjguNzE0ODc2IDE1Ljg0MjgxNjMsMjguNzE0ODc2IEMxNy4zMjg1MTI0LDI4LjcxNDg3NiAxNy42NTQ2NDA4LDI5LjQ3NTg0MjMgMTguOTU5MTU0NSwyOS40NzU4NDIzIEMyMC4yMzk1MTA1LDI5LjQ3NTg0MjMgMjEuMDk3MTA3NCwyOC4yOTIxMTcgMjEuOTA2Mzg5MSwyNy4xMzI1NDkzIEMyMi44MTIzMDEzLDI1LjgwMzg3NzkgMjMuMTg2NzQ1MSwyNC40OTkzNjQzIDIzLjIxMDkwMjcsMjQuNDM4OTcwMSBDMjMuMTI2MzUwOSwyNC40MTQ4MTI1IDIwLjY3NDM0ODQsMjMuNDEyMjY5NSAyMC42NzQzNDg0LDIwLjU5NzkwMjEgQzIwLjY3NDM0ODQsMTguMTU3OTc4NCAyMi42MDY5NjEyLDE3LjA1ODgwNDggMjIuNzE1NjcwNywxNi45NzQyNTMgQzIxLjQzNTMxNDcsMTUuMTM4MjcwOCAxOS40OTA2MjMsMTUuMDg5OTU1NSAxOC45NTkxNTQ1LDE1LjA4OTk1NTUgQzE3LjUyMTc3MzcsMTUuMDg5OTU1NSAxNi4zNTAxMjcxLDE1Ljk1OTYzMTMgMTUuNjEzMzE4NSwxNS45NTk2MzEzIEMxNC44MTYxMTU3LDE1Ljk1OTYzMTMgMTMuNzY1MjU3NSwxNS4xMzgyNzA4IDEyLjUyMTEzOCwxNS4xMzgyNzA4IEMxMC4xNTM2ODcyLDE1LjEzODI3MDggNy43NSwxNy4wOTUwNDEzIDcuNzUsMjAuNzkxMTYzNCBDNy43NSwyMy4wODYxNDExIDguNjQzODMzNDQsMjUuNTEzOTg2IDkuNzQzMDA2OTksMjcuMDg0MjMzOSBDMTAuNjg1MTU1OCwyOC40MTI5MDUzIDExLjUwNjUxNjIsMjkuNSAxMi42OTAyNDE2LDI5LjUgWiIgaWQ9Iu+jvyIgZmlsbD0iIzAwMDAwMCIgZmlsbC1ydWxlPSJub256ZXJvIj48L3BhdGg+CiAgICA8L2c+Cjwvc3ZnPg=="
+
+export const APPLE_LEFT_ALIGNED_LOGO_WHITE = "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPHN2ZyB3aWR0aD0iMzFweCIgaGVpZ2h0PSI0NHB4IiB2aWV3Qm94PSIwIDAgMzEgNDQiIHZlcnNpb249IjEuMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayI+CiAgICA8IS0tIEdlbmVyYXRvcjogU2tldGNoIDYxICg4OTU4MSkgLSBodHRwczovL3NrZXRjaC5jb20gLS0+CiAgICA8dGl0bGU+TGVmdCBXaGl0ZSBMb2dvIE1lZGl1bTwvdGl0bGU+CiAgICA8ZGVzYz5DcmVhdGVkIHdpdGggU2tldGNoLjwvZGVzYz4KICAgIDxnIGlkPSJMZWZ0LVdoaXRlLUxvZ28tTWVkaXVtIiBzdHJva2U9Im5vbmUiIHN0cm9rZS13aWR0aD0iMSIgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj4KICAgICAgICA8cmVjdCBpZD0iUmVjdGFuZ2xlIiBmaWxsPSIjMDAwMDAwIiB4PSIwIiB5PSIwIiB3aWR0aD0iMzEiIGhlaWdodD0iNDQiPjwvcmVjdD4KICAgICAgICA8cGF0aCBkPSJNMTUuNzA5OTQ5MSwxNC44ODQ2MTU0IEMxNi41Njc1NDYxLDE0Ljg4NDYxNTQgMTcuNjQyNTYyLDE0LjMwNDgzMTUgMTguMjgyNzQsMTMuNTMxNzg2NCBDMTguODYyNTIzOCwxMi44MzEyMTQyIDE5LjI4NTI4MjksMTEuODUyODI5IDE5LjI4NTI4MjksMTAuODc0NDQzNyBDMTkuMjg1MjgyOSwxMC43NDE1NzY2IDE5LjI3MzIwNDEsMTAuNjA4NzA5NSAxOS4yNDkwNDY0LDEwLjUgQzE4LjI5NDgxODgsMTAuNTM2MjM2NSAxNy4xNDczMjk5LDExLjE0MDE3OCAxNi40NTg4MzY2LDExLjk0OTQ1OTYgQzE1LjkxNTI4OTMsMTIuNTY1NDggMTUuNDIwMDU3MiwxMy41MzE3ODY0IDE1LjQyMDA1NzIsMTQuNTIyMjUwNSBDMTUuNDIwMDU3MiwxNC42NjcxOTY0IDE1LjQ0NDIxNDksMTQuODEyMTQyNCAxNS40NTYyOTM3LDE0Ljg2MDQ1NzcgQzE1LjUxNjY4NzksMTQuODcyNTM2NiAxNS42MTMzMTg1LDE0Ljg4NDYxNTQgMTUuNzA5OTQ5MSwxNC44ODQ2MTU0IFogTTEyLjY5MDI0MTYsMjkuNSBDMTMuODYxODg4MSwyOS41IDE0LjM4MTI3NzgsMjguNzE0ODc2IDE1Ljg0MjgxNjMsMjguNzE0ODc2IEMxNy4zMjg1MTI0LDI4LjcxNDg3NiAxNy42NTQ2NDA4LDI5LjQ3NTg0MjMgMTguOTU5MTU0NSwyOS40NzU4NDIzIEMyMC4yMzk1MTA1LDI5LjQ3NTg0MjMgMjEuMDk3MTA3NCwyOC4yOTIxMTcgMjEuOTA2Mzg5MSwyNy4xMzI1NDkzIEMyMi44MTIzMDEzLDI1LjgwMzg3NzkgMjMuMTg2NzQ1MSwyNC40OTkzNjQzIDIzLjIxMDkwMjcsMjQuNDM4OTcwMSBDMjMuMTI2MzUwOSwyNC40MTQ4MTI1IDIwLjY3NDM0ODQsMjMuNDEyMjY5NSAyMC42NzQzNDg0LDIwLjU5NzkwMjEgQzIwLjY3NDM0ODQsMTguMTU3OTc4NCAyMi42MDY5NjEyLDE3LjA1ODgwNDggMjIuNzE1NjcwNywxNi45NzQyNTMgQzIxLjQzNTMxNDcsMTUuMTM4MjcwOCAxOS40OTA2MjMsMTUuMDg5OTU1NSAxOC45NTkxNTQ1LDE1LjA4OTk1NTUgQzE3LjUyMTc3MzcsMTUuMDg5OTU1NSAxNi4zNTAxMjcxLDE1Ljk1OTYzMTMgMTUuNjEzMzE4NSwxNS45NTk2MzEzIEMxNC44MTYxMTU3LDE1Ljk1OTYzMTMgMTMuNzY1MjU3NSwxNS4xMzgyNzA4IDEyLjUyMTEzOCwxNS4xMzgyNzA4IEMxMC4xNTM2ODcyLDE1LjEzODI3MDggNy43NSwxNy4wOTUwNDEzIDcuNzUsMjAuNzkxMTYzNCBDNy43NSwyMy4wODYxNDExIDguNjQzODMzNDQsMjUuNTEzOTg2IDkuNzQzMDA2OTksMjcuMDg0MjMzOSBDMTAuNjg1MTU1OCwyOC40MTI5MDUzIDExLjUwNjUxNjIsMjkuNSAxMi42OTAyNDE2LDI5LjUgWiIgaWQ9Iu+jvyIgZmlsbD0iI0ZGRkZGRiIgZmlsbC1ydWxlPSJub256ZXJvIj48L3BhdGg+CiAgICA8L2c+Cjwvc3ZnPg=="
diff --git a/src/web/src/app/(auth)/sign-in/page.test.ts b/src/web/src/app/(auth)/sign-in/page.test.ts
new file mode 100644
index 000000000..e0131226f
--- /dev/null
+++ b/src/web/src/app/(auth)/sign-in/page.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it, vi } from "vitest"
+
+const mocks = vi.hoisted(() => ({
+ getCloudflareContext: vi.fn(),
+}))
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: mocks.getCloudflareContext,
+}))
+vi.mock("./sign-in-client", () => ({
+ default: () => null,
+}))
+
+import SignInPage from "./page"
+
+describe("sign-in server configuration", () => {
+ it("passes a disabled Apple flag when all Apple secrets are absent", async () => {
+ mocks.getCloudflareContext.mockResolvedValueOnce({
+ env: { NODE_ENV: "production" },
+ })
+
+ const page = await SignInPage()
+
+ expect(page.props).toMatchObject({ isProd: true, appleEnabled: false })
+ })
+
+ it("passes only an enabled boolean when all Apple secrets are present", async () => {
+ mocks.getCloudflareContext.mockResolvedValueOnce({
+ env: {
+ NODE_ENV: "development",
+ APPLE_CLIENT_ID: "ai.alook.web",
+ APPLE_TEAM_ID: "TEAM123456",
+ APPLE_KEY_ID: "KEY1234567",
+ APPLE_PRIVATE_KEY: "private-key-never-passed-to-the-client",
+ },
+ })
+
+ const page = await SignInPage()
+
+ expect(page.props).toMatchObject({ isProd: false, appleEnabled: true })
+ expect(JSON.stringify(page.props)).not.toContain("private-key-never-passed-to-the-client")
+ })
+
+ it("fails closed instead of rendering with partial Apple configuration", async () => {
+ mocks.getCloudflareContext.mockResolvedValueOnce({
+ env: { APPLE_CLIENT_ID: "ai.alook.web" },
+ })
+
+ await expect(SignInPage()).rejects.toThrow(
+ "Apple authentication configuration is incomplete",
+ )
+ })
+})
diff --git a/src/web/src/app/(auth)/sign-in/page.tsx b/src/web/src/app/(auth)/sign-in/page.tsx
index c8b1b280a..5bd1433c0 100644
--- a/src/web/src/app/(auth)/sign-in/page.tsx
+++ b/src/web/src/app/(auth)/sign-in/page.tsx
@@ -1,11 +1,13 @@
import { getCloudflareContext } from "@opennextjs/cloudflare"
import { resolveMode } from "@alook/shared"
+import { resolveAppleAuthConfig } from "@/lib/apple-auth"
import SignInPageClient from "./sign-in-client"
export default async function SignInPage() {
const { env } = await getCloudflareContext({ async: true })
const mode = resolveMode({ nodeEnv: env.NODE_ENV ?? process.env.NODE_ENV })
const isProd = mode === "production"
+ const appleEnabled = resolveAppleAuthConfig(env).enabled
- return <SignInPageClient isProd={isProd} />
+ return <SignInPageClient isProd={isProd} appleEnabled={appleEnabled} />
}
diff --git a/src/web/src/app/(auth)/sign-in/sign-in-client.dom.test.ts b/src/web/src/app/(auth)/sign-in/sign-in-client.dom.test.ts
new file mode 100644
index 000000000..071a9342c
--- /dev/null
+++ b/src/web/src/app/(auth)/sign-in/sign-in-client.dom.test.ts
@@ -0,0 +1,81 @@
+import { createElement } from "react"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { render, screen } from "@/test/react-dom-harness"
+
+const mocks = vi.hoisted(() => ({
+ searchParams: new URLSearchParams(),
+}))
+
+vi.mock("next/navigation", () => ({
+ useSearchParams: () => mocks.searchParams,
+}))
+vi.mock("@/lib/auth-client", () => ({
+ authClient: {},
+ signIn: {},
+ signUp: {},
+}))
+vi.mock("./sign-in-fields", () => ({
+ SignInEmailField: () => null,
+ SignInOtpField: () => null,
+}))
+vi.mock("./social-sign-in", () => ({
+ SocialSignIn: ({
+ postLoginUrl,
+ appleEnabled,
+ }: {
+ postLoginUrl: string
+ appleEnabled: boolean
+ }) => createElement("div", {
+ "data-testid": "social-sign-in-props",
+ "data-post-login-url": postLoginUrl,
+ "data-apple-enabled": String(appleEnabled),
+ }),
+}))
+vi.mock("@/components/gradient-background", () => ({
+ GradientBackground: () => null,
+}))
+vi.mock("@/components/logo", () => ({
+ Logo: () => null,
+}))
+vi.mock("@/components/home/landing-shell-motion", () => ({
+ LandingShellMotion: () => null,
+}))
+vi.mock("@/components/home/landing-shell-motion.module.css", () => ({
+ default: {},
+}))
+
+import SignInPageClient from "./sign-in-client"
+
+describe("sign-in client Apple availability", () => {
+ beforeEach(() => {
+ mocks.searchParams = new URLSearchParams("redirect=%2Fc%2Fme")
+ window.matchMedia = vi.fn(() => ({
+ matches: false,
+ addEventListener: vi.fn(),
+ removeEventListener: vi.fn(),
+ })) as never
+ })
+
+ it.each([true, false])("passes server-derived appleEnabled=%s unchanged", (appleEnabled) => {
+ render(createElement(SignInPageClient, { isProd: true, appleEnabled }))
+
+ const social = screen.getByTestId("social-sign-in-props")
+ expect(social).toHaveAttribute("data-post-login-url", "/c/me")
+ expect(social).toHaveAttribute("data-apple-enabled", String(appleEnabled))
+ })
+
+ it.each([
+ [true, "Send Code"],
+ [false, "Sign in"],
+ ] as const)("uses the former social outline style for the email action when isProd=%s", (isProd, label) => {
+ render(createElement(SignInPageClient, { isProd, appleEnabled: true }))
+
+ expect(screen.getByRole("button", { name: label })).toHaveClass(
+ "h-9",
+ "border-border",
+ "bg-background",
+ "text-base",
+ "w-full",
+ )
+ })
+})
diff --git a/src/web/src/app/(auth)/sign-in/sign-in-client.tsx b/src/web/src/app/(auth)/sign-in/sign-in-client.tsx
index 7178d66ec..d3ec211c4 100644
--- a/src/web/src/app/(auth)/sign-in/sign-in-client.tsx
+++ b/src/web/src/app/(auth)/sign-in/sign-in-client.tsx
@@ -37,7 +37,17 @@ function safeRedirectUrl(redirect: string | null): string {
return DEFAULT_POST_LOGIN
}
-function SignInForm({ postLoginUrl, isProd, accountDeleted }: { postLoginUrl: string; isProd: boolean; accountDeleted: boolean }) {
+function SignInForm({
+ postLoginUrl,
+ isProd,
+ accountDeleted,
+ appleEnabled,
+}: {
+ postLoginUrl: string
+ isProd: boolean
+ accountDeleted: boolean
+ appleEnabled: boolean
+}) {
const [email, setEmail] = useState("")
const [emailError, setEmailError] = useState("")
const [otpError, setOtpError] = useState("")
@@ -193,9 +203,11 @@ function SignInForm({ postLoginUrl, isProd, accountDeleted }: { postLoginUrl: st
/>
<Field>
<Button
+ variant="outline"
+ size="lg"
type="submit"
disabled={loading || isCoolingDown}
- className="w-full"
+ className="w-full text-base"
>
{sendLabel}
</Button>
@@ -239,7 +251,13 @@ function SignInForm({ postLoginUrl, isProd, accountDeleted }: { postLoginUrl: st
}}
/>
<Field>
- <Button type="submit" disabled={loading} className="w-full">
+ <Button
+ variant="outline"
+ size="lg"
+ type="submit"
+ disabled={loading}
+ className="w-full text-base"
+ >
{loading ? "Signing in..." : "Sign in"}
</Button>
</Field>
@@ -250,7 +268,7 @@ function SignInForm({ postLoginUrl, isProd, accountDeleted }: { postLoginUrl: st
<FieldSeparator className="*:data-[slot=field-separator-content]:bg-card">
Or continue with
</FieldSeparator>
- <SocialSignIn postLoginUrl={postLoginUrl} />
+ <SocialSignIn postLoginUrl={postLoginUrl} appleEnabled={appleEnabled} />
</FieldGroup>
)
}
@@ -361,7 +379,13 @@ function ProductGallery() {
)
}
-export default function SignInPageClient({ isProd }: { isProd: boolean }) {
+export default function SignInPageClient({
+ isProd,
+ appleEnabled,
+}: {
+ isProd: boolean
+ appleEnabled: boolean
+}) {
const searchParams = useSearchParams()
const postLoginUrl = safeRedirectUrl(searchParams.get("redirect"))
const accountDeleted = searchParams.get("account_deleted") === "1"
@@ -377,7 +401,12 @@ export default function SignInPageClient({ isProd }: { isProd: boolean }) {
<Card className="overflow-hidden p-0">
<CardContent className="grid p-0 sm:grid-cols-[minmax(320px,0.82fr)_minmax(0,1.35fr)]">
<div className="flex flex-col justify-center p-6 sm:min-h-120 sm:p-8">
- <SignInForm postLoginUrl={postLoginUrl} isProd={isProd} accountDeleted={accountDeleted} />
+ <SignInForm
+ postLoginUrl={postLoginUrl}
+ isProd={isProd}
+ accountDeleted={accountDeleted}
+ appleEnabled={appleEnabled}
+ />
</div>
<div className="relative hidden min-h-120 overflow-hidden bg-muted sm:block">
<ProductGallery />
diff --git a/src/web/src/app/(auth)/sign-in/social-sign-in.dom.test.ts b/src/web/src/app/(auth)/sign-in/social-sign-in.dom.test.ts
index 2880bc9e7..cd19490e8 100644
--- a/src/web/src/app/(auth)/sign-in/social-sign-in.dom.test.ts
+++ b/src/web/src/app/(auth)/sign-in/social-sign-in.dom.test.ts
@@ -1,8 +1,15 @@
import { createElement } from "react"
+import { createHash } from "node:crypto"
+import { existsSync, readFileSync } from "node:fs"
+import { resolve } from "node:path"
import { beforeEach, describe, expect, it, vi } from "vitest"
import type { NativeOauthView } from "@/lib/native-oauth-client"
import { act, render, screen, setupUser } from "@/test/react-dom-harness"
+const webRoot = existsSync(resolve(process.cwd(), "next.config.ts"))
+ ? process.cwd()
+ : resolve(process.cwd(), "src/web")
+
const mocks = vi.hoisted(() => ({
tauri: false,
social: vi.fn(),
@@ -59,6 +66,110 @@ describe("social sign-in native boundary", () => {
expect(mocks.start).not.toHaveBeenCalled()
})
+ it("keeps every provider's icon and title together at the visual center", async () => {
+ const user = setupUser()
+ render(createElement(SocialSignIn, {
+ postLoginUrl: "/c/me?tab=1",
+ appleEnabled: true,
+ }))
+
+ const socialButtons = screen.getAllByRole("button")
+ expect(socialButtons.map((item) => item.dataset.testid)).toEqual([
+ "native-oauth-github",
+ "native-oauth-google",
+ "native-oauth-apple",
+ ])
+ const github = button("native-oauth-github")
+ const google = button("native-oauth-google")
+ const apple = button("native-oauth-apple")
+ for (const provider of [github, google, apple]) {
+ expect(provider).toHaveClass(
+ "h-9",
+ "border-0",
+ "bg-apple-signin",
+ "text-base",
+ "text-apple-signin-foreground",
+ "hover:bg-apple-signin",
+ )
+ }
+ for (const provider of ["github", "google", "apple"]) {
+ expect(screen.getByTestId(`native-oauth-${provider}-content`))
+ .toHaveClass("inline-flex", "items-center", "gap-2")
+ }
+ expect(apple).toHaveClass("col-span-2")
+ expect(apple).toHaveClass("min-w-35")
+ expect(apple).toHaveAccessibleName("Continue with Apple")
+ expect(apple.tabIndex).toBe(0)
+ apple.focus()
+ expect(apple).toHaveFocus()
+
+ await user.click(apple)
+ expect(mocks.social).toHaveBeenCalledWith({
+ provider: "apple",
+ callbackURL: "/c/me?tab=1",
+ })
+ expect(mocks.start).not.toHaveBeenCalled()
+ })
+
+ it("keeps every provider on Apple's mandated black-on-light and white-on-dark tokens", () => {
+ const globalsCss = readFileSync(resolve(webRoot, "src/app/globals.css"), "utf8")
+ expect(globalsCss).toMatch(
+ /:root\s*\{[^}]*--apple-signin:\s*oklch\(0 0 0\);[^}]*--apple-signin-foreground:\s*oklch\(1 0 0\);/s,
+ )
+ expect(globalsCss).toMatch(
+ /\.dark\s*\{[^}]*--apple-signin:\s*oklch\(1 0 0\);[^}]*--apple-signin-foreground:\s*oklch\(0 0 0\);/s,
+ )
+ expect(globalsCss).not.toContain("apple-signin-hover")
+ })
+
+ it("embeds Apple's official left-aligned logo-with-text artwork", () => {
+ render(createElement(SocialSignIn, {
+ postLoginUrl: "/c/me",
+ appleEnabled: true,
+ }))
+
+ const source = readFileSync(resolve(
+ webRoot,
+ "src/app/(auth)/sign-in/social-sign-in.tsx",
+ ), "utf8")
+ const artwork = readFileSync(resolve(
+ webRoot,
+ "src/app/(auth)/sign-in/apple-sign-in-artwork.ts",
+ ), "utf8")
+ expect(source).not.toContain("SiApple")
+ expect(source).not.toContain("appleid.cdn-apple.com/appleid/button/logo")
+ expect(artwork).not.toContain("appleid.cdn-apple.com/appleid/button/logo")
+ expect(artwork).toContain("Logo-Sign-in-with-Apple.dmg")
+ expect(artwork).toContain("Sign in with Apple - Left Aligned")
+ const white = screen.getByTestId("apple-official-left-aligned-logo-white")
+ const black = screen.getByTestId("apple-official-left-aligned-logo-black")
+ expect(white).toHaveAttribute(
+ "src",
+ expect.stringMatching(/^data:image\/svg\+xml;base64,/),
+ )
+ expect(white).toHaveAttribute("width", "31")
+ expect(white).toHaveAttribute("height", "44")
+ expect(white).toHaveClass("col-start-1", "row-start-1", "h-9", "w-auto", "dark:hidden")
+ expect(black).toHaveAttribute(
+ "src",
+ expect.stringMatching(/^data:image\/svg\+xml;base64,/),
+ )
+ expect(black).toHaveAttribute("width", "31")
+ expect(black).toHaveAttribute("height", "44")
+ expect(black).toHaveClass("col-start-1", "row-start-1", "h-9", "w-auto", "dark:block")
+ expect([white, black].map((image) => createHash("sha256")
+ .update(Buffer.from(image.getAttribute("src")!.split(",")[1], "base64"))
+ .digest("hex"))).toEqual([
+ "f43d1ed5be59bcffdf4c20b5e29f8de041858678f549515377d0ba4f5ebd115e",
+ "0f56330a7a4fe2db06ec79fdbfed1eec1d434557f052add6d848daa31877f380",
+ ])
+ })
+
+ it("does not expose Apple when server configuration is absent", () => {
+ render(createElement(SocialSignIn, { postLoginUrl: "/c/me" }))
+ expect(screen.queryByTestId("native-oauth-apple")).not.toBeInTheDocument()
+ })
+
it("never falls back to embedded social OAuth in Tauri, including unsupported apps", async () => {
const user = setupUser()
mocks.tauri = true
@@ -74,6 +185,26 @@ describe("social sign-in native boundary", () => {
expect(screen.getByRole("alert")).toHaveTextContent("You can still use email")
})
+ it("disables only Apple when an older app rejects that provider", () => {
+ mocks.tauri = true
+ render(createElement(SocialSignIn, {
+ postLoginUrl: "/c/me",
+ appleEnabled: true,
+ }))
+
+ act(() => mocks.emit!({
+ phase: "error",
+ message: "apple_update_required",
+ attempt: null,
+ }))
+
+ expect(button("native-oauth-apple")).toBeDisabled()
+ expect(button("native-oauth-github")).toBeEnabled()
+ expect(button("native-oauth-google")).toBeEnabled()
+ expect(screen.queryByTestId("native-oauth-retry")).not.toBeInTheDocument()
+ expect(screen.getByRole("alert")).toHaveTextContent("GitHub, Google, and email still work")
+ })
+
it("shows bounded progress, Cancel and Retry controls without rendering proof data", async () => {
const user = setupUser()
mocks.tauri = true
diff --git a/src/web/src/app/(auth)/sign-in/social-sign-in.tsx b/src/web/src/app/(auth)/sign-in/social-sign-in.tsx
index 76cdf6ebc..cb43b4a9c 100644
--- a/src/web/src/app/(auth)/sign-in/social-sign-in.tsx
+++ b/src/web/src/app/(auth)/sign-in/social-sign-in.tsx
@@ -1,12 +1,17 @@
"use client"
import { useEffect, useRef, useState } from "react"
-import { isTauri, safeRedirectPath } from "@alook/shared"
+import { isTauri, safeRedirectPath, type NativeOauthProvider } from "@alook/shared"
import { SiGithub, SiGoogle } from "@icons-pack/react-simple-icons"
+import Image from "next/image"
import { Button } from "@/components/ui/button"
import { Field } from "@/components/ui/field"
import { signIn } from "@/lib/auth-client"
import { createNativeOauthController, nativeOauthBrowserDeps, type NativeOauthView } from "@/lib/native-oauth-client"
+import {
+ APPLE_LEFT_ALIGNED_LOGO_BLACK,
+ APPLE_LEFT_ALIGNED_LOGO_WHITE,
+} from "./apple-sign-in-artwork"
const messages = {
start_failed: "Couldn't open sign-in. Try again.",
@@ -15,12 +20,19 @@ const messages = {
invalid_callback: "That sign-in link wasn't valid. Waiting for your browser to finish.",
retry_required: "Couldn't confirm sign-in. Try again to start a new attempt.",
unavailable: "Sign-in is unavailable. Try again or use email.",
+ apple_update_required: "Update Alook to continue with Apple. GitHub, Google, and email still work.",
} as const
-export function SocialSignIn({ postLoginUrl }: { postLoginUrl: string }) {
+export function SocialSignIn({
+ postLoginUrl,
+ appleEnabled = false,
+}: {
+ postLoginUrl: string
+ appleEnabled?: boolean
+}) {
const controller = useRef<ReturnType<typeof createNativeOauthController> | null>(null)
const [native, setNative] = useState<NativeOauthView | null>(null)
- const lastProvider = useRef<"github" | "google">("github")
+ const lastProvider = useRef<NativeOauthProvider>("github")
useEffect(() => {
if (!isTauri()) return
const instance = createNativeOauthController(nativeOauthBrowserDeps, setNative)
@@ -28,14 +40,15 @@ export function SocialSignIn({ postLoginUrl }: { postLoginUrl: string }) {
void instance.connect()
return () => { instance.dispose(); if (controller.current === instance) controller.current = null }
}, [])
- const begin = (provider: "github" | "google") => {
+ const begin = (provider: NativeOauthProvider) => {
lastProvider.current = provider
if (!isTauri()) { void signIn.social({ provider, callbackURL: postLoginUrl }); return }
if (controller.current) void controller.current.start(provider, safeRedirectPath(postLoginUrl))
}
const busy = native?.phase === "initializing" || native?.phase === "preparing" || native?.phase === "exchanging" || native?.phase === "checking_status"
const unsupported = native?.phase === "unsupported"
- const text = unsupported ? "Update Alook to sign in with GitHub or Google. You can still use email."
+ const appleUpdateRequired = native?.message === "apple_update_required"
+ const text = unsupported ? "Update Alook to use social sign-in. You can still use email."
: native?.message ? messages[native.message]
: native?.phase === "preparing" ? "Opening sign-in in your browser…"
: native?.phase === "exchanging" || native?.phase === "checking_status" ? "Confirming sign-in…"
@@ -44,15 +57,69 @@ export function SocialSignIn({ postLoginUrl }: { postLoginUrl: string }) {
return (
<>
<Field className="grid grid-cols-2 gap-4">
- <Button variant="outline" type="button" disabled={busy || unsupported} data-testid="native-oauth-github" onClick={() => begin("github")}>
- <SiGithub className="size-4" />GitHub
+ <Button
+ size="lg"
+ type="button"
+ disabled={busy || unsupported}
+ className="border-0 bg-apple-signin text-base text-apple-signin-foreground hover:bg-apple-signin"
+ data-testid="native-oauth-github"
+ onClick={() => begin("github")}
+ >
+ <span className="inline-flex items-center gap-2" data-testid="native-oauth-github-content">
+ <SiGithub className="size-4" aria-hidden />
+ <span>GitHub</span>
+ </span>
</Button>
- <Button variant="outline" type="button" disabled={busy || unsupported} data-testid="native-oauth-google" onClick={() => begin("google")}>
- <SiGoogle className="size-4" />Google
+ <Button
+ size="lg"
+ type="button"
+ disabled={busy || unsupported}
+ className="border-0 bg-apple-signin text-base text-apple-signin-foreground hover:bg-apple-signin"
+ data-testid="native-oauth-google"
+ onClick={() => begin("google")}
+ >
+ <span className="inline-flex items-center gap-2" data-testid="native-oauth-google-content">
+ <SiGoogle className="size-4" aria-hidden />
+ <span>Google</span>
+ </span>
</Button>
+ {appleEnabled ? (
+ <Button
+ type="button"
+ size="lg"
+ disabled={busy || unsupported || appleUpdateRequired}
+ className="col-span-2 min-w-35 border-0 bg-apple-signin text-base text-apple-signin-foreground hover:bg-apple-signin"
+ data-testid="native-oauth-apple"
+ onClick={() => begin("apple")}
+ >
+ <span className="inline-flex items-center gap-2" data-testid="native-oauth-apple-content">
+ <span className="grid h-9 place-items-center" aria-hidden>
+ <Image
+ src={APPLE_LEFT_ALIGNED_LOGO_WHITE}
+ alt=""
+ width={31}
+ height={44}
+ unoptimized
+ className="col-start-1 row-start-1 h-9 w-auto dark:hidden"
+ data-testid="apple-official-left-aligned-logo-white"
+ />
+ <Image
+ src={APPLE_LEFT_ALIGNED_LOGO_BLACK}
+ alt=""
+ width={31}
+ height={44}
+ unoptimized
+ className="col-start-1 row-start-1 hidden h-9 w-auto dark:block"
+ data-testid="apple-official-left-aligned-logo-black"
+ />
+ </span>
+ <span>Continue with Apple</span>
+ </span>
+ </Button>
+ ) : null}
</Field>
{text && <p role={native?.phase === "error" || unsupported ? "alert" : "status"} className="text-sm text-muted-foreground" data-testid="native-oauth-status">{text}</p>}
- {!unsupported && native && (native.attempt || native.phase === "error" || native.phase === "preparing") && (
+ {!unsupported && !appleUpdateRequired && native && (native.attempt || native.phase === "error" || native.phase === "preparing") && (
<div className="flex gap-2">
{(native.attempt || native.phase === "preparing") && <Button type="button" variant="ghost" data-testid="native-oauth-cancel" onClick={() => { void controller.current?.cancel() }}>Cancel</Button>}
<Button type="button" variant="outline" disabled={busy} data-testid="native-oauth-retry" onClick={() => begin(native.attempt?.provider ?? lastProvider.current)}>Try again</Button>
diff --git a/src/web/src/app/globals.css b/src/web/src/app/globals.css
index c0ff6a95d..d1250e696 100644
--- a/src/web/src/app/globals.css
+++ b/src/web/src/app/globals.css
@@ -48,6 +48,8 @@
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
+ --color-apple-signin: var(--apple-signin);
+ --color-apple-signin-foreground: var(--apple-signin-foreground);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
@@ -499,6 +501,8 @@ body.driver-active .community-ws-reconnect-overlay * {
--popover-foreground: oklch(0.18 0.03 230);
--primary: oklch(0.22 0.03 230);
--primary-foreground: oklch(0.985 0.005 80);
+ --apple-signin: oklch(0 0 0);
+ --apple-signin-foreground: oklch(1 0 0);
--secondary: oklch(0.96 0.006 80);
--secondary-foreground: oklch(0.22 0.03 230);
--shimmer: rgba(0, 0, 0, 0.06);
@@ -553,6 +557,8 @@ body.driver-active .community-ws-reconnect-overlay * {
--popover-foreground: oklch(0.93 0.006 80);
--primary: oklch(0.9 0.008 80);
--primary-foreground: oklch(0.21 0.008 60);
+ --apple-signin: oklch(1 0 0);
+ --apple-signin-foreground: oklch(0 0 0);
--secondary: oklch(0.27 0.008 60);
--secondary-foreground: oklch(0.93 0.006 80);
--shimmer: rgba(255, 255, 255, 0.06);
diff --git a/src/web/src/env.d.ts b/src/web/src/env.d.ts
index eddb187ce..13132b294 100644
--- a/src/web/src/env.d.ts
+++ b/src/web/src/env.d.ts
@@ -6,6 +6,10 @@ interface RuntimeEnv {
NODE_ENV?: string
DEV_WS_DO_URL?: string
DEV_WAKE_WORKER_URL?: string
+ APPLE_CLIENT_ID?: string
+ APPLE_TEAM_ID?: string
+ APPLE_KEY_ID?: string
+ APPLE_PRIVATE_KEY?: string
}
declare namespace Cloudflare {
diff --git a/src/web/src/lib/account-deletion/execution.test.ts b/src/web/src/lib/account-deletion/execution.test.ts
index a722be8a3..7b9ebe0fa 100644
--- a/src/web/src/lib/account-deletion/execution.test.ts
+++ b/src/web/src/lib/account-deletion/execution.test.ts
@@ -141,7 +141,7 @@ describe("account deletion execution", () => {
{ waitUntil: vi.fn() },
"user-1",
)).resolves.toEqual({ kind: "failed" })
- expect(mocks.getSnapshot).toHaveBeenCalledOnce()
+ expect(mocks.getSnapshot).toHaveBeenCalledTimes(2)
expect(mocks.deleteRows).not.toHaveBeenCalled()
})
@@ -205,6 +205,61 @@ describe("account deletion execution", () => {
)
})
+ it("revokes Apple synchronously before deleting local account rows", async () => {
+ const current = {
+ ...snapshot("current"),
+ providers: [{
+ providerId: "apple",
+ accountId: "stable-sub",
+ accessToken: "access",
+ refreshToken: "refresh",
+ }],
+ }
+ mocks.getSnapshot.mockResolvedValue(current)
+ mocks.deleteRows.mockResolvedValue({ deleted: true, readStateRevisions: [] })
+
+ await expect(executeAccountDeletion(
+ {} as never,
+ {} as never,
+ { waitUntil: vi.fn() },
+ "user-1",
+ )).resolves.toEqual({ kind: "deleted" })
+
+ expect(mocks.revokeProvider).toHaveBeenCalledOnce()
+ expect(mocks.revokeProvider).toHaveBeenCalledWith(expect.anything(), current.providers[0])
+ expect(mocks.revokeProvider.mock.invocationCallOrder[0])
+ .toBeLessThan(mocks.deleteStorage.mock.invocationCallOrder[0])
+ expect(mocks.deleteStorage.mock.invocationCallOrder[0])
+ .toBeLessThan(mocks.deleteStorage.mock.invocationCallOrder[1])
+ expect(mocks.deleteStorage.mock.invocationCallOrder[1])
+ .toBeLessThan(mocks.deleteRows.mock.invocationCallOrder[0])
+ })
+
+ it("preserves the local account when Apple revocation fails", async () => {
+ const current = {
+ ...snapshot("current"),
+ providers: [{
+ providerId: "apple",
+ accountId: "stable-sub",
+ accessToken: "access",
+ refreshToken: "refresh",
+ }],
+ }
+ mocks.getSnapshot.mockResolvedValue(current)
+ mocks.revokeProvider.mockRejectedValue(new Error("Apple unavailable"))
+
+ await expect(executeAccountDeletion(
+ {} as never,
+ {} as never,
+ { waitUntil: vi.fn() },
+ "user-1",
+ )).resolves.toEqual({ kind: "failed" })
+
+ expect(mocks.deleteStorage).not.toHaveBeenCalled()
+ expect(mocks.deleteRows).not.toHaveBeenCalled()
+ expect(mocks.invalidateMany).not.toHaveBeenCalled()
+ })
+
it("keeps a committed deletion successful when machine-token invalidation fails", async () => {
const current = {
...snapshot("current"),
diff --git a/src/web/src/lib/account-deletion/execution.ts b/src/web/src/lib/account-deletion/execution.ts
index fa63fb8d8..8d578707d 100644
--- a/src/web/src/lib/account-deletion/execution.ts
+++ b/src/web/src/lib/account-deletion/execution.ts
@@ -44,7 +44,9 @@ function scheduleAfterCommit(
revision: revision.revision,
inboxChanged: true,
})),
- ...snapshot.providers.map((provider) => revokeProviderAccount(env, provider)),
+ ...snapshot.providers
+ .filter((provider) => provider.providerId !== "apple")
+ .map((provider) => revokeProviderAccount(env, provider)),
]).then((results) => {
const failures = results.filter((result) => result.status === "rejected").length
if (failures > 0) log.warn("account_deletion_post_commit_effects_failed", { failures })
@@ -65,11 +67,11 @@ export async function executeAccountDeletion(
try {
const firstSnapshot = await queries.accountDeletion.getAccountDeletionSnapshot(db, userId)
if (!firstSnapshot) return { kind: "missing" }
- await deleteAccountStorage(env, firstSnapshot)
const finalDb = getPrimaryDb(env.DB)
const finalSnapshot = await queries.accountDeletion.getAccountDeletionSnapshot(finalDb, userId)
if (!finalSnapshot) {
+ await deleteAccountStorage(env, firstSnapshot)
await invalidateMachineTokens(firstSnapshot.machineTokens)
return { kind: "missing" }
}
@@ -77,6 +79,12 @@ export async function executeAccountDeletion(
...firstSnapshot.machineTokens,
...finalSnapshot.machineTokens,
])]
+ await Promise.all(
+ finalSnapshot.providers
+ .filter((provider) => provider.providerId === "apple")
+ .map((provider) => revokeProviderAccount(env, provider)),
+ )
+ await deleteAccountStorage(env, firstSnapshot)
await deleteAccountStorage(env, finalSnapshot)
let deletion: Awaited<ReturnType<typeof queries.accountDeletion.deleteAccountRows>>
diff --git a/src/web/src/lib/account-deletion/provider-revocation.test.ts b/src/web/src/lib/account-deletion/provider-revocation.test.ts
index 82f2c6d58..491393c54 100644
--- a/src/web/src/lib/account-deletion/provider-revocation.test.ts
+++ b/src/web/src/lib/account-deletion/provider-revocation.test.ts
@@ -1,7 +1,41 @@
-import { afterEach, describe, expect, it, vi } from "vitest"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+
+const appleMocks = vi.hoisted(() => ({
+ generateClientSecret: vi.fn(),
+ resolveConfig: vi.fn(),
+}))
+
+vi.mock("@/lib/apple-auth", () => ({
+ generateAppleClientSecret: appleMocks.generateClientSecret,
+ resolveAppleAuthConfig: appleMocks.resolveConfig,
+}))
+
import { revokeProviderAccount } from "./provider-revocation"
+const appleEnv = {
+ APPLE_CLIENT_ID: "ai.alook.web",
+ APPLE_TEAM_ID: "TEAM123456",
+ APPLE_KEY_ID: "KEY1234567",
+ APPLE_PRIVATE_KEY: "fake-private-key",
+ GITHUB_CLIENT_ID: "github-client",
+ GITHUB_CLIENT_SECRET: "github-secret",
+}
+
describe("account deletion provider revocation", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ appleMocks.resolveConfig.mockReturnValue({
+ enabled: true,
+ config: {
+ clientId: appleEnv.APPLE_CLIENT_ID,
+ teamId: appleEnv.APPLE_TEAM_ID,
+ keyId: appleEnv.APPLE_KEY_ID,
+ privateKey: appleEnv.APPLE_PRIVATE_KEY,
+ },
+ })
+ appleMocks.generateClientSecret.mockResolvedValue("signed-client-secret")
+ })
+
afterEach(() => vi.unstubAllGlobals())
it("revokes Google with the refresh token", async () => {
@@ -55,4 +89,132 @@ describe("account deletion provider revocation", () => {
await expect(failure).rejects.toThrow("provider revocation returned 401")
await expect(failure).rejects.not.toThrow("private-access-token")
})
+
+ it.each([
+ {
+ name: "refresh token",
+ accessToken: "apple-access",
+ refreshToken: "apple-refresh",
+ expectedToken: "apple-refresh",
+ expectedHint: "refresh_token",
+ },
+ {
+ name: "access token fallback",
+ accessToken: "apple-access",
+ refreshToken: null,
+ expectedToken: "apple-access",
+ expectedHint: "access_token",
+ },
+ {
+ name: "access token fallback for an empty refresh token",
+ accessToken: "apple-access",
+ refreshToken: "",
+ expectedToken: "apple-access",
+ expectedHint: "access_token",
+ },
+ ])("revokes Apple with the $name before local deletion", async ({
+ accessToken,
+ refreshToken,
+ expectedToken,
+ expectedHint,
+ }) => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 200 }))
+ vi.stubGlobal("fetch", fetchMock)
+
+ await revokeProviderAccount(appleEnv, {
+ providerId: "apple",
+ accountId: "stable-sub",
+ accessToken,
+ refreshToken,
+ })
+
+ const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]
+ expect(url).toBe("https://appleid.apple.com/auth/revoke")
+ expect(init).toMatchObject({
+ method: "POST",
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
+ })
+ expect(Object.fromEntries((init.body as URLSearchParams).entries())).toEqual({
+ client_id: appleEnv.APPLE_CLIENT_ID,
+ client_secret: "signed-client-secret",
+ token: expectedToken,
+ token_type_hint: expectedHint,
+ })
+ expect(appleMocks.generateClientSecret).toHaveBeenCalledOnce()
+ })
+
+ it("fails closed without an Apple token", async () => {
+ const fetchMock = vi.fn()
+ vi.stubGlobal("fetch", fetchMock)
+
+ await expect(revokeProviderAccount(appleEnv, {
+ providerId: "apple",
+ accountId: "stable-sub",
+ accessToken: null,
+ refreshToken: null,
+ })).rejects.toThrow("Apple provider revocation token is unavailable")
+
+ expect(fetchMock).not.toHaveBeenCalled()
+ expect(appleMocks.generateClientSecret).not.toHaveBeenCalled()
+ })
+
+ it("fails closed when Apple revocation configuration is absent", async () => {
+ appleMocks.resolveConfig.mockReturnValue({ enabled: false })
+ const fetchMock = vi.fn()
+ vi.stubGlobal("fetch", fetchMock)
+
+ await expect(revokeProviderAccount(appleEnv, {
+ providerId: "apple",
+ accountId: "stable-sub",
+ accessToken: "apple-access",
+ refreshToken: null,
+ })).rejects.toThrow("Apple provider revocation configuration is unavailable")
+
+ expect(fetchMock).not.toHaveBeenCalled()
+ expect(appleMocks.generateClientSecret).not.toHaveBeenCalled()
+ })
+
+ it("propagates value-free partial-configuration failures", async () => {
+ appleMocks.resolveConfig.mockImplementation(() => {
+ throw new Error("Apple authentication configuration is incomplete")
+ })
+
+ const failure = revokeProviderAccount(appleEnv, {
+ providerId: "apple",
+ accountId: "stable-sub",
+ accessToken: "private-apple-access-token",
+ refreshToken: null,
+ })
+
+ await expect(failure).rejects.toThrow("Apple authentication configuration is incomplete")
+ await expect(failure).rejects.not.toThrow(appleEnv.APPLE_PRIVATE_KEY)
+ })
+
+ it("fails closed when Apple's revocation endpoint is unreachable", async () => {
+ const fetchMock = vi.fn().mockRejectedValue(new TypeError("network unavailable"))
+ vi.stubGlobal("fetch", fetchMock)
+
+ await expect(revokeProviderAccount(appleEnv, {
+ providerId: "apple",
+ accountId: "stable-sub",
+ accessToken: "apple-access",
+ refreshToken: null,
+ })).rejects.toThrow("network unavailable")
+ })
+
+ it("does not expose Apple tokens or client secrets in provider errors", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 503 }))
+ vi.stubGlobal("fetch", fetchMock)
+
+ const failure = revokeProviderAccount(appleEnv, {
+ providerId: "apple",
+ accountId: "stable-sub",
+ accessToken: "private-apple-access-token",
+ refreshToken: null,
+ })
+
+ await expect(failure).rejects.toThrow("provider revocation returned 503")
+ await expect(failure).rejects.not.toThrow("private-apple-access-token")
+ await expect(failure).rejects.not.toThrow("signed-client-secret")
+ })
})
diff --git a/src/web/src/lib/account-deletion/provider-revocation.ts b/src/web/src/lib/account-deletion/provider-revocation.ts
index 7d5367f4e..66b013899 100644
--- a/src/web/src/lib/account-deletion/provider-revocation.ts
+++ b/src/web/src/lib/account-deletion/provider-revocation.ts
@@ -1,4 +1,5 @@
import type { queries } from "@alook/shared"
+import { generateAppleClientSecret, resolveAppleAuthConfig } from "@/lib/apple-auth"
type Provider = queries.accountDeletion.AccountDeletionSnapshot["providers"][number]
@@ -13,7 +14,15 @@ async function providerFetch(url: string, init: RequestInit): Promise<void> {
}
export async function revokeProviderAccount(
- env: Pick<Env, "GITHUB_CLIENT_ID" | "GITHUB_CLIENT_SECRET">,
+ env: Pick<
+ Env,
+ | "GITHUB_CLIENT_ID"
+ | "GITHUB_CLIENT_SECRET"
+ | "APPLE_CLIENT_ID"
+ | "APPLE_TEAM_ID"
+ | "APPLE_KEY_ID"
+ | "APPLE_PRIVATE_KEY"
+ >,
provider: Provider,
): Promise<void> {
if (provider.providerId === "google") {
@@ -41,5 +50,27 @@ export async function revokeProviderAccount(
},
body: JSON.stringify({ access_token: provider.accessToken }),
})
+ return
+ }
+
+ if (provider.providerId === "apple") {
+ const refreshToken = provider.refreshToken || undefined
+ const token = refreshToken ?? provider.accessToken
+ if (!token) throw new Error("Apple provider revocation token is unavailable")
+
+ const state = resolveAppleAuthConfig(env)
+ if (!state.enabled) throw new Error("Apple provider revocation configuration is unavailable")
+
+ const clientSecret = await generateAppleClientSecret(state.config)
+ await providerFetch("https://appleid.apple.com/auth/revoke", {
+ method: "POST",
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
+ body: new URLSearchParams({
+ client_id: state.config.clientId,
+ client_secret: clientSecret,
+ token,
+ token_type_hint: refreshToken ? "refresh_token" : "access_token",
+ }),
+ })
}
}
diff --git a/src/web/src/lib/apple-auth.test.ts b/src/web/src/lib/apple-auth.test.ts
new file mode 100644
index 000000000..2ec96e164
--- /dev/null
+++ b/src/web/src/lib/apple-auth.test.ts
@@ -0,0 +1,183 @@
+import { decodeJwt, decodeProtectedHeader, exportJWK, importJWK, importPKCS8, jwtVerify } from "jose"
+import { describe, expect, it, vi } from "vitest"
+import {
+ APPLE_CLIENT_SECRET_TTL_SECONDS,
+ APPLE_ISSUER,
+ AppleAuthConfigurationError,
+ generateAppleClientSecret,
+ mapAppleProfileToUser,
+ resolveAppleAuthConfig,
+} from "./apple-auth"
+
+const TEST_PRIVATE_KEY = `-----BEGIN PRIVATE KEY-----
+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgiyvo0X+VQ0yIrOaN
+nlrnUclopnvuuMfoc8HHly3505OhRANCAAQWUcdZ8uTSAsFuwtNy4KtsKqgeqYxg
+l6kwL5D4N3pEGYGIDjV69Sw0zAt43480WqJv7HCL0mQnyqFmSrxj8jMa
+-----END PRIVATE KEY-----`
+
+const completeEnv = {
+ APPLE_CLIENT_ID: "ai.alook.web",
+ APPLE_TEAM_ID: "TEAM123456",
+ APPLE_KEY_ID: "KEY1234567",
+ APPLE_PRIVATE_KEY: TEST_PRIVATE_KEY,
+}
+
+const partialEnvs = Array.from({ length: 14 }, (_, index) => {
+ const mask = index + 1
+ return {
+ mask,
+ env: Object.fromEntries(
+ Object.entries(completeEnv).filter((_, keyIndex) => mask & (1 << keyIndex)),
+ ),
+ }
+})
+
+describe("Apple auth configuration", () => {
+ it("disables Apple only when all four values are absent", () => {
+ expect(resolveAppleAuthConfig({})).toEqual({ enabled: false })
+ expect(resolveAppleAuthConfig({
+ APPLE_CLIENT_ID: " ",
+ APPLE_TEAM_ID: "",
+ APPLE_KEY_ID: undefined,
+ APPLE_PRIVATE_KEY: "\n",
+ })).toEqual({ enabled: false })
+ })
+
+ it.each(partialEnvs)("fails closed for partial configuration mask $mask", ({ env }) => {
+ let error: unknown
+ try {
+ resolveAppleAuthConfig(env)
+ } catch (caught) {
+ error = caught
+ }
+ expect(error).toBeInstanceOf(AppleAuthConfigurationError)
+ expect(String(error)).not.toContain(TEST_PRIVATE_KEY)
+ expect(String(error)).not.toContain(completeEnv.APPLE_KEY_ID)
+ })
+
+ it("returns trimmed complete configuration", () => {
+ expect(resolveAppleAuthConfig({
+ ...completeEnv,
+ APPLE_CLIENT_ID: ` ${completeEnv.APPLE_CLIENT_ID} `,
+ })).toEqual({
+ enabled: true,
+ config: expect.objectContaining({ clientId: completeEnv.APPLE_CLIENT_ID }),
+ })
+ })
+})
+
+describe("Apple client secret", () => {
+ it("signs the exact Apple JWT contract with a fixed ES256 key", async () => {
+ const state = resolveAppleAuthConfig(completeEnv)
+ if (!state.enabled) throw new Error("test configuration unexpectedly disabled")
+ const now = 1_800_000_000
+ const token = await generateAppleClientSecret(state.config, now)
+ const privateKey = await importPKCS8(TEST_PRIVATE_KEY, "ES256", { extractable: true })
+ const jwk = await exportJWK(privateKey)
+ delete jwk.d
+ const publicKey = await importJWK(jwk, "ES256")
+ const verified = await jwtVerify(token, publicKey, {
+ issuer: completeEnv.APPLE_TEAM_ID,
+ subject: completeEnv.APPLE_CLIENT_ID,
+ audience: APPLE_ISSUER,
+ currentDate: new Date(now * 1000),
+ })
+
+ expect(decodeProtectedHeader(token)).toEqual({ alg: "ES256", kid: completeEnv.APPLE_KEY_ID })
+ expect(decodeJwt(token)).toMatchObject({
+ iss: completeEnv.APPLE_TEAM_ID,
+ sub: completeEnv.APPLE_CLIENT_ID,
+ aud: APPLE_ISSUER,
+ iat: now,
+ exp: now + APPLE_CLIENT_SECRET_TTL_SECONDS,
+ })
+ expect(verified.payload.exp! - verified.payload.iat!).toBe(APPLE_CLIENT_SECRET_TTL_SECONDS)
+ expect(token).not.toContain(TEST_PRIVATE_KEY)
+ })
+
+ it("uses the current time when no signing clock is supplied", async () => {
+ const state = resolveAppleAuthConfig(completeEnv)
+ if (!state.enabled) throw new Error("test configuration unexpectedly disabled")
+ const before = Math.floor(Date.now() / 1000)
+ const token = await generateAppleClientSecret(state.config)
+ const after = Math.floor(Date.now() / 1000)
+ const payload = decodeJwt(token)
+
+ expect(payload.iat).toBeGreaterThanOrEqual(before)
+ expect(payload.iat).toBeLessThanOrEqual(after)
+ expect(payload.exp! - payload.iat!).toBe(APPLE_CLIENT_SECRET_TTL_SECONDS)
+ })
+})
+
+describe("Apple profile mapping", () => {
+ it("rejects an empty subject before identity or email handling", async () => {
+ const lookup = vi.fn()
+ await expect(mapAppleProfileToUser({
+ sub: " ",
+ email: "[email protected]",
+ email_verified: true,
+ }, lookup)).resolves.toEqual({ email: undefined })
+ expect(lookup).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ ["[email protected]", true],
+ ["[email protected]", "true"],
+ ])("uses a first-authorized verified email without an identity lookup: %s", async (email, verified) => {
+ const lookup = vi.fn()
+ await expect(mapAppleProfileToUser({
+ sub: "stable-sub",
+ email,
+ email_verified: verified,
+ }, lookup)).resolves.toEqual({ email, emailVerified: true })
+ expect(lookup).not.toHaveBeenCalled()
+ })
+
+ it("rejects an empty stable subject before identity lookup", async () => {
+ const lookup = vi.fn()
+ await expect(mapAppleProfileToUser({
+ sub: " ",
+ email: "[email protected]",
+ email_verified: true,
+ }, lookup)).resolves.toEqual({ email: undefined })
+ expect(lookup).not.toHaveBeenCalled()
+ })
+
+ it("rehydrates a returning Apple identity from its stored verified user", async () => {
+ const lookup = vi.fn().mockResolvedValue({
+ email: "[email protected]",
+ emailVerified: true,
+ name: "Existing Person",
+ })
+ await expect(mapAppleProfileToUser({ sub: "stable-sub" }, lookup)).resolves.toEqual({
+ email: "[email protected]",
+ emailVerified: true,
+ name: "Existing Person",
+ })
+ expect(lookup).toHaveBeenCalledWith("stable-sub")
+ })
+
+ it.each([
+ { sub: "new-sub" },
+ { sub: "new-sub", email: "[email protected]", email_verified: false },
+ ])("returns no placeholder for a never-seen identity: %o", async (profile) => {
+ const result = await mapAppleProfileToUser(
+ profile,
+ vi.fn().mockResolvedValue(null),
+ )
+ expect(result).toEqual({ email: undefined })
+ expect(JSON.stringify(result)).not.toContain("placeholder")
+ expect(JSON.stringify(result)).not.toContain("new-sub")
+ })
+
+ it("does not rehydrate an existing user whose local email is unverified", async () => {
+ await expect(mapAppleProfileToUser(
+ { sub: "stable-sub" },
+ vi.fn().mockResolvedValue({
+ email: "[email protected]",
+ emailVerified: false,
+ name: "Person",
+ }),
+ )).resolves.toEqual({ email: undefined })
+ })
+})
diff --git a/src/web/src/lib/apple-auth.ts b/src/web/src/lib/apple-auth.ts
new file mode 100644
index 000000000..03f14474b
--- /dev/null
+++ b/src/web/src/lib/apple-auth.ts
@@ -0,0 +1,96 @@
+import { importPKCS8, SignJWT } from "jose"
+
+export const APPLE_ISSUER = "https://appleid.apple.com"
+export const APPLE_CLIENT_SECRET_TTL_SECONDS = 180 * 24 * 60 * 60
+
+const APPLE_CONFIG_KEYS = [
+ "APPLE_CLIENT_ID",
+ "APPLE_TEAM_ID",
+ "APPLE_KEY_ID",
+ "APPLE_PRIVATE_KEY",
+] as const
+
+type AppleConfigKey = (typeof APPLE_CONFIG_KEYS)[number]
+
+export type AppleAuthEnv = Partial<Record<AppleConfigKey, string | undefined>>
+
+export type AppleAuthConfig = {
+ clientId: string
+ teamId: string
+ keyId: string
+ privateKey: string
+}
+
+export type AppleAuthConfigState =
+ | { enabled: false }
+ | { enabled: true; config: AppleAuthConfig }
+
+export class AppleAuthConfigurationError extends Error {
+ constructor() {
+ super("Apple authentication configuration is incomplete")
+ this.name = "AppleAuthConfigurationError"
+ }
+}
+
+export function resolveAppleAuthConfig(env: AppleAuthEnv): AppleAuthConfigState {
+ const values = APPLE_CONFIG_KEYS.map((key) => {
+ const value = env[key]
+ return typeof value === "string" ? value.trim() : ""
+ })
+ const present = values.filter(Boolean).length
+ if (present === 0) return { enabled: false }
+ if (present !== APPLE_CONFIG_KEYS.length) throw new AppleAuthConfigurationError()
+
+ const [clientId, teamId, keyId, privateKey] = values as [string, string, string, string]
+ return {
+ enabled: true,
+ config: { clientId, teamId, keyId, privateKey },
+ }
+}
+
+export async function generateAppleClientSecret(
+ config: AppleAuthConfig,
+ nowSeconds = Math.floor(Date.now() / 1000),
+): Promise<string> {
+ const key = await importPKCS8(config.privateKey, "ES256")
+ return new SignJWT({})
+ .setProtectedHeader({ alg: "ES256", kid: config.keyId })
+ .setIssuer(config.teamId)
+ .setSubject(config.clientId)
+ .setAudience(APPLE_ISSUER)
+ .setIssuedAt(nowSeconds)
+ .setExpirationTime(nowSeconds + APPLE_CLIENT_SECRET_TTL_SECONDS)
+ .sign(key)
+}
+
+export type StoredAppleUser = {
+ email: string
+ emailVerified: boolean | null
+ name: string
+}
+
+export type AppleProfileForMapping = {
+ sub: string
+ email?: string
+ email_verified?: boolean | string
+}
+
+export async function mapAppleProfileToUser(
+ profile: AppleProfileForMapping,
+ findExisting: (sub: string) => Promise<StoredAppleUser | null>,
+): Promise<{ email?: string; emailVerified?: boolean; name?: string }> {
+ const sub = profile.sub.trim()
+ if (!sub) return { email: undefined }
+
+ const email = profile.email?.trim()
+ const emailVerified = profile.email_verified === true || profile.email_verified === "true"
+ if (email && emailVerified) return { email, emailVerified: true }
+
+ const existing = await findExisting(sub)
+ if (!existing || existing.emailVerified !== true) return { email: undefined }
+ return {
+ email: existing.email,
+ emailVerified: true,
+ name: existing.name,
+ }
+}
diff --git a/src/web/src/lib/apple-oauth-hardening.test.ts b/src/web/src/lib/apple-oauth-hardening.test.ts
new file mode 100644
index 000000000..2caee9641
--- /dev/null
+++ b/src/web/src/lib/apple-oauth-hardening.test.ts
@@ -0,0 +1,687 @@
+import {
+ SignJWT,
+ createRemoteJWKSet,
+ customFetch,
+ exportJWK,
+ generateKeyPair,
+} from "jose"
+import { getTestInstance } from "better-auth/test"
+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest"
+import { APPLE_ISSUER, mapAppleProfileToUser } from "./apple-auth"
+import {
+ APPLE_JWKS_URL,
+ appleOauthHardeningPlugin,
+ verifyAppleIdToken,
+} from "./apple-oauth-hardening"
+
+const CLIENT_ID = "ai.alook.web"
+const EXPECTED_NONCE = "request-bound-nonce"
+const NOW_SECONDS = 1_800_000_000
+const NOW = new Date(NOW_SECONDS * 1000)
+
+let rsaPrivateKey: CryptoKey
+let rsaPublicKey: CryptoKey
+let otherRsaPrivateKey: CryptoKey
+let ecPrivateKey: CryptoKey
+
+beforeAll(async () => {
+ const rsa = await generateKeyPair("RS256")
+ rsaPrivateKey = rsa.privateKey
+ rsaPublicKey = rsa.publicKey
+ otherRsaPrivateKey = (await generateKeyPair("RS256")).privateKey
+ ecPrivateKey = (await generateKeyPair("ES256")).privateKey
+})
+
+type Claims = {
+ iss?: string
+ aud?: string
+ sub?: string
+ nonce?: string
+ iat?: number
+ exp?: number
+ email?: string
+ email_verified?: boolean
+}
+
+async function signToken(
+ claims: Claims = {},
+ options: { alg?: "RS256" | "ES256"; key?: CryptoKey } = {},
+): Promise<string> {
+ const alg = options.alg ?? "RS256"
+ const key = options.key ?? rsaPrivateKey
+ return new SignJWT({
+ iss: APPLE_ISSUER,
+ aud: CLIENT_ID,
+ sub: "apple-stable-subject",
+ nonce: EXPECTED_NONCE,
+ iat: NOW_SECONDS,
+ exp: NOW_SECONDS + 300,
+ ...claims,
+ })
+ .setProtectedHeader({ alg, kid: "apple-test-key" })
+ .sign(key)
+}
+
+async function sha256Hex(value: string): Promise<string> {
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value))
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("")
+}
+
+describe("Apple ID-token verification", () => {
+ it.each([
+ ["the exact nonce", async () => EXPECTED_NONCE],
+ ["Apple's SHA-256 nonce form", async () => sha256Hex(EXPECTED_NONCE)],
+ ])("accepts a valid RS256 Apple token with %s", async (_, nonce) => {
+ const token = await signToken({ nonce: await nonce() })
+ await expect(verifyAppleIdToken(token, EXPECTED_NONCE, CLIENT_ID, {
+ key: rsaPublicKey,
+ currentDate: NOW,
+ })).resolves.toBe(true)
+ })
+
+ it("loads verification keys only from Apple's fixed JWKS URL", async () => {
+ const jwk = await exportJWK(rsaPublicKey)
+ Object.assign(jwk, { kid: "apple-test-key", alg: "RS256", use: "sig" })
+ const fetchJwks = vi.fn(async (url: string) => {
+ return new Response(JSON.stringify({ keys: [jwk] }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ })
+ })
+ const jwks = createRemoteJWKSet(new URL(APPLE_JWKS_URL), {
+ [customFetch]: fetchJwks,
+ })
+
+ await expect(verifyAppleIdToken(
+ await signToken(),
+ EXPECTED_NONCE,
+ CLIENT_ID,
+ { key: jwks, currentDate: NOW },
+ )).resolves.toBe(true)
+ expect(fetchJwks).toHaveBeenCalledOnce()
+ expect(fetchJwks.mock.calls[0]?.[0]).toBe(APPLE_JWKS_URL)
+ })
+
+ it.each([
+ ["wrong issuer", { iss: "https://attacker.example" }],
+ ["wrong audience", { aud: "another.service" }],
+ ["wrong nonce", { nonce: "another-request" }],
+ ["expired token", { exp: NOW_SECONDS - 1 }],
+ ["token older than one hour", { iat: NOW_SECONDS - 3601 }],
+ ["empty subject", { sub: "" }],
+ ["empty nonce", { nonce: "" }],
+ ])("rejects a %s", async (_, claims) => {
+ await expect(verifyAppleIdToken(
+ await signToken(claims),
+ EXPECTED_NONCE,
+ CLIENT_ID,
+ { key: rsaPublicKey, currentDate: NOW },
+ )).resolves.toBe(false)
+ })
+
+ it.each(["iss", "aud", "sub", "nonce", "iat", "exp"] as const)(
+ "rejects a token missing the %s claim",
+ async (claim) => {
+ const claims: Claims = {
+ iss: APPLE_ISSUER,
+ aud: CLIENT_ID,
+ sub: "apple-stable-subject",
+ nonce: EXPECTED_NONCE,
+ iat: NOW_SECONDS,
+ exp: NOW_SECONDS + 300,
+ }
+ delete claims[claim]
+ const token = await new SignJWT(claims)
+ .setProtectedHeader({ alg: "RS256", kid: "apple-test-key" })
+ .sign(rsaPrivateKey)
+
+ await expect(verifyAppleIdToken(token, EXPECTED_NONCE, CLIENT_ID, {
+ key: rsaPublicKey,
+ currentDate: NOW,
+ })).resolves.toBe(false)
+ },
+ )
+
+ it("rejects an invalid signature", async () => {
+ await expect(verifyAppleIdToken(
+ await signToken({}, { key: otherRsaPrivateKey }),
+ EXPECTED_NONCE,
+ CLIENT_ID,
+ { key: rsaPublicKey, currentDate: NOW },
+ )).resolves.toBe(false)
+ })
+
+ it("rejects a tampered signature", async () => {
+ const [header, payload, signature] = (await signToken()).split(".")
+ const tamperedSignature = `${signature?.startsWith("a") ? "b" : "a"}${signature?.slice(1)}`
+ await expect(verifyAppleIdToken(
+ `${header}.${payload}.${tamperedSignature}`,
+ EXPECTED_NONCE,
+ CLIENT_ID,
+ { key: rsaPublicKey, currentDate: NOW },
+ )).resolves.toBe(false)
+ })
+
+ it("rejects every algorithm except RS256", async () => {
+ await expect(verifyAppleIdToken(
+ await signToken({}, { alg: "ES256", key: ecPrivateKey }),
+ EXPECTED_NONCE,
+ CLIENT_ID,
+ { key: rsaPublicKey, currentDate: NOW },
+ )).resolves.toBe(false)
+ })
+
+ it.each([
+ ["malformed", "not-a-jwt"],
+ ["missing token", ""],
+ ])("fails closed for a %s without leaking parser errors", async (_, token) => {
+ await expect(verifyAppleIdToken(
+ token,
+ EXPECTED_NONCE,
+ CLIENT_ID,
+ { key: rsaPublicKey, currentDate: NOW },
+ )).resolves.toBe(false)
+ })
+
+ it("requires both the expected nonce and client ID before parsing", async () => {
+ const token = await signToken()
+ await expect(verifyAppleIdToken(token, "", CLIENT_ID, {
+ key: rsaPublicKey,
+ currentDate: NOW,
+ })).resolves.toBe(false)
+ await expect(verifyAppleIdToken(token, EXPECTED_NONCE, "", {
+ key: rsaPublicKey,
+ currentDate: NOW,
+ })).resolves.toBe(false)
+ })
+})
+
+describe("Better Auth Apple callback integration", () => {
+ afterEach(() => vi.unstubAllGlobals())
+
+ it("binds authorization, token exchange, JWKS verification, persistence, and single-use state", async () => {
+ const publicJwk = await exportJWK(rsaPublicKey)
+ Object.assign(publicJwk, { kid: "apple-test-key", alg: "RS256", use: "sig" })
+ let nextIdToken = ""
+ let rejectCode = false
+ const externalFetch = vi.fn(async (input: string | URL | Request) => {
+ const url = input instanceof Request ? input.url : String(input)
+ if (url === APPLE_JWKS_URL) {
+ return new Response(JSON.stringify({ keys: [publicJwk] }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ })
+ }
+ if (url === `${APPLE_ISSUER}/auth/token`) {
+ if (rejectCode) {
+ return new Response(JSON.stringify({ error: "invalid_grant" }), {
+ status: 400,
+ headers: { "Content-Type": "application/json" },
+ })
+ }
+ return new Response(JSON.stringify({
+ access_token: "apple-access-token",
+ refresh_token: "apple-refresh-token",
+ token_type: "Bearer",
+ expires_in: 3600,
+ id_token: nextIdToken,
+ }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ })
+ }
+ throw new Error(`Unexpected external request: ${url}`)
+ })
+ vi.stubGlobal("fetch", externalFetch)
+
+ let findExistingAppleUser = async (_sub: string) => null as {
+ email: string
+ emailVerified: boolean | null
+ name: string
+ } | null
+ const { auth, db } = await getTestInstance({
+ socialProviders: {
+ apple: {
+ clientId: CLIENT_ID,
+ clientSecret: "test-client-secret",
+ mapProfileToUser: (profile) => mapAppleProfileToUser(
+ profile,
+ findExistingAppleUser,
+ ),
+ },
+ },
+ plugins: [appleOauthHardeningPlugin(CLIENT_ID)],
+ }, { disableTestUser: true })
+ findExistingAppleUser = async (sub) => {
+ const linked = await db.findOne<{ userId: string }>({
+ model: "account",
+ where: [
+ { field: "providerId", value: "apple" },
+ { field: "accountId", value: sub },
+ ],
+ })
+ if (!linked) return null
+ return db.findOne<{
+ email: string
+ emailVerified: boolean | null
+ name: string
+ }>({
+ model: "user",
+ where: [{ field: "id", value: linked.userId }],
+ })
+ }
+
+ const directIdToken = await auth.handler(new Request(
+ "http://localhost:3000/api/auth/sign-in/social",
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Origin: "http://localhost:3000",
+ },
+ body: JSON.stringify({
+ provider: "apple",
+ callbackURL: "/signed-in",
+ idToken: { token: "client-submitted-id-token" },
+ }),
+ },
+ ))
+ expect(directIdToken.status).toBe(404)
+ await expect(directIdToken.json()).resolves.toMatchObject({
+ code: "ID_TOKEN_NOT_SUPPORTED",
+ })
+ expect(await db.count({ model: "user" })).toBe(0)
+ expect(await db.count({ model: "account" })).toBe(0)
+ expect(externalFetch).not.toHaveBeenCalled()
+
+ async function begin() {
+ const response = await auth.handler(new Request(
+ "http://localhost:3000/api/auth/sign-in/social",
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Origin: "http://localhost:3000",
+ },
+ body: JSON.stringify({
+ provider: "apple",
+ callbackURL: "/signed-in",
+ disableRedirect: true,
+ }),
+ },
+ ))
+ expect(response.status).toBe(200)
+ const result = await response.json() as { url: string }
+ const url = new URL(result.url!)
+ expect(url.origin).toBe(APPLE_ISSUER)
+ expect(url.searchParams.get("state")).toBeTruthy()
+ expect(url.searchParams.get("code_challenge")).toBeTruthy()
+ expect(url.searchParams.get("nonce")).toBeTruthy()
+ const cookie = response.headers.get("set-cookie")?.split(";", 1)[0]
+ expect(cookie).toBeTruthy()
+ return { url, cookie: cookie! }
+ }
+
+ async function callback(params: Record<string, string>, cookie: string) {
+ const post = await auth.handler(new Request(
+ "http://localhost:3000/api/auth/callback/apple",
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/x-www-form-urlencoded",
+ },
+ body: new URLSearchParams(params),
+ redirect: "manual",
+ },
+ ))
+ expect(post.status).toBe(302)
+ const normalizedCallback = post.headers.get("location")
+ expect(normalizedCallback).toBeTruthy()
+ return auth.handler(new Request(normalizedCallback!, {
+ headers: { Cookie: cookie },
+ redirect: "manual",
+ }))
+ }
+
+ async function liveToken(
+ nonce: string,
+ claims: Claims = {},
+ key = rsaPrivateKey,
+ ) {
+ const now = Math.floor(Date.now() / 1000)
+ return new SignJWT({
+ iss: APPLE_ISSUER,
+ aud: CLIENT_ID,
+ sub: "apple-integration-subject",
+ email: "[email protected]",
+ email_verified: true,
+ nonce,
+ iat: now,
+ exp: now + 300,
+ ...claims,
+ })
+ .setProtectedHeader({ alg: "RS256", kid: "apple-test-key" })
+ .sign(key)
+ }
+
+ for (const invalid of [
+ async (nonce: string) => liveToken(nonce, { iss: "https://attacker.example" }),
+ async (nonce: string) => liveToken(nonce, { aud: "another.service" }),
+ async (nonce: string) => liveToken("wrong-nonce"),
+ async (nonce: string) => liveToken(nonce, { exp: Math.floor(Date.now() / 1000) - 1 }),
+ async (nonce: string) => liveToken(nonce, {}, otherRsaPrivateKey),
+ ]) {
+ const authorization = await begin()
+ const state = authorization.url.searchParams.get("state")!
+ const nonce = authorization.url.searchParams.get("nonce")!
+ nextIdToken = await invalid(nonce)
+ const response = await callback({
+ code: "invalid-token-code",
+ state,
+ iss: APPLE_ISSUER,
+ }, authorization.cookie)
+ expect(response.status).toBe(302)
+ expect(new URL(response.headers.get("location")!).searchParams.get("error"))
+ .toBe("unable_to_get_user_info")
+ expect(await db.count({ model: "user" })).toBe(0)
+ expect(await db.count({ model: "account" })).toBe(0)
+ }
+
+ const rejectedAuthorization = await begin()
+ rejectCode = true
+ const rejectedCode = await callback({
+ code: "rejected-code",
+ state: rejectedAuthorization.url.searchParams.get("state")!,
+ iss: APPLE_ISSUER,
+ }, rejectedAuthorization.cookie)
+ expect(new URL(rejectedCode.headers.get("location")!).searchParams.get("error"))
+ .toBe("invalid_code")
+ expect(await db.count({ model: "user" })).toBe(0)
+ rejectCode = false
+
+ const cancelledAuthorization = await begin()
+ const cancelled = await callback({
+ error: "access_denied",
+ state: cancelledAuthorization.url.searchParams.get("state")!,
+ }, cancelledAuthorization.cookie)
+ expect(new URL(cancelled.headers.get("location")!).searchParams.get("error"))
+ .toBe("access_denied")
+ expect(await db.count({ model: "user" })).toBe(0)
+
+ const unverifiedEmailAuthorization = await begin()
+ nextIdToken = await liveToken(
+ unverifiedEmailAuthorization.url.searchParams.get("nonce")!,
+ {
+ sub: "never-seen-unverified-email-subject",
+ email: "[email protected]",
+ email_verified: false,
+ },
+ )
+ const unverifiedEmail = await callback({
+ code: "unverified-email-code",
+ state: unverifiedEmailAuthorization.url.searchParams.get("state")!,
+ iss: APPLE_ISSUER,
+ }, unverifiedEmailAuthorization.cookie)
+ expect(new URL(unverifiedEmail.headers.get("location")!).searchParams.get("error"))
+ .toBe("email_not_found")
+ expect(await db.count({ model: "user" })).toBe(0)
+ expect(await db.count({ model: "account" })).toBe(0)
+
+ const authorization = await begin()
+ const state = authorization.url.searchParams.get("state")!
+ const nonce = authorization.url.searchParams.get("nonce")!
+ nextIdToken = await liveToken(nonce)
+ const success = await callback(
+ {
+ code: "valid-code",
+ state,
+ iss: APPLE_ISSUER,
+ user: JSON.stringify({
+ name: { firstName: "Apple", lastName: "Person" },
+ email: "[email protected]",
+ }),
+ },
+ authorization.cookie,
+ )
+
+ expect(success.status).toBe(302)
+ expect(success.headers.get("location")).toBe("/signed-in")
+ expect(await db.count({ model: "user" })).toBe(1)
+ expect(await db.count({ model: "account" })).toBe(1)
+ await expect(db.findOne<{ name: string }>({
+ model: "user",
+ where: [{ field: "email", value: "[email protected]" }],
+ })).resolves.toMatchObject({ name: "Apple Person" })
+ await expect(db.findOne<{ providerId: string; accountId: string }>({
+ model: "account",
+ where: [{ field: "providerId", value: "apple" }],
+ })).resolves.toMatchObject({
+ providerId: "apple",
+ accountId: "apple-integration-subject",
+ })
+
+ const tokenRequestsBeforeReplay = externalFetch.mock.calls.filter(([input]) => {
+ const url = input instanceof Request ? input.url : String(input)
+ return url === `${APPLE_ISSUER}/auth/token`
+ }).length
+ const replay = await callback(
+ { code: "valid-code", state, iss: APPLE_ISSUER },
+ authorization.cookie,
+ )
+ expect(replay.status).toBe(302)
+ expect(new URL(replay.headers.get("location")!).searchParams.get("error"))
+ .toBe("state_mismatch")
+ const tokenRequestsAfterReplay = externalFetch.mock.calls.filter(([input]) => {
+ const url = input instanceof Request ? input.url : String(input)
+ return url === `${APPLE_ISSUER}/auth/token`
+ }).length
+ expect(tokenRequestsAfterReplay).toBe(tokenRequestsBeforeReplay)
+ expect(await db.count({ model: "user" })).toBe(1)
+ expect(await db.count({ model: "account" })).toBe(1)
+
+ const sameEmailAuthorization = await begin()
+ nextIdToken = await liveToken(
+ sameEmailAuthorization.url.searchParams.get("nonce")!,
+ { sub: "apple-same-email-subject" },
+ )
+ const sameEmail = await callback({
+ code: "same-email-code",
+ state: sameEmailAuthorization.url.searchParams.get("state")!,
+ iss: APPLE_ISSUER,
+ }, sameEmailAuthorization.cookie)
+ expect(sameEmail.headers.get("location")).toBe("/signed-in")
+ expect(await db.count({ model: "user" })).toBe(1)
+ expect(await db.count({ model: "account" })).toBe(2)
+
+ const relayAuthorization = await begin()
+ nextIdToken = await liveToken(
+ relayAuthorization.url.searchParams.get("nonce")!,
+ {
+ sub: "apple-relay-subject",
+ email: "[email protected]",
+ },
+ )
+ const relay = await callback({
+ code: "relay-code",
+ state: relayAuthorization.url.searchParams.get("state")!,
+ iss: APPLE_ISSUER,
+ }, relayAuthorization.cookie)
+ expect(relay.headers.get("location")).toBe("/signed-in")
+ expect(await db.count({ model: "user" })).toBe(2)
+ expect(await db.count({ model: "account" })).toBe(3)
+
+ const returningAuthorization = await begin()
+ nextIdToken = await liveToken(
+ returningAuthorization.url.searchParams.get("nonce")!,
+ {
+ email: undefined,
+ email_verified: undefined,
+ },
+ )
+ const returning = await callback({
+ code: "returning-code",
+ state: returningAuthorization.url.searchParams.get("state")!,
+ iss: APPLE_ISSUER,
+ }, returningAuthorization.cookie)
+ expect(returning.headers.get("location")).toBe("/signed-in")
+ expect(await db.count({ model: "user" })).toBe(2)
+ expect(await db.count({ model: "account" })).toBe(3)
+
+ const missingEmailAuthorization = await begin()
+ nextIdToken = await liveToken(
+ missingEmailAuthorization.url.searchParams.get("nonce")!,
+ {
+ sub: "never-seen-apple-subject",
+ email: undefined,
+ email_verified: undefined,
+ },
+ )
+ const missingEmail = await callback({
+ code: "missing-email-code",
+ state: missingEmailAuthorization.url.searchParams.get("state")!,
+ iss: APPLE_ISSUER,
+ }, missingEmailAuthorization.cookie)
+ expect(new URL(missingEmail.headers.get("location")!).searchParams.get("error"))
+ .toBe("email_not_found")
+ expect(await db.count({ model: "user" })).toBe(2)
+ expect(await db.count({ model: "account" })).toBe(3)
+ })
+})
+
+type AuthorizationData = {
+ state: string
+ codeVerifier: string
+ redirectURI: string
+ idTokenNonce?: string
+}
+
+type TokenData = {
+ accessToken?: string
+ idToken?: string
+ expectedIdTokenNonce?: string
+}
+
+function makeProvider() {
+ const accountSubject = vi.fn(({ profile }: { profile: { sub: string } }) => profile.sub)
+ const createAuthorizationURL = vi.fn(async (data: AuthorizationData) => {
+ const url = new URL("https://appleid.apple.com/auth/authorize")
+ url.searchParams.set("state", data.state)
+ url.searchParams.set("code_challenge", data.codeVerifier)
+ return url
+ })
+ const getUserInfo = vi.fn(async (_tokens: TokenData) => ({
+ user: { email: "[email protected]", emailVerified: true, name: "Person" },
+ data: { sub: "apple-stable-subject" },
+ }))
+ const provider = {
+ id: "apple",
+ name: "Apple",
+ options: {} as { disableIdTokenSignIn?: boolean },
+ requiresIdTokenNonce: false,
+ issuer: undefined as string | undefined,
+ accountSubject,
+ createAuthorizationURL,
+ validateAuthorizationCode: vi.fn(),
+ getUserInfo,
+ }
+ return { provider, accountSubject, createAuthorizationURL, getUserInfo }
+}
+
+function initializeProvider(
+ verifyIdToken = vi.fn(async () => true),
+ providers = [makeProvider().provider],
+) {
+ const plugin = appleOauthHardeningPlugin(CLIENT_ID, verifyIdToken)
+ plugin.init?.({ socialProviders: providers } as never)
+ return { plugin, provider: providers[0], verifyIdToken }
+}
+
+describe("Apple OAuth hardening plugin", () => {
+ it("requires state-bound nonces and disables the client-submitted ID-token flow", () => {
+ const { provider } = initializeProvider()
+
+ expect(provider.requiresIdTokenNonce).toBe(true)
+ expect(provider.issuer).toBe(APPLE_ISSUER)
+ expect(provider.options.disableIdTokenSignIn).toBe(true)
+ })
+
+ it("forwards the identical state nonce to Apple without changing state or PKCE", async () => {
+ const fixture = makeProvider()
+ const originalAccountSubject = fixture.provider.accountSubject
+ const { provider } = initializeProvider(vi.fn(async () => true), [fixture.provider])
+ const data = {
+ state: "signed-state",
+ codeVerifier: "pkce-verifier",
+ redirectURI: "https://alook.ai/api/auth/callback/apple",
+ idTokenNonce: EXPECTED_NONCE,
+ }
+
+ const url = await provider.createAuthorizationURL(data)
+
+ expect(fixture.createAuthorizationURL).toHaveBeenCalledWith(data)
+ expect(url.searchParams.get("state")).toBe(data.state)
+ expect(url.searchParams.get("code_challenge")).toBe(data.codeVerifier)
+ expect(url.searchParams.get("nonce")).toBe(EXPECTED_NONCE)
+ expect(provider.accountSubject).toBe(originalAccountSubject)
+ expect(provider.accountSubject({ profile: { sub: "stable-sub" } })).toBe("stable-sub")
+ })
+
+ it("fails closed before redirect when no nonce is available", async () => {
+ const fixture = makeProvider()
+ const { provider } = initializeProvider(vi.fn(async () => true), [fixture.provider])
+
+ await expect(provider.createAuthorizationURL({
+ state: "signed-state",
+ codeVerifier: "pkce-verifier",
+ redirectURI: "https://alook.ai/api/auth/callback/apple",
+ })).rejects.toThrow("Apple OAuth authorization could not be initialized")
+ expect(fixture.createAuthorizationURL).not.toHaveBeenCalled()
+ })
+
+ it("delegates profile mapping only after the callback ID token verifies", async () => {
+ const fixture = makeProvider()
+ const verify = vi.fn(async () => true)
+ const { provider } = initializeProvider(verify, [fixture.provider])
+ const tokens = {
+ accessToken: "access-token",
+ idToken: "signed-id-token",
+ expectedIdTokenNonce: EXPECTED_NONCE,
+ }
+
+ await expect(provider.getUserInfo(tokens)).resolves.toEqual({
+ user: { email: "[email protected]", emailVerified: true, name: "Person" },
+ data: { sub: "apple-stable-subject" },
+ })
+ expect(verify).toHaveBeenCalledWith("signed-id-token", EXPECTED_NONCE, CLIENT_ID)
+ expect(fixture.getUserInfo).toHaveBeenCalledWith(tokens)
+ })
+
+ it.each([
+ ["invalid token", { idToken: "invalid", expectedIdTokenNonce: EXPECTED_NONCE }],
+ ["missing token", { expectedIdTokenNonce: EXPECTED_NONCE }],
+ ["missing expected nonce", { idToken: "signed-id-token" }],
+ ])("returns no user and performs no mapping for a callback with %s", async (_, tokens) => {
+ const fixture = makeProvider()
+ const verify = vi.fn(async () => false)
+ const { provider } = initializeProvider(verify, [fixture.provider])
+
+ await expect(provider.getUserInfo(tokens)).resolves.toBeNull()
+ expect(fixture.getUserInfo).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ ["no Apple provider", []],
+ ["duplicate Apple providers", [makeProvider().provider, makeProvider().provider]],
+ ])("fails initialization for %s", (_, providers) => {
+ const plugin = appleOauthHardeningPlugin(CLIENT_ID)
+ expect(() => plugin.init?.({ socialProviders: providers } as never))
+ .toThrow("Apple OAuth hardening could not be initialized")
+ })
+
+ it("fails initialization if the Apple provider options contract drifts", () => {
+ const provider = { ...makeProvider().provider, options: undefined }
+ const plugin = appleOauthHardeningPlugin(CLIENT_ID)
+ expect(() => plugin.init?.({ socialProviders: [provider] } as never))
+ .toThrow("Apple OAuth hardening could not be initialized")
+ })
+})
diff --git a/src/web/src/lib/apple-oauth-hardening.ts b/src/web/src/lib/apple-oauth-hardening.ts
new file mode 100644
index 000000000..6bdd371a8
--- /dev/null
+++ b/src/web/src/lib/apple-oauth-hardening.ts
@@ -0,0 +1,103 @@
+import type { BetterAuthPlugin } from "better-auth"
+import {
+ createRemoteJWKSet,
+ decodeProtectedHeader,
+ jwtVerify,
+ type JWTVerifyGetKey,
+} from "jose"
+import { APPLE_ISSUER } from "@/lib/apple-auth"
+
+export const APPLE_JWKS_URL = `${APPLE_ISSUER}/auth/keys`
+
+const appleJwks = createRemoteJWKSet(new URL(APPLE_JWKS_URL))
+
+type AppleVerificationKey = CryptoKey | Uint8Array | JWTVerifyGetKey
+
+type VerifyAppleIdTokenOptions = {
+ key?: AppleVerificationKey
+ currentDate?: Date
+}
+
+async function sha256Hex(value: string): Promise<string> {
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value))
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("")
+}
+
+export async function verifyAppleIdToken(
+ token: string,
+ expectedNonce: string,
+ clientId: string,
+ options: VerifyAppleIdTokenOptions = {},
+): Promise<boolean> {
+ if (!token || !expectedNonce || !clientId) return false
+
+ try {
+ if (decodeProtectedHeader(token).alg !== "RS256") return false
+
+ const { payload } = await jwtVerify(token, options.key ?? appleJwks, {
+ algorithms: ["RS256"],
+ issuer: APPLE_ISSUER,
+ audience: clientId,
+ maxTokenAge: "1h",
+ requiredClaims: ["iss", "aud", "exp", "iat", "sub", "nonce"],
+ currentDate: options.currentDate,
+ })
+
+ if (typeof payload.sub !== "string" || payload.sub.length === 0) return false
+ if (typeof payload.nonce !== "string" || payload.nonce.length === 0) return false
+
+ return payload.nonce === expectedNonce || payload.nonce === await sha256Hex(expectedNonce)
+ } catch {
+ return false
+ }
+}
+
+type AppleIdTokenVerifier = (
+ token: string,
+ expectedNonce: string,
+ clientId: string,
+) => Promise<boolean>
+
+export function appleOauthHardeningPlugin(
+ clientId: string,
+ verifyIdToken: AppleIdTokenVerifier = verifyAppleIdToken,
+): BetterAuthPlugin {
+ return {
+ id: "apple-oauth-hardening",
+ init(ctx) {
+ const appleProviders = ctx.socialProviders.filter((provider) => provider.id === "apple")
+ if (appleProviders.length !== 1) {
+ throw new Error("Apple OAuth hardening could not be initialized")
+ }
+
+ const provider = appleProviders[0]
+ if (!provider.options) {
+ throw new Error("Apple OAuth hardening could not be initialized")
+ }
+
+ provider.requiresIdTokenNonce = true
+ provider.issuer = APPLE_ISSUER
+ provider.options.disableIdTokenSignIn = true
+
+ const createAuthorizationURL = provider.createAuthorizationURL.bind(provider)
+ provider.createAuthorizationURL = async (data) => {
+ if (!data.idTokenNonce) {
+ throw new Error("Apple OAuth authorization could not be initialized")
+ }
+
+ const url = await createAuthorizationURL(data)
+ url.searchParams.set("nonce", data.idTokenNonce)
+ return url
+ }
+
+ const getUserInfo = provider.getUserInfo.bind(provider)
+ provider.getUserInfo = async (tokens) => {
+ if (!tokens.idToken || !tokens.expectedIdTokenNonce) return null
+ if (!await verifyIdToken(tokens.idToken, tokens.expectedIdTokenNonce, clientId)) {
+ return null
+ }
+ return getUserInfo(tokens)
+ }
+ },
+ }
+}
diff --git a/src/web/src/lib/auth.test.ts b/src/web/src/lib/auth.test.ts
index f48a96221..c9952ed10 100644
--- a/src/web/src/lib/auth.test.ts
+++ b/src/web/src/lib/auth.test.ts
@@ -1,5 +1,9 @@
import { afterEach, describe, it, expect, vi, beforeEach } from "vitest"
+const appleMocks = vi.hoisted(() => ({
+ generateClientSecret: vi.fn(async () => "signed-apple-client-secret"),
+}))
+
vi.mock("better-auth", () => ({
betterAuth: vi.fn((opts: unknown) => ({ __options: opts })),
}))
@@ -11,6 +15,14 @@ vi.mock("better-auth/plugins", () => ({
oneTimeToken: vi.fn((cfg: unknown) => ({ __plugin: "oneTimeToken", cfg })),
}))
+vi.mock("@/lib/apple-auth", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@/lib/apple-auth")>()
+ return {
+ ...actual,
+ generateAppleClientSecret: appleMocks.generateClientSecret,
+ }
+})
+
// `probeAvailableDiscriminator` (called from the `user.create.before` hook)
// does a real `getUserByNameAndDiscriminator` SELECT against `getDb(env.DB)`
// — stub `getDb` to return a minimal drizzle-chain fake instead of `{}` so
@@ -26,12 +38,16 @@ function queueSelectResponse(rows: unknown[]) {
function makeFakeDb() {
const chain = {
from: () => chain,
+ innerJoin: () => chain,
where: () => chain,
limit: async () => selectResponses.shift() ?? [],
}
return { select: () => chain }
}
-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => makeFakeDb()) }));
+vi.mock("@/lib/db", () => ({
+ getDb: vi.fn(() => makeFakeDb()),
+ getPrimaryDb: vi.fn(() => makeFakeDb()),
+}));
vi.mock("@alook/shared", async (importOriginal) => {
const actual = await importOriginal<typeof import("@alook/shared")>()
@@ -79,6 +95,8 @@ function makeEnv(overrides: Partial<Record<string, unknown>> = {}) {
}
type AuthOptions = {
+ trustedOrigins?: string[]
+ socialProviders?: Record<string, unknown>
user?: {
additionalFields?: Record<
string,
@@ -90,6 +108,7 @@ type AuthOptions = {
}
plugins?: Array<{
__plugin?: string
+ id?: string
cfg?: Record<string, unknown> & {
sendVerificationOTP?: (args: { email: string; otp: string; type: string }) => Promise<void>
}
@@ -111,6 +130,11 @@ type AuthOptions = {
after?: (user: unknown, ctx: unknown) => Promise<void>
}
}
+ session?: {
+ create?: {
+ after?: (session: unknown, ctx: unknown) => Promise<void>
+ }
+ }
}
}
@@ -308,6 +332,66 @@ describe("createAuth user fields", () => {
})
})
+describe("createAuth Apple provider", () => {
+ it("omits Apple and its trusted origin when all Apple configuration is absent", async () => {
+ const createAuth = await loadCreateAuth()
+ const opts = (createAuth(makeEnv() as never) as { __options: AuthOptions }).__options
+
+ expect(opts.socialProviders).not.toHaveProperty("apple")
+ expect(opts.trustedOrigins).not.toContain("https://appleid.apple.com")
+ expect(opts.plugins).not.toContainEqual(expect.objectContaining({ id: "apple-oauth-hardening" }))
+ })
+
+ it.each(["production", "development"])(
+ "enables only the hardened async built-in provider surface in %s",
+ async (nodeEnv) => {
+ const createAuth = await loadCreateAuth()
+ const opts = (createAuth(makeEnv({
+ NODE_ENV: nodeEnv,
+ APPLE_CLIENT_ID: "ai.alook.web",
+ APPLE_TEAM_ID: "TEAM123456",
+ APPLE_KEY_ID: "KEY1234567",
+ APPLE_PRIVATE_KEY: "test-private-key-shape-is-validated-on-provider-use",
+ }) as never) as { __options: AuthOptions }).__options
+
+ expect(opts.socialProviders?.apple).toEqual(expect.any(Function))
+ expect(opts.trustedOrigins).toEqual(["https://appleid.apple.com"])
+ expect(opts.plugins).toContainEqual(expect.objectContaining({ id: "apple-oauth-hardening" }))
+
+ const createAppleProvider = opts.socialProviders?.apple as () => Promise<{
+ clientId: string
+ clientSecret: string
+ mapProfileToUser: (profile: {
+ sub: string
+ email?: string
+ email_verified?: boolean | string
+ }) => Promise<{ email?: string; emailVerified?: boolean; name?: string }>
+ }>
+ const provider = await createAppleProvider()
+ expect(provider).toMatchObject({
+ clientId: "ai.alook.web",
+ clientSecret: "signed-apple-client-secret",
+ })
+ queueSelectResponse([{
+ email: "[email protected]",
+ emailVerified: true,
+ name: "Stored Person",
+ }])
+ await expect(provider.mapProfileToUser({ sub: "returning-sub" })).resolves.toEqual({
+ email: "[email protected]",
+ emailVerified: true,
+ name: "Stored Person",
+ })
+ expect(appleMocks.generateClientSecret).toHaveBeenCalled()
+ })
+
+ it("fails closed before Better Auth initializes when configuration is partial", async () => {
+ const createAuth = await loadCreateAuth()
+ expect(() => createAuth(makeEnv({ APPLE_CLIENT_ID: "ai.alook.web" }) as never))
+ .toThrow("Apple authentication configuration is incomplete")
+ })
+})
+
describe("createAuth device authorization plugin", () => {
beforeEach(() => vi.clearAllMocks())
@@ -397,6 +481,15 @@ describe("createAuth databaseHooks — user.create.after", () => {
expect(ctx.setCookie).toHaveBeenCalledWith("is_new_signup", "google", expect.anything())
})
+ it("sets method=apple for apple callback path", async () => {
+ const createAuth = await loadCreateAuth()
+ const opts = (createAuth(makeEnv({ NODE_ENV: "production" }) as never) as { __options: AuthOptions }).__options
+ const afterHook = opts.databaseHooks!.user!.create!.after!
+ const ctx = makeCtx("http://localhost:3000/api/auth/callback/apple")
+ await afterHook({ id: "u-apple" }, ctx)
+ expect(ctx.setCookie).toHaveBeenCalledWith("is_new_signup", "apple", expect.anything())
+ })
+
it("sets method=unknown for unrecognized path", async () => {
const createAuth = await loadCreateAuth()
const opts = (createAuth(makeEnv({ NODE_ENV: "production" }) as never) as { __options: AuthOptions }).__options
@@ -414,6 +507,31 @@ describe("createAuth databaseHooks — user.create.after", () => {
})
})
+describe("createAuth databaseHooks — session.create.after", () => {
+ beforeEach(() => vi.clearAllMocks())
+
+ it("sets is_sign_in cookie with method=apple for an Apple callback", async () => {
+ const createAuth = await loadCreateAuth()
+ const opts = (createAuth(makeEnv({ NODE_ENV: "production" }) as never) as {
+ __options: AuthOptions
+ }).__options
+ const afterHook = opts.databaseHooks!.session!.create!.after!
+ const ctx = {
+ request: { url: "http://localhost:3000/api/auth/callback/apple" },
+ getCookie: vi.fn(() => undefined),
+ setCookie: vi.fn(),
+ }
+
+ await afterHook({ id: "session-apple", userId: "u-apple" }, ctx)
+
+ expect(ctx.setCookie).toHaveBeenCalledWith(
+ "is_sign_in",
+ "apple",
+ expect.objectContaining({ maxAge: 60 }),
+ )
+ })
+})
+
describe("createAuth databaseHooks — user.create.before", () => {
beforeEach(() => {
vi.clearAllMocks()
diff --git a/src/web/src/lib/auth.ts b/src/web/src/lib/auth.ts
index 1f68955c2..08d11aec5 100644
--- a/src/web/src/lib/auth.ts
+++ b/src/web/src/lib/auth.ts
@@ -10,8 +10,15 @@ import {
RATE_LIMITS,
sanitizeCommunityName,
} from "@alook/shared"
-import { getDb } from "@/lib/db"
+import { getDb, getPrimaryDb } from "@/lib/db"
import { checkRateLimit } from "@/lib/rate-limit"
+import {
+ APPLE_ISSUER,
+ generateAppleClientSecret,
+ mapAppleProfileToUser,
+ resolveAppleAuthConfig,
+} from "@/lib/apple-auth"
+import { appleOauthHardeningPlugin } from "@/lib/apple-oauth-hardening"
import { getOtpSubject, renderOtpEmail, type OtpType } from "./email-templates"
const log = createLogger({ service: "auth" })
@@ -73,6 +80,10 @@ export function createAuth(env: Env) {
const mode = resolveMode({ nodeEnv: env.NODE_ENV ?? process.env.NODE_ENV })
const isProd = mode === "production"
const otpPolicy = getAuthOtpRateLimitPolicy(env)
+ const appleAuth = resolveAppleAuthConfig(env)
+ const applePlugins = appleAuth.enabled
+ ? [appleOauthHardeningPlugin(appleAuth.config.clientId)]
+ : []
const validateClient = (clientId: string) => {
const allowed = (env.DEVICE_CLIENT_IDS || "").split(",").map((s) => s.trim()).filter(Boolean)
return allowed.includes(clientId)
@@ -133,6 +144,7 @@ export function createAuth(env: Env) {
},
},
},
+ trustedOrigins: appleAuth.enabled ? [APPLE_ISSUER] : [],
socialProviders: {
github: {
clientId: env.GITHUB_CLIENT_ID,
@@ -142,6 +154,23 @@ export function createAuth(env: Env) {
clientId: env.GOOGLE_CLIENT_ID,
clientSecret: env.GOOGLE_CLIENT_SECRET,
},
+ ...(appleAuth.enabled ? {
+ apple: async () => ({
+ clientId: appleAuth.config.clientId,
+ clientSecret: await generateAppleClientSecret(appleAuth.config),
+ mapProfileToUser: async (profile: {
+ sub: string
+ email?: string
+ email_verified?: boolean | string
+ }) => mapAppleProfileToUser(profile, async (sub) => {
+ return queries.user.getUserByProviderAccount(
+ getPrimaryDb(env.DB),
+ "apple",
+ sub,
+ )
+ }),
+ }),
+ } : {}),
},
// Better-auth's built-in rate limiter is intentionally OFF — we run our
// own DO-backed limiter inside `sendVerificationOTP` below. That gives
@@ -192,6 +221,7 @@ export function createAuth(env: Env) {
if (path.includes("email-otp")) method = "email"
else if (path.includes("github")) method = "github"
else if (path.includes("google")) method = "google"
+ else if (path.includes("apple")) method = "apple"
ctx.setCookie("is_new_signup", method, {
maxAge: 60,
path: "/",
@@ -245,6 +275,7 @@ export function createAuth(env: Env) {
if (path.includes("email-otp")) method = "email_otp"
else if (path.includes("github")) method = "github"
else if (path.includes("google")) method = "google"
+ else if (path.includes("apple")) method = "apple"
ctx.setCookie("is_sign_in", method, {
maxAge: 60,
path: "/",
@@ -258,6 +289,7 @@ export function createAuth(env: Env) {
},
plugins: isProd
? [
+ ...applePlugins,
deviceAuthorization({ verificationUri: "/device", validateClient, expiresIn: "5m", schema: {} }),
bearer(),
oneTimeToken({
@@ -287,6 +319,7 @@ export function createAuth(env: Env) {
}),
]
: [
+ ...applePlugins,
deviceAuthorization({ verificationUri: "/device", validateClient, expiresIn: "5m", schema: {} }),
bearer(),
oneTimeToken({
diff --git a/src/web/src/lib/native-oauth-client.test.ts b/src/web/src/lib/native-oauth-client.test.ts
index 8569de700..43102c385 100644
--- a/src/web/src/lib/native-oauth-client.test.ts
+++ b/src/web/src/lib/native-oauth-client.test.ts
@@ -19,7 +19,7 @@ function setup() {
events.push(command)
if (command === "native_oauth_snapshot") return snapshot && { ...snapshot }
if (command === "native_oauth_prepare") {
- snapshot = { attemptId: `attempt_${String(++count).padStart(24, "0")}`, provider: args!.provider as "github" | "google", redirectPath: args!.redirectPath as string, expiresAt: Date.now() + 600_000, waiting: false }
+ snapshot = { attemptId: `attempt_${String(++count).padStart(24, "0")}`, provider: args!.provider as NativeOauthSnapshot["provider"], redirectPath: args!.redirectPath as string, expiresAt: Date.now() + 600_000, waiting: false }
pending = []
return { attemptId: snapshot.attemptId, provider: snapshot.provider, redirectPath: snapshot.redirectPath, platform: "macos", stateHash: "a".repeat(64), codeChallenge: "b".repeat(43), instanceKeyHash: "c".repeat(64) }
}
@@ -62,6 +62,30 @@ function fixture() { const f = setup(); controllers.push(f.controller); return f
afterEach(() => { for (const c of controllers.splice(0)) c.dispose(); vi.unstubAllGlobals(); vi.useRealTimers() })
describe("native OAuth controller", () => {
+ it("starts and restores Apple through the existing prepare, snapshot, open, and waiting flow", async () => {
+ const f = fixture()
+ await f.controller.connect()
+ await f.controller.start("apple", "/c/me")
+
+ expect(f.view()).toMatchObject({
+ phase: "waiting",
+ attempt: { provider: "apple", redirectPath: "/c/me", waiting: true },
+ })
+ expect(f.events.indexOf("native_oauth_prepare"))
+ .toBeLessThan(f.events.indexOf("attempt"))
+ expect(f.events.indexOf("attempt"))
+ .toBeLessThan(f.events.indexOf("native_oauth_open_start"))
+
+ f.controller.dispose()
+ const restored = f.make()
+ controllers.push(restored)
+ await restored.connect()
+ expect(f.view()).toMatchObject({
+ phase: "waiting",
+ attempt: { provider: "apple", redirectPath: "/c/me", waiting: true },
+ })
+ })
+
it("registers the listener before reading pending, opens only the registered start, and keeps proofs out of view state", async () => {
const f = fixture(); await f.controller.connect(); await f.controller.start("github", "/c/me")
expect(f.events.indexOf("listen")).toBeLessThan(f.events.indexOf("native_oauth_pending_exchange"))
@@ -200,6 +224,45 @@ afterEach(() => { for (const c of controllers.splice(0)) c.dispose(); vi.unstubA
expect(g.view().message).toBe("start_failed"); expect(g.snapshot()).toBeNull()
expect(g.invoke.mock.calls.some(([name]) => name === "native_oauth_open_start")).toBe(false)
})
+ it("treats only an old app's Apple rejection as update-required and keeps other providers usable", async () => {
+ const f = fixture(); await f.controller.connect()
+ const original = f.invoke.getMockImplementation()!
+ f.invoke.mockImplementation((command, args) => {
+ if (command === "native_oauth_prepare" && args?.provider === "apple") {
+ return Promise.reject("invalid_request")
+ }
+ return original(command, args)
+ })
+
+ await f.controller.start("apple", "/c/me")
+ expect(f.view()).toMatchObject({
+ phase: "error",
+ message: "apple_update_required",
+ attempt: null,
+ })
+ expect(f.post).not.toHaveBeenCalled()
+
+ await f.controller.start("github", "/c/me")
+ expect(f.view().phase).toBe("waiting")
+ expect(f.snapshot()?.provider).toBe("github")
+ })
+ it("keeps nonstandard Apple prepare failures on the generic retry path", async () => {
+ const f = fixture(); await f.controller.connect()
+ const original = f.invoke.getMockImplementation()!
+ f.invoke.mockImplementation((command, args) => {
+ if (command === "native_oauth_prepare" && args?.provider === "apple") {
+ return Promise.reject({ code: "invalid_request" })
+ }
+ return original(command, args)
+ })
+
+ await f.controller.start("apple", "/c/me")
+ expect(f.view()).toMatchObject({
+ phase: "error",
+ message: "start_failed",
+ attempt: null,
+ })
+ })
it("checks an already-dispatched cold callback against a successful session", async () => {
const f = fixture(); await f.controller.connect(); await f.controller.start("google", "/c/me")
f.queue("k".repeat(32), null, true); f.controller.dispose(); f.hasSession.mockResolvedValue(true)
diff --git a/src/web/src/lib/native-oauth-client.ts b/src/web/src/lib/native-oauth-client.ts
index d921688be..228868b2a 100644
--- a/src/web/src/lib/native-oauth-client.ts
+++ b/src/web/src/lib/native-oauth-client.ts
@@ -1,4 +1,11 @@
-import { isSafeRedirectPath, nativeOauthRegistrationSchema, nativeOauthProofSchema, nativeOauthExchangeSchema, tauriInvoke } from "@alook/shared"
+import {
+ isSafeRedirectPath,
+ nativeOauthRegistrationSchema,
+ nativeOauthProofSchema,
+ nativeOauthExchangeSchema,
+ tauriInvoke,
+ type NativeOauthProvider,
+} from "@alook/shared"
import { z } from "zod"
import { nativeOauthSnapshotSchema, type NativeOauthSnapshot } from "@/lib/native-oauth-schema"
@@ -8,7 +15,7 @@ const exchangeSchema = nativeOauthProofSchema.extend({
export type { NativeOauthSnapshot } from "@/lib/native-oauth-schema"
export type NativeOauthView = {
phase: "initializing" | "idle" | "preparing" | "waiting" | "exchanging" | "checking_status" | "error" | "unsupported"
- message?: "start_failed" | "expired" | "denied" | "invalid_callback" | "retry_required" | "unavailable"
+ message?: "start_failed" | "expired" | "denied" | "invalid_callback" | "retry_required" | "unavailable" | "apple_update_required"
attempt: NativeOauthSnapshot | null
}
export type NativeOauthDeps = {
@@ -153,7 +160,7 @@ export function createNativeOauthController(deps: NativeOauthDeps, changed: (vie
: { phase: "unsupported", attempt: null })
}
},
- start(provider: "github" | "google", redirectPath: string) {
+ start(provider: NativeOauthProvider, redirectPath: string) {
if (disposed || !connected || !isSafeRedirectPath(redirectPath)) return Promise.resolve()
const version = ++generation
publish({ phase: "preparing", attempt: view.attempt })
@@ -177,13 +184,21 @@ export function createNativeOauthController(deps: NativeOauthDeps, changed: (vie
if (!current(version)) return
publish({ phase: "waiting", attempt: waiting })
void drain()
- } catch {
+ } catch (error) {
if (!current(version)) return
if (attemptId) {
const proof = await deps.invoke("native_oauth_cancel", { attemptId }).catch(() => null)
if (proof) await deps.post("cancel", nativeOauthProofSchema.parse(proof)).catch(() => {})
}
- if (current(version)) { setAttempt(null); publish({ phase: "error", message: "start_failed", attempt: null }) }
+ const nativeError = typeof error === "string"
+ ? error
+ : error instanceof Error
+ ? error.message
+ : ""
+ const message = provider === "apple" && !attemptId && nativeError === "invalid_request"
+ ? "apple_update_required"
+ : "start_failed"
+ if (current(version)) { setAttempt(null); publish({ phase: "error", message, attempt: null }) }
}
}
startQueue = startQueue.then(task, task)
diff --git a/src/web/src/lib/native-oauth-schema.ts b/src/web/src/lib/native-oauth-schema.ts
index 735eb17fb..37e2280c8 100644
--- a/src/web/src/lib/native-oauth-schema.ts
+++ b/src/web/src/lib/native-oauth-schema.ts
@@ -1,9 +1,9 @@
-import { isSafeRedirectPath } from "@alook/shared"
+import { isSafeRedirectPath, nativeOauthProviderSchema } from "@alook/shared"
import { z } from "zod"
export const nativeOauthSnapshotSchema = z.object({
attemptId: z.string(),
- provider: z.enum(["github", "google"]),
+ provider: nativeOauthProviderSchema,
redirectPath: z.string().refine(isSafeRedirectPath),
expiresAt: z.number(),
waiting: z.boolean(),
diff --git a/src/web/src/test/e2e/native-oauth-schema.test.ts b/src/web/src/test/e2e/native-oauth-schema.test.ts
index 7d3b874e8..fedc26bb2 100644
--- a/src/web/src/test/e2e/native-oauth-schema.test.ts
+++ b/src/web/src/test/e2e/native-oauth-schema.test.ts
@@ -5,16 +5,21 @@ const TABLE = "native_oauth_attempt";
const NOW = 1_788_531_200_000;
const INSTANCE = "a".repeat(64);
-function insertPending(id: string, instanceKeyHash = INSTANCE): void {
+function insertPending(
+ id: string,
+ instanceKeyHash = INSTANCE,
+ provider: "github" | "google" | "apple" = "github",
+): void {
sqlRun(
`INSERT INTO ${TABLE} (
id, instance_key_hash, state_hash, pkce_challenge, provider, platform,
redirect_path, status, attempt_expires_at, created_at, updated_at
- ) VALUES (?, ?, ?, ?, 'github', 'ios', '/c/me', 'pending', ?, ?, ?)`,
+ ) VALUES (?, ?, ?, ?, ?, 'ios', '/c/me', 'pending', ?, ?, ?)`,
id,
instanceKeyHash,
"b".repeat(64),
"c".repeat(43),
+ provider,
NOW + 600_000,
NOW,
NOW,
@@ -91,6 +96,17 @@ describe("native_oauth_attempt migration parity", () => {
expect(() => insertPending("attempt_new_123456789012")).not.toThrow();
});
+ it.each(["github", "google", "apple"] as const)(
+ "accepts the %s provider through the frozen migration CHECK",
+ (provider) => {
+ expect(() => insertPending(
+ `attempt_${provider}_123456789012`,
+ INSTANCE,
+ provider,
+ )).not.toThrow();
+ },
+ );
+
it("rejects malformed hashes, unsafe redirects, invalid enums, and bad epochs", () => {
expect(() => insertPending("too_short")).toThrow(/CHECK constraint failed/i);
expect(() => {