The open-source AI receptionist for businesses. Answers every call, books the appointment and hands over to a person when needed. You own the code and the data.
TypeScript ai-receptionistanswering-serviceappointment-bookinglivekitlocal-firstmcpopen-sourceself-hostedsiptelephonytypescriptvoice-agentvoice-ai
Sign in with Apple on the web and in the apps (PR 1988)
Tim Gutberlet8f65244a3e97
diff --git a/apps/api/src/admin-handlers.ts b/apps/api/src/admin-handlers.tsindex d564860c..c74d301c 100644--- a/apps/api/src/admin-handlers.ts+++ b/apps/api/src/admin-handlers.ts@@ -23,6 +23,7 @@ import { createEmailSender, type EmailSender, emailSender, emailSettingsOf, sendimport { emailSafeName, passkeyEnrolmentIssuedEmail, welcomeEmail } from './emails/templates.ts'import { db } from './db.ts'import { and, eq, ne, or, sql } from 'drizzle-orm'+import { toPem } from './apple-sign-in.ts'import { Forbidden, type Handler, type HandlerCtx, Reject, wordsOf } from './handler-context.ts'import { SOURCE } from '@linedesk/i18n'import { alertInstanceAdmins } from './admin-alerts.ts'@@ -358,6 +359,14 @@ export const adminHandlers: Record<string, Handler> = {}// Billing keys: only an admin as themselves with the passkey, never while billing is on, never a live key where// the server does not allow one (billing-settings.ts).+ // A Sign in with Apple key that does not sign is never stored (apple-sign-in.ts; security review of #1988, M1).+ if (input.provider === 'apple' && input.values.private_key) {+ try {+ toPem(input.values.private_key)+ } catch {+ throw Reject.t('server.api.providerTest.apple.keyNotP8')+ }+ }if (moneyCategories.includes(providerSpec(input.provider).category)) refuseMoneyKeysChange(actor)if (input.provider === 'stripe') {await refuseStripeKeysWhileOn(tx, input.values, actor, now)diff --git a/apps/api/src/admin-overview.ts b/apps/api/src/admin-overview.tsindex 692c21d7..46ff16b3 100644--- a/apps/api/src/admin-overview.ts+++ b/apps/api/src/admin-overview.ts@@ -45,6 +45,7 @@ export const pricePerMinute: Record<ProviderName, number> = {file: 0,s3: 0,// Email, sign-in and calendar apps are not billed per call minute either.+ apple: 0,calendly: 0,calcom: 0,hubspot: 0,diff --git a/apps/api/src/app.ts b/apps/api/src/app.tsindex 71b326ed..c20c3555 100644--- a/apps/api/src/app.ts+++ b/apps/api/src/app.ts@@ -59,6 +59,7 @@ import { mcpCors, registerOAuthRoutes } from './oauth.ts'import { registerAppLinkRoutes } from './app-links.ts'import { setsUpByHand } from './install-setup.ts'import { authMethods, currentAuthMethods } from './auth-methods.ts'+import { APPLE_CALLBACK_MAX_BYTES, appleCallbackRedirect } from './apple-sign-in.ts'import { browserErrorReporting, errorReportingEnabled, type ReportedUser, reportError } from './error-reporting.ts'import { billingRules } from './billing-rules.ts'import { accountTrialUsed } from './billing-checkout.ts'@@ -213,6 +214,12 @@ app.get('/v1/health/host', c => {if (!probed) return c.json({ ok: false, error: 'not found' }, 404)return c.json({ ok: true, domainId: probed.domainId, proof: probed.proof })})+// Apple comes back with a cross-site form POST: answered as the GET every other provider sends (apple-sign-in.ts).+app.post(+ '/api/auth/callback/apple',+ bodyLimit({ maxSize: APPLE_CALLBACK_MAX_BYTES, onError: c => c.body(null, 413) }),+ async c => c.redirect(appleCallbackRedirect(await c.req.parseBody()), 303),+)app.on(['GET', 'POST'], '/api/auth/*', c => {const request = withClientIp(c)// Better Auth reads the trusted origins from this Request (auth.ts): the host the middleware resolved for it.diff --git a/apps/api/src/apple-sign-in.test.ts b/apps/api/src/apple-sign-in.test.tsnew file mode 100644index 00000000..5483753e--- /dev/null+++ b/apps/api/src/apple-sign-in.test.ts@@ -0,0 +1,102 @@+import { createPublicKey, generateKeyPairSync, verify } from 'node:crypto'+import { describe, expect, it } from 'vitest'+import { appleCallbackRedirect, appleClientSecret, appleProvider, readAppleConfig, toPem } from './apple-sign-in.ts'++const { privateKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' })+const pem = privateKey.export({ type: 'pkcs8', format: 'pem' }).toString()+const env = {+ APPLE_CLIENT_ID: 'ai.example.signin',+ APPLE_TEAM_ID: 'TEAM123456',+ APPLE_KEY_ID: 'KEY1234567',+ APPLE_PRIVATE_KEY: pem,+}++const decode = (part: string) => JSON.parse(Buffer.from(part, 'base64url').toString())++describe('readAppleConfig', () => {+ it('is off until all four values are there', () => {+ expect(readAppleConfig({})).toBeNull()+ expect(readAppleConfig({ ...env, APPLE_KEY_ID: ' ' })).toBeNull()+ expect(readAppleConfig(env)).toMatchObject({+ clientId: 'ai.example.signin',+ teamId: 'TEAM123456',+ appBundleId: null,+ })+ expect(readAppleConfig({ ...env, APPLE_APP_BUNDLE_ID: 'ai.example.app' })?.appBundleId).toBe('ai.example.app')+ })+})++describe('toPem', () => {+ it('takes the key on one line, with \\n, or as Apple gives it', () => {+ const oneLine = pem.replace(/\n/g, ' ')+ const escaped = pem.replace(/\n/g, '\\n')+ expect(toPem(oneLine)).toBe(toPem(pem))+ expect(toPem(escaped)).toBe(toPem(pem))+ })++ it('refuses something that is not an Apple (EC P-256) key', () => {+ expect(() => toPem('not a key')).toThrow(/APPLE_PRIVATE_KEY/)+ const rsa = generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey.export({ type: 'pkcs8', format: 'pem' })+ expect(() => toPem(rsa.toString())).toThrow(/APPLE_PRIVATE_KEY/)+ })++ it('turns Apple off for a bad key instead of failing the start', () => {+ expect(readAppleConfig({ ...env, APPLE_PRIVATE_KEY: 'junk' })).toBeNull()+ })+})++describe('appleClientSecret', () => {+ it('is an ES256 JWT for Apple, signed with the key, valid for 150 days', () => {+ const config = readAppleConfig(env)!+ const jwt = appleClientSecret(config, 1_000_000)+ const [header, claims, signature] = jwt.split('.') as [string, string, string]+ expect(decode(header)).toEqual({ alg: 'ES256', kid: 'KEY1234567' })+ expect(decode(claims)).toEqual({+ iss: 'TEAM123456',+ iat: 1_000_000,+ exp: 1_000_000 + 150 * 24 * 60 * 60,+ aud: 'https://appleid.apple.com',+ sub: 'ai.example.signin',+ })+ const ok = verify(+ 'sha256',+ Buffer.from(`${header}.${claims}`),+ { key: createPublicKey(privateKey), dsaEncoding: 'ieee-p1363' },+ Buffer.from(signature, 'base64url'),+ )+ expect(ok).toBe(true)+ })+})++describe('appleProvider', () => {+ it('makes the client secret when it is read, and keeps it until it is renewed', () => {+ const provider = appleProvider(readAppleConfig({ ...env, APPLE_APP_BUNDLE_ID: 'ai.example.app' })!, null)+ const first = provider.clientSecret+ expect(first.split('.')).toHaveLength(3)+ expect(provider.clientSecret).toBe(first)+ expect(provider).toMatchObject({ clientId: 'ai.example.signin', appBundleIdentifier: 'ai.example.app' })+ })+})++describe('appleCallbackRedirect', () => {+ it('passes the answer on as a GET and drops everything else', () => {+ const user = JSON.stringify({ name: { firstName: 'Mike', lastName: 'Brennan' }, email: '[email protected]' })+ const url = appleCallbackRedirect({ code: 'c1', state: 's1', id_token: 'x', user, other: 'y' })+ expect(url.startsWith('/api/auth/callback/apple?')).toBe(true)+ const params = new URLSearchParams(url.split('?')[1])+ // The name only: the email never goes into the address.+ expect(Object.fromEntries(params)).toEqual({+ code: 'c1',+ state: 's1',+ user: JSON.stringify({ name: { firstName: 'Mike', lastName: 'Brennan' } }),+ })+ expect(new URLSearchParams(appleCallbackRedirect({ code: 'c', user: 'not json' }).split('?')[1]).has('user')).toBe(+ false,+ )+ })++ it('passes an error on', () => {+ const params = new URLSearchParams(appleCallbackRedirect({ error: 'user_cancelled_authorize' }).split('?')[1])+ expect(params.get('error')).toBe('user_cancelled_authorize')+ })+})diff --git a/apps/api/src/apple-sign-in.ts b/apps/api/src/apple-sign-in.tsnew file mode 100644index 00000000..784bc9dd--- /dev/null+++ b/apps/api/src/apple-sign-in.ts@@ -0,0 +1,154 @@+// Sign in with Apple (Better Auth's `apple` provider). Apple has no fixed client secret: it is a JWT the install signs+// with its Sign in with Apple key (ES256), valid at most six months. It is made here from the four values the operator+// enters (Server admin › Providers, or APPLE_* in .env) and made again before it runs out, so a server that runs for+// months keeps signing people in.+import { createPrivateKey, sign } from 'node:crypto'++type Env = Record<string, string | undefined>++export type AppleConfig = {+ /** The Services ID of the website (APPLE_CLIENT_ID), e.g. ai.linedesk.signin. */+ clientId: string+ teamId: string+ keyId: string+ /** The .p8 key's PEM. */+ privateKey: string+ /** The iOS app's bundle ID (optional): a sign-in made in the app carries it as the token's audience. */+ appBundleId: string | null+}++/**+ * The Apple sign-in settings, or null while one of the four required values is missing or the key is not a Sign in+ * with Apple key. A bad key only turns Apple off (one log line, never the key): the API must start, so an admin can+ * fix it in Server admin (security review of #1988, M1). `provider.setKeys` refuses such a key anyway.+ */+export function readAppleConfig(env: Env): AppleConfig | null {+ const clientId = env.APPLE_CLIENT_ID?.trim()+ const teamId = env.APPLE_TEAM_ID?.trim()+ const keyId = env.APPLE_KEY_ID?.trim()+ const key = env.APPLE_PRIVATE_KEY?.trim()+ if (!clientId || !teamId || !keyId || !key) return null+ let privateKey: string+ try {+ privateKey = toPem(key)+ } catch (e) {+ console.error(`Sign in with Apple is off: ${(e as Error).message}`)+ return null+ }+ return { clientId, teamId, keyId, privateKey, appBundleId: env.APPLE_APP_BUNDLE_ID?.trim() || null }+}++const PEM_LABEL = ['PRIVATE', 'KEY'].join(' ')++/**+ * The key as PEM. A form field keeps no line breaks, and an env file often holds the key on one line with `\n`: both+ * come back to the PEM Apple's file has. A key that is not one fails at start, not at the first sign-in.+ */+export function toPem(raw: string): string {+ const body = raw+ .replace(/\\n/g, '\n')+ .replace(/-----(BEGIN|END) PRIVATE KEY-----/g, '')+ .replace(/\s+/g, '')+ // The PEM armour is put together from its parts: written out whole it reads to secret scanners as a key.+ const armour = (edge: 'BEGIN' | 'END') => `-----${edge} ${PEM_LABEL}-----`+ const pem = `${armour('BEGIN')}\n${body.match(/.{1,64}/g)?.join('\n') ?? ''}\n${armour('END')}\n`+ // Apple's keys are EC P-256 (ES256); any other PEM key would sign a client secret Apple refuses at every sign-in.+ let fits = false+ try {+ const key = createPrivateKey(pem)+ fits = key.asymmetricKeyType === 'ec' && key.asymmetricKeyDetails?.namedCurve === 'prime256v1'+ } catch {+ fits = false+ }+ if (!fits)+ throw new Error('APPLE_PRIVATE_KEY is not the .p8 key Apple gave (Certificates, Identifiers & Profiles › Keys)')+ return pem+}++/** Apple accepts a client secret for at most 6 months; this one lasts 150 days and is renewed after 30. */+const SECRET_LIFETIME_S = 150 * 24 * 60 * 60+const RENEW_AFTER_S = 30 * 24 * 60 * 60++const base64url = (value: string | Buffer) => Buffer.from(value).toString('base64url')++/** The client secret JWT Apple's token endpoint wants (developer.apple.com: "Creating a client secret"). */+export function appleClientSecret(config: AppleConfig, nowS = Math.floor(Date.now() / 1000)): string {+ const header = base64url(JSON.stringify({ alg: 'ES256', kid: config.keyId }))+ const claims = base64url(+ JSON.stringify({+ iss: config.teamId,+ iat: nowS,+ exp: nowS + SECRET_LIFETIME_S,+ aud: 'https://appleid.apple.com',+ sub: config.clientId,+ }),+ )+ const signature = sign('sha256', Buffer.from(`${header}.${claims}`), {+ key: config.privateKey,+ dsaEncoding: 'ieee-p1363',+ })+ return `${header}.${claims}.${base64url(signature)}`+}++/**+ * Better Auth's `apple` provider options. `clientSecret` is a getter: the provider reads it at each code exchange, so+ * the secret is renewed while the server runs instead of running out after 150 days. So the object is passed on as+ * it is: spreading it would read the getter once.+ */+export function appleProvider<M>(config: AppleConfig, mapProfileToUser: M) {+ let secret = ''+ let madeAt = 0+ return {+ clientId: config.clientId,+ get clientSecret() {+ const now = Math.floor(Date.now() / 1000)+ if (!secret || now - madeAt > RENEW_AFTER_S) {+ secret = appleClientSecret(config, now)+ madeAt = now+ }+ return secret+ },+ ...(config.appBundleId && { appBundleIdentifier: config.appBundleId }),+ mapProfileToUser,+ }+}++/** The fields of Apple's form POST back to the callback (response_mode=form_post) that the callback reads. */+const CALLBACK_FIELDS = ['code', 'state', 'error', 'error_description'] as const++/** Apple's form POST is a few KB at most (route body limit in app.ts). */+export const APPLE_CALLBACK_MAX_BYTES = 16 * 1024++/**+ * Apple's `user` (only at a person's first sign-in): its name, which the address bar of the GET may carry, and its+ * email, which may not (the email comes from Apple's token anyway). Null when there is no usable name.+ */+function userNameOnly(value: unknown): string | null {+ if (typeof value !== 'string') return null+ try {+ const name = (JSON.parse(value) as { name?: { firstName?: unknown; lastName?: unknown } })?.name+ const part = (v: unknown) => (typeof v === 'string' ? v.slice(0, 100) : undefined)+ const firstName = part(name?.firstName)+ const lastName = part(name?.lastName)+ return firstName || lastName ? JSON.stringify({ name: { firstName, lastName } }) : null+ } catch {+ return null+ }+}++/**+ * Apple returns from its sign-in page with a cross-site form POST. Better Auth checks a POST's Origin+ * (appleid.apple.com, not ours) whenever any cookie comes along, and the sign-in's own state cookie (SameSite=Lax) is+ * not sent with it. The same answer as a GET to the same callback, which the browser makes with that cookie, is what+ * every other provider sends: this is where the POST is turned into it.+ */+export function appleCallbackRedirect(form: Record<string, unknown>): string {+ const params = new URLSearchParams()+ for (const field of CALLBACK_FIELDS) {+ const value = form[field]+ if (typeof value === 'string' && value.length <= 2048) params.set(field, value)+ }+ const user = userNameOnly(form.user)+ if (user) params.set('user', user)+ return `/api/auth/callback/apple?${params}`+}diff --git a/apps/api/src/auth-methods.test.ts b/apps/api/src/auth-methods.test.tsindex 867375eb..35ff5a50 100644--- a/apps/api/src/auth-methods.test.ts+++ b/apps/api/src/auth-methods.test.ts@@ -1,3 +1,4 @@+import { generateKeyPairSync } from 'node:crypto'import { describe, expect, it } from 'vitest'import { readAuthConfig, readLegalLinks, signUpSettingRemovedWarning } from './auth-methods.ts'@@ -22,6 +23,10 @@ describe('readLegalLinks', () => {})})+const appleKey = generateKeyPairSync('ec', { namedCurve: 'P-256' })+ .privateKey.export({ type: 'pkcs8', format: 'pem' })+ .toString()+describe('readAuthConfig', () => {it('offers only the password (and passkeys, added after signing in) with no env set', () => {expect(readAuthConfig({}).methods).toEqual({@@ -36,8 +41,12 @@ describe('readAuthConfig', () => {it('names the address provider sign-ins must start from: BETTER_AUTH_URL, else PUBLIC_URL, else WEB_ORIGIN', () => {const origin = (env: Record<string, string>) => readAuthConfig(env).methods.signInOrigin- expect(origin({ BETTER_AUTH_URL: 'https://abc.ngrok.app/api/auth', PUBLIC_URL: 'http://x.localhost' })).toBe('https://abc.ngrok.app')- expect(origin({ PUBLIC_URL: 'https://desk.example.com/', WEB_ORIGIN: 'http://localhost:5173' })).toBe('https://desk.example.com')+ expect(origin({ BETTER_AUTH_URL: 'https://abc.ngrok.app/api/auth', PUBLIC_URL: 'http://x.localhost' })).toBe(+ 'https://abc.ngrok.app',+ )+ expect(origin({ PUBLIC_URL: 'https://desk.example.com/', WEB_ORIGIN: 'http://localhost:5173' })).toBe(+ 'https://desk.example.com',+ )expect(origin({ WEB_ORIGIN: 'http://localhost:5173' })).toBe('http://localhost:5173')expect(origin({ BETTER_AUTH_URL: 'not a url', WEB_ORIGIN: 'http://localhost:5173' })).toBe('http://localhost:5173')})@@ -111,9 +120,13 @@ describe('readAuthConfig', () => {OIDC_CLIENT_ID: 'id',OIDC_CLIENT_SECRET: 's',OIDC_DISCOVERY_URL: 'https://id.example.com/.well-known/openid-configuration',+ APPLE_CLIENT_ID: 'ai.example.signin',+ APPLE_TEAM_ID: 'TEAM123456',+ APPLE_KEY_ID: 'KEY1234567',+ APPLE_PRIVATE_KEY: appleKey,}expect(readAuthConfig(all).trustedProviders).toEqual([])- expect(readAuthConfig(all).methods.sso.map(m => m.id)).toEqual(['google', 'microsoft', 'github', 'oidc'])+ expect(readAuthConfig(all).methods.sso.map(m => m.id)).toEqual(['google', 'apple', 'microsoft', 'github', 'oidc'])})})})@@ -121,7 +134,8 @@ describe('readAuthConfig', () => {describe('AUTH_SIGNUP_ENABLED', () => {it('is gone: any value only brings a warning at start, and the sign-in screen offers no sign-up', () => {expect(signUpSettingRemovedWarning({})).toBeNull()- for (const value of ['', 'false', 'true']) expect(signUpSettingRemovedWarning({ AUTH_SIGNUP_ENABLED: value })).toMatch(/no longer read/)+ for (const value of ['', 'false', 'true'])+ expect(signUpSettingRemovedWarning({ AUTH_SIGNUP_ENABLED: value })).toMatch(/no longer read/)expect(readAuthConfig({ AUTH_SIGNUP_ENABLED: 'true' }).methods).not.toHaveProperty('signUp')})})diff --git a/apps/api/src/auth-methods.ts b/apps/api/src/auth-methods.tsindex e16c8f73..bce4f7f6 100644--- a/apps/api/src/auth-methods.ts+++ b/apps/api/src/auth-methods.ts@@ -1,5 +1,6 @@// Which ways to sign in this install offers. Everything except the password is switched on by// setting its env vars, so a self-hosted install works with none of them.+import { readAppleConfig } from './apple-sign-in.ts'import type { AuthMethods, LegalLinks, SsoMethod } from './auth-types.ts'type Env = Record<string, string | undefined>@@ -23,6 +24,7 @@ export function readAuthConfig(env: Env) {const github = pair(env.GITHUB_CLIENT_ID, env.GITHUB_CLIENT_SECRET)const microsoftKeys = pair(env.MICROSOFT_CLIENT_ID, env.MICROSOFT_CLIENT_SECRET)const microsoft = microsoftKeys && { ...microsoftKeys, tenantId: env.MICROSOFT_TENANT_ID || 'common' }+ const apple = readAppleConfig(env)const oidcKeys = pair(env.OIDC_CLIENT_ID, env.OIDC_CLIENT_SECRET)const oidcName = env.OIDC_DISPLAY_NAME?.trim()const oidc =@@ -40,6 +42,7 @@ export function readAuthConfig(env: Env) {passkey: passkeySignInEnabled(env),sso: [google && { id: 'google', label: 'Google' },+ apple && { id: 'apple', label: 'Apple' },microsoft && { id: 'microsoft', label: 'Microsoft' },github && { id: 'github', label: 'GitHub' },oidc && { id: 'oidc', label: oidc.label, ...(oidc.unnamed ? { unnamed: true } : {}) },@@ -47,7 +50,7 @@ export function readAuthConfig(env: Env) {links: readLegalLinks(env),signInOrigin: signInOrigin(env),}- return { google, microsoft, github, oidc, trustedProviders, methods }+ return { google, apple, microsoft, github, oidc, trustedProviders, methods }}/** Where provider sign-ins come back to: BETTER_AUTH_URL, else PUBLIC_URL, else WEB_ORIGIN (its origin only). */diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.tsindex 3cb30ccd..6ddea676 100644--- a/apps/api/src/auth.ts+++ b/apps/api/src/auth.ts@@ -4,6 +4,7 @@ import { APIError, createAuthMiddleware } from 'better-auth/api'import { drizzleAdapter } from 'better-auth/adapters/drizzle'import { emailOTP, genericOAuth, organization } from 'better-auth/plugins'import { appSignIn } from './app-sign-in.ts'+import { appleProvider } from './apple-sign-in.ts'import { authConfig, emailCodesOn } from './auth-methods.ts'import { accountLinkingHooks, mapGoogleProfile, mapMicrosoftProfile, mapOidcProfile } from './account-linking.ts'import { auditHooks, recordAuthEndpoint } from './audit.ts'@@ -51,7 +52,7 @@ import { clearProfileChangeAfterOwnUpdate } from './user-avatar.ts'import { releaseWorkspaceClones } from './voices.ts'import { localeForEmail } from './email-locale.ts'-const { google, microsoft, github, oidc, trustedProviders, methods } = authConfig+const { google, apple, microsoft, github, oidc, trustedProviders, methods } = authConfig/** Where the web app is served from; the only origin browser requests are accepted from. */export const WEB_ORIGIN = process.env.WEB_ORIGIN ?? 'http://localhost:5173'@@ -311,6 +312,8 @@ export const auth = betterAuth({socialProviders: {// A sign-in whose email the provider does not prove has no email and signs nobody in (account-linking.ts)....(google && { google: { ...google, mapProfileToUser: mapGoogleProfile } }),+ // Like Google, Apple says whether it verified the address (`email_verified`, also for its private relay addresses).+ ...(apple && { apple: appleProvider(apple, mapGoogleProfile) }),...(microsoft && { microsoft: { ...microsoft, mapProfileToUser: mapMicrosoftProfile } }),...(github && { github: githubProvider(github) }),},diff --git a/apps/api/src/provider-test.ts b/apps/api/src/provider-test.tsindex 990f9395..782e1360 100644--- a/apps/api/src/provider-test.ts+++ b/apps/api/src/provider-test.ts@@ -24,6 +24,7 @@ import { LIVE_KEYS_REFUSED, liveKeysAllowed, loadBillingProvider, stripeKeyModeimport { JOBBER_API, JOBBER_CLIENT_REFUSED, ZOHO_CLIENT_REFUSED, ZOHO_DATA_CENTERS } from '@linedesk/connectors'import { msg } from '@linedesk/i18n'import { probeApns, probeFcm, readApnsConfig, readFcmConfig } from './native-push.ts'+import { toPem } from './apple-sign-in.ts'import { smtpCheck } from './email.ts'import { ResendError, resendKeyCheck } from './email-resend.ts'import { isMailService, type MailService, mailConnectionOf } from './email-services.ts'@@ -585,6 +586,18 @@ const fcm: Check = async values => {}}+// Apple answers a made-up code, refresh token or revoke the same for a right and a wrong client secret (tried+// 2026-11-28: invalid_grant, or 200 for revoke), so nothing can test the keys from here. What can be checked here is+// that the key is a .p8 key that signs the client secret (apple-sign-in.ts); the rest at the first sign-in.+const apple: Check = async values => {+ try {+ toPem(values.private_key ?? '')+ } catch {+ return error('config', said('server.api.providerTest.apple.keyNotP8'))+ }+ return ok(said('server.api.providerTest.oauth.checkedAtSignIn', { provider: providerSpec('apple').label }))+}+// Shopify's token endpoint lives on each shop's own domain, so without a shop nothing can test the client secret: only// the client ID's form is checked here, the keys themselves when the first business connects.const shopify: Check = async values => {@@ -616,6 +629,7 @@ const checks: Record<HttpProvider, Check> = {jobber,shopify,zoho,+ apple,turnstile,cloudflare_saas: cloudflareSaas,apns,diff --git a/apps/api/src/setup-mcp.ts b/apps/api/src/setup-mcp.tsindex 947b74ea..70f3f8b5 100644--- a/apps/api/src/setup-mcp.ts+++ b/apps/api/src/setup-mcp.ts@@ -941,6 +941,7 @@ function redirectUris(provider: ProviderName): string[] {]if (provider === 'google_mail') return [`${app}/v1/mail/callback/google`]if (provider === 'github') return [`${app}/api/auth/callback/github`]+ if (provider === 'apple') return [`${app}/api/auth/callback/apple`]if (provider === 'oidc') return [`${app}/api/auth/oauth2/callback/oidc`]if (provider === 'calendly' || provider === 'calcom') return [`${app}/v1/calendar/callback/${provider}`]if (diff --git a/apps/web/src/admin/AuditLog.tsx b/apps/web/src/admin/AuditLog.tsxindex 3ccfa50b..b4c56a38 100644--- a/apps/web/src/admin/AuditLog.tsx+++ b/apps/web/src/admin/AuditLog.tsx@@ -149,7 +149,12 @@ const methods: Record<string, MessageKey> = {app: msg('admin.audit.method.app'),}/** Brand names stay as they are. */-const brandMethods: Record<string, string> = { google: 'Google', microsoft: 'Microsoft', github: 'GitHub' }+const brandMethods: Record<string, string> = {+ google: 'Google',+ apple: 'Apple',+ microsoft: 'Microsoft',+ github: 'GitHub',+}const method = (m: string | null) => {if (!m) return ''const key = methods[m]diff --git a/apps/web/src/admin/ProviderLogo.tsx b/apps/web/src/admin/ProviderLogo.tsxindex 90d5ce74..1c470968 100644--- a/apps/web/src/admin/ProviderLogo.tsx+++ b/apps/web/src/admin/ProviderLogo.tsx@@ -189,6 +189,11 @@ export const providerMeta: Record<ProviderName, Meta> = {blurb: msg('admin.provider.blurb.google_mail'),keysUrl: 'https://console.cloud.google.com/apis/credentials',},+ apple: {+ mark: { brand: 'apple' },+ blurb: msg('admin.provider.blurb.apple'),+ keysUrl: 'https://developer.apple.com/account/resources/identifiers/list/serviceId',+ },github: {mark: { brand: 'github' },blurb: msg('admin.provider.blurb.github'),@@ -222,6 +227,7 @@ export function redirectUris(provider: ProviderName, origin: string): string[] {]if (provider === 'google_mail') return [`${origin}/v1/mail/callback/google`]if (provider === 'github') return [`${origin}/api/auth/callback/github`]+ if (provider === 'apple') return [`${origin}/api/auth/callback/apple`]// Calendly allows exactly one redirect URI per app: the calendar one.if (provider === 'calendly' || provider === 'calcom') return [`${origin}/v1/calendar/callback/${provider}`]if (provider === 'oidc') return [`${origin}/api/auth/oauth2/callback/oidc`]diff --git a/apps/web/src/admin/logos.ts b/apps/web/src/admin/logos.tsindex f7899802..ede0c5f5 100644--- a/apps/web/src/admin/logos.ts+++ b/apps/web/src/admin/logos.ts@@ -41,6 +41,8 @@ export const brandMarks = {'M0 0v24h24V0H0zm4.602 4.025h2.244c.509 0 .716.215.716.717v5.64h8.883v-5.64c0-.509.215-.717.717-.717h2.229c.5 0 .71.23.724.717v14.516c0 .509-.215.717-.717.717h-2.23c-.51 0-.717-.215-.717-.717v-5.735H7.562v5.735c0 .516-.215.717-.716.717H4.602c-.51 0-.717-.208-.717-.717V4.742c0-.509.207-.717.717-.717z',google:'M12.48 10.92v3.28h7.84c-.24 1.84-.853 3.187-1.787 4.133-1.147 1.147-2.933 2.4-6.053 2.4-4.827 0-8.6-3.893-8.6-8.72s3.773-8.72 8.6-8.72c2.6 0 4.507 1.027 5.907 2.347l2.307-2.307C18.747 1.44 16.133 0 12.48 0 5.867 0 .307 5.387.307 12s5.56 12 12.173 12c3.573 0 6.267-1.173 8.373-3.36 2.16-2.16 2.84-5.213 2.84-7.667 0-.76-.053-1.467-.173-2.053H12.48z',+ apple:+ 'M12.152 6.896c-.948 0-2.415-1.078-3.96-1.04-2.04.027-3.91 1.183-4.961 3.014-2.117 3.675-.546 9.103 1.519 12.09 1.013 1.454 2.208 3.09 3.792 3.039 1.52-.065 2.09-.987 3.935-.987 1.831 0 2.35.987 3.96.948 1.637-.026 2.676-1.48 3.676-2.948 1.156-1.688 1.636-3.325 1.662-3.415-.039-.013-3.182-1.221-3.22-4.857-.026-3.04 2.48-4.494 2.597-4.559-1.429-2.09-3.623-2.324-4.39-2.376-2-.156-3.675 1.09-4.61 1.09zM15.53 3.83c.843-1.012 1.4-2.427 1.245-3.83-1.207.052-2.662.805-3.532 1.818-.78.896-1.454 2.338-1.273 3.714 1.338.104 2.715-.688 3.559-1.701',github:'M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12',// Cal.com: only "Cal" from the Simple Icons wordmark (the full "Cal.com" is unreadable at icon size), drawn in brandViewBox.diff --git a/apps/web/src/auth.ts b/apps/web/src/auth.tsindex acf62f1b..4e95e540 100644--- a/apps/web/src/auth.ts+++ b/apps/web/src/auth.ts@@ -362,7 +362,12 @@ export async function startSso(return { error: null }}-const providerNames: Record<string, string> = { google: 'Google', microsoft: 'Microsoft', github: 'GitHub' }+const providerNames: Record<string, string> = {+ google: 'Google',+ apple: 'Apple',+ microsoft: 'Microsoft',+ github: 'GitHub',+}/** The provider didn't prove the address, so it signs nobody in (the API's account-linking rule). */const unprovenEmail = (provider: string | null) => {diff --git a/apps/web/src/ui/brand-logos.tsx b/apps/web/src/ui/brand-logos.tsxindex 3c4c08c3..4c8cd0fb 100644--- a/apps/web/src/ui/brand-logos.tsx+++ b/apps/web/src/ui/brand-logos.tsx@@ -4,6 +4,8 @@// - Microsoft logo: Microsoft identity platform sign-in branding guidelines// (learn.microsoft.com/entra/identity-platform/howto-add-branding-in-apps), four squares.// - GitHub mark: GitHub logos (github.com/logos), the Octicons `mark-github` path; drawn in the text colour.+// - Apple logo: Sign in with Apple guidelines (developer.apple.com/design/human-interface-guidelines/sign-in-with-apple),+// the Simple Icons path in admin/logos.ts, drawn in the text colour like the black and white buttons.// - Cal.com, Calendly, iCloud (calendar accounts): the Simple Icons paths in admin/logos.ts, in each brand's colour// (Simple Icons' hex; Cal.com's is near-black, so it is drawn in the text colour). A CalDAV server that is not// iCloud gets a neutral calendar.@@ -94,7 +96,7 @@ const PasswordMark = () =></g>,)-const simpleMark = (brand: 'caldotcom' | 'calendly' | 'icloud', fill: string) => () =>+const simpleMark = (brand: 'apple' | 'caldotcom' | 'calendly' | 'icloud', fill: string) => () =>svg(brandViewBox(brand), <path fill={fill} d={brandMarks[brand]} />)const CalendarMark = () => <Icon name="calendar" size={18} className="auth-logo" />@@ -103,6 +105,7 @@ const marks: Record<string, () => ReactNode> = {google: GoogleMark,microsoft: MicrosoftMark,github: GitHubMark,+ apple: simpleMark('apple', 'currentColor'),calcom: simpleMark('caldotcom', 'currentColor'),calendly: simpleMark('calendly', '#006BFF'),icloud: simpleMark('icloud', '#3693F3'),diff --git a/docs/architecture.md b/docs/architecture.mdindex 686d4cf3..8a8f71a9 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -55,7 +55,7 @@ Out of scope for v1: messaging channels, outbound campaigns, multi-location rout| Database | **Postgres** + **Drizzle** (schema + migrations) | Source of truth || Sync to clients | Own **outbox** for writes + `ReadSyncAdapter` for reads; **Electric** default, PowerSync tested swap, LISTEN/NOTIFY + WebSocket possible | See §6 || Jobs | **pg-boss** | Post-call summaries, notifications, calendar sync, reminders, webhooks |-| Auth | **Better Auth**: email sign-in code + Google/Microsoft/GitHub sign-in, organizations, API keys, OAuth provider for MCP | Same OAuth consent can grant calendar access |+| Auth | **Better Auth**: email sign-in code + Google/Apple/Microsoft/GitHub sign-in, organizations, API keys, OAuth provider for MCP | Same OAuth consent can grant calendar access || Calendar | Own **Google Calendar**, **Microsoft Graph**, **CalDAV** (iCloud, Fastmail, Nextcloud), **Cal.com** and **Calendly** adapters | See §8 || Recordings | LiveKit egress into a `RecordingStore`: a shared directory (default, self-hosted) or any S3-compatible bucket (AWS S3, Cloudflare R2, Hetzner, Backblaze B2, MinIO), picked under Server admin › Providers › Recording storage (§12) | Played through an authenticated API route; signed URLs with S3. Each call keeps the store its recording is in (`calls.recording_store`) || Web app | **React SPA (Vite)** with local store, outbox, service worker | Built from the merged prototype (`prototypes/inbox-html`, Relay design) |@@ -362,7 +362,7 @@ Better Auth's admin plugin was not used: it adds impersonation, user creation, p**An owner deleting their own workspace.** `workspace.deleteOwn` { name, keepOwnAccount?, keepAccounts? } (`workspace:own`, which only the owner role has, and the handler refuses anyone but the owner of the workspace, and impersonations; `apps/api/src/workspace-delete-own.ts`; Workspace settings › Danger zone, "Delete workspace…"). The same delete as above, plus: a fresh sign-in first (`apps/api/src/owner-step-up.ts`, checked in `run-action.ts` before the transaction and again in the handler): a sign-in in the last 10 minutes, and when the owner has a passkey that sign-in must be the passkey (`PASSKEY_STEP_UP_REQUIRED`, the web app's passkey dialog); without one the refusal is `SIGN_IN_AGAIN` and the dialog offers "Sign in again", which comes back to it. `ADMIN_SECOND_FACTOR=off` leaves only the 10 minutes. It waits for a confirmed email address like inviting. Every other member gets an email (`workspace.deletedEmail` job, queued in the transaction: who deleted it, when in the workspace's time zone, whether their account went too). Accounts: members who belong to no other workspace and are not instance admins are deleted, and so is the owner's own, unless `keepAccounts` (every account stays) or `keepOwnAccount` (only the owner's stays; then they land on the no-workspace page); an owner with another workspace continues there (`nextWorkspaceId`). `workspace.deletePreview` (owners, read-only) gives the dialog its counts (calls, contacts, numbers bought and attached, other members, accounts that go, whether the owner's own goes) and the step-up the server would ask for now. Command log kind `team`.-**Providers.** The registry in `packages/actions/src/admin.ts` describes each provider: label, category (telephony, speech to text, language model, voice, realtime model, email, sign-in and calendar, recording storage), its fields and which are secret or optional; `apps/api/src/provider-test.ts` holds how to test its connection. Shipped: Telnyx (API key, webhook public key; the default carrier), Twilio (account SID, auth token), Deepgram (API key), ElevenLabs Scribe, OpenAI transcription and AssemblyAI Universal-3.6 Pro (streaming speech recognition that detects the end of a turn itself; own key variables `ELEVENLABS_STT_API_KEY`, `OPENAI_STT_API_KEY`, `ASSEMBLYAI_STT_API_KEY`), OpenRouter (API key, zero data retention switch), OpenAI, Anthropic, Google Gemini, Groq and Mistral (API key; each on its OpenAI-compatible API, endpoints and default models in `llmEndpoints`, `packages/actions/src/admin.ts`, shared by the agent and the API), ElevenLabs and Cartesia (API key), OpenAI Realtime (API key; its key falls back to `OPENAI_API_KEY`), for email SMTP (URL, from; a preset for Amazon SES) and mail services with a key or app password: Resend, Postmark, SendGrid, Brevo, Mailgun and Gmail (address and app password); `apps/api/src/email-services.ts` turns the one that sends (picked, `EMAIL_PROVIDER`, else the first set up; plain SMTP first) into `SMTP_URL` and `EMAIL_FROM` at start: an SMTP URL on 587 for every service but Resend, which sends and is tested through its HTTPS API (`https://resend:<key>@api.resend.com`, `apps/api/src/email-resend.ts`; port 443, open on hosts that block outgoing SMTP such as DigitalOcean), for sign-in and calendar Google, Microsoft (with tenant), GitHub and OIDC (discovery URL, client, button label, trusted email domains), and for recording storage Local disk (`file`, no fields) and S3-compatible (`s3`, see below), and for billing Stripe (`stripe`: secret or restricted key and webhook signing secret, both secret; Linedesk Cloud only). Each field falls back to the variable the voice agent reads (`apps/agent/src/config.ts`): `DEEPGRAM_API_KEY`, `S3_ENDPOINT` and so on. The speech, language, voice and realtime providers hold only their key (decision of 2026-11-18): the call's models come from its call quality level (Server admin › Settings › Calls › Call quality, `CALL_QUALITY_DEFAULTS`), the after-call summary's from `SUMMARY_MODEL_DEFAULTS` (both in `packages/actions/src/usage-level.ts`), the voice from each assistant (else the provider's default voice); "Hear the voice" speaks with the default voice model of the level new assistants start on. The database stores provider id and field name as text (`provider_settings`, one row per field), so a new provider is an entry in the registry and no migration. `workspace_id` is null: the keys are for the whole install. Rows with a workspace id are a workspace's own carrier credentials (§8, Own carrier account); they never count for the install, the admin area does not list them, and only `apps/api/src/workspace-carrier.ts` reads them.+**Providers.** The registry in `packages/actions/src/admin.ts` describes each provider: label, category (telephony, speech to text, language model, voice, realtime model, email, sign-in and calendar, recording storage), its fields and which are secret or optional; `apps/api/src/provider-test.ts` holds how to test its connection. Shipped: Telnyx (API key, webhook public key; the default carrier), Twilio (account SID, auth token), Deepgram (API key), ElevenLabs Scribe, OpenAI transcription and AssemblyAI Universal-3.6 Pro (streaming speech recognition that detects the end of a turn itself; own key variables `ELEVENLABS_STT_API_KEY`, `OPENAI_STT_API_KEY`, `ASSEMBLYAI_STT_API_KEY`), OpenRouter (API key, zero data retention switch), OpenAI, Anthropic, Google Gemini, Groq and Mistral (API key; each on its OpenAI-compatible API, endpoints and default models in `llmEndpoints`, `packages/actions/src/admin.ts`, shared by the agent and the API), ElevenLabs and Cartesia (API key), OpenAI Realtime (API key; its key falls back to `OPENAI_API_KEY`), for email SMTP (URL, from; a preset for Amazon SES) and mail services with a key or app password: Resend, Postmark, SendGrid, Brevo, Mailgun and Gmail (address and app password); `apps/api/src/email-services.ts` turns the one that sends (picked, `EMAIL_PROVIDER`, else the first set up; plain SMTP first) into `SMTP_URL` and `EMAIL_FROM` at start: an SMTP URL on 587 for every service but Resend, which sends and is tested through its HTTPS API (`https://resend:<key>@api.resend.com`, `apps/api/src/email-resend.ts`; port 443, open on hosts that block outgoing SMTP such as DigitalOcean), for sign-in and calendar Google, Apple (Services ID, team ID, key ID, the .p8 key, the iOS app's bundle ID), Microsoft (with tenant), GitHub and OIDC (discovery URL, client, button label, trusted email domains), and for recording storage Local disk (`file`, no fields) and S3-compatible (`s3`, see below), and for billing Stripe (`stripe`: secret or restricted key and webhook signing secret, both secret; Linedesk Cloud only). Each field falls back to the variable the voice agent reads (`apps/agent/src/config.ts`): `DEEPGRAM_API_KEY`, `S3_ENDPOINT` and so on. The speech, language, voice and realtime providers hold only their key (decision of 2026-11-18): the call's models come from its call quality level (Server admin › Settings › Calls › Call quality, `CALL_QUALITY_DEFAULTS`), the after-call summary's from `SUMMARY_MODEL_DEFAULTS` (both in `packages/actions/src/usage-level.ts`), the voice from each assistant (else the provider's default voice); "Hear the voice" speaks with the default voice model of the level new assistants start on. The database stores provider id and field name as text (`provider_settings`, one row per field), so a new provider is an entry in the registry and no migration. `workspace_id` is null: the keys are for the whole install. Rows with a workspace id are a workspace's own carrier credentials (§8, Own carrier account); they never count for the install, the admin area does not list them, and only `apps/api/src/workspace-carrier.ts` reads them.**What stays in env.** Only what the install needs before it can read its database: the secrets its containers share (`POSTGRES_PASSWORD`, `ELECTRIC_SECRET`, `BETTER_AUTH_SECRET`, `SECRETS_KEY`, `AGENT_API_TOKEN`, LiveKit's key and secret, which LiveKit, SIP and egress read from their own config), addresses (`PUBLIC_URL`) and limits. `scripts/setup.sh` writes them with random values, so a new install needs no hand-made `.env`. Every provider field keeps its variable as a fallback for scripted installs; `apps/api/src/providers-import.ts` moves set variables into the app.@@ -458,7 +458,7 @@ REST routes outside the registry: `/v1/admin/*` need `instance:admin`; `/v1/shap**System prompt.** Server admin › System prompt shows the assistant's whole system prompt in the order `buildInstructions()` (`apps/agent/src/prompt.ts`) builds it, for every workspace of the install. Its fixed parts and their defaults are one table, `PROMPT_TEXTS` in `packages/actions/src/prompt-texts.ts` (a stable key, the section, the condition it is used under, the text with `{variables}`); the agent and the page both read it, so the text is never copied into the UI. Each part's fixed text is editable in place; the variables are chips that cannot change, and an edit must keep the default's variables in the same order (`overrideFits`). `systemPrompt.get` / `.setPart` / `.resetPart` (`instance:admin`, in the command log and the audit log) store an edit as a row of `prompt_overrides` (key, text, the default it was made against, who and when; migration 0116); setting the default text deletes the row. `call.start` hands the edits to the voice agent, which uses an edit only while it fits and the default for every other part; an edit is the admin's own instruction, not caller data, so it is not fenced (control characters are taken out). When a release changes a part's default, the page says "Default changed since your edit" (the stored default differs); when it changes the variables, the edit no longer fits, the default is used and the page says so. A blocked call gets no edits. The snapshot test `apps/agent/src/prompt.snapshot.test.ts` keeps the prompt without edits byte for byte.-**Sign-in providers and account linking.** Google, Microsoft, GitHub and one OpenID Connect provider, each on when its keys are set (`apps/api/src/auth-methods.ts`; `GET /v1/auth-methods` lists them for the sign-in page). The email address is the account: a provider sign-in lands in the account with the same email, however that account was made (email code, password, an invitation or `user.invite` that never signed in, another provider), and every method attaches to that one account. Condition: the provider proves the address (`apps/api/src/account-linking.ts`). Google: `email_verified`. Microsoft: a personal account (tenant `9188040d-6c67-4c5b-b112-36a304b66dad`: Outlook.com, Hotmail, Live), or a work account whose ID token carries `xms_edov` (the tenant owns the email's domain; an optional claim the app registration must add) or lists the address in `verified_primary_email`; a work account's plain `email` claim is not proof, any tenant can set it. GitHub (`apps/api/src/github-sign-in.ts`, scopes `read:user` and `user:email`): the account's primary address from `GET /user/emails`, only when GitHub verified it; the public profile address and other addresses are never used. OIDC: `email_verified`, or, opted in with `OIDC_TRUST_EMAIL_DOMAINS` (only when the provider sends no such claim), an address on exactly one of the listed domains the provider owns. A sign-in that does not prove its address has no email: Better Auth stops with `email_not_found` before it looks up or creates a user, and the sign-in page says the provider didn't confirm the address. No provider is trusted by name (`trustedProviders` is empty) and `requireLocalEmailVerified` is off, so a proven provider email also joins an account whose own address was never verified; Better Auth then marks it verified, and an `account.create` hook removes what got in without proof (`dropUnprovenAccessOf`: other sign-in accounts, passkeys, sessions, API keys, webhooks, pending invitations, calendar connections) (otherwise someone who signed up with another person's address and a password would keep a way in). A first email-code sign-in that proves an unverified address does the same (`dropUnprovenAccessAfterCodeSignIn`, a `user.update` hook on `/sign-in/email-otp`). What `dropUnprovenAccessOf` removes: every other sign-in account (password, providers; the provider account being linked stays), passkeys, sessions, push subscriptions, API keys and AI agent setup links the account created (revoked), webhook endpoints and calendar connections it created and invitations it sent that are still pending, and in the workspaces it owns and created (its member row is the workspace's first; not one an instance admin or owner added it to) the assistants' warm transfer (switch and on-call number) and numbers set to forward every call go back to the defaults, recorded in the audit log per workspace as `call_routing_reset`. Workspaces it created stay, with their members. An unconfirmed address cannot add a passkey at all (403 `EMAIL_NOT_VERIFIED`). Better Auth's email link ("Confirm your email", `/send-verification-email`, `/verify-email`) is off (`disabledPaths`, auth.ts): addresses are confirmed only by an email code (typed, or the sign-in email's button, which redeems the same code) or a provider that proves them. Pending workspace invitations stay pending and can be accepted afterwards. A provider sign-in for an address with an account or a pending invitation works; any other is refused with `SIGNUP_CLOSED`. Provider accounts are keyed on the provider's stable id (Google `sub`, Microsoft `oid`, GitHub's numeric id).+**Sign-in providers and account linking.** Google, Apple, Microsoft, GitHub and one OpenID Connect provider, each on when its keys are set (`apps/api/src/auth-methods.ts`; `GET /v1/auth-methods` lists them for the sign-in page). The email address is the account: a provider sign-in lands in the account with the same email, however that account was made (email code, password, an invitation or `user.invite` that never signed in, another provider), and every method attaches to that one account. Condition: the provider proves the address (`apps/api/src/account-linking.ts`). Google: `email_verified`. Apple: `email_verified` too, also for its private relay addresses (`@privaterelay.appleid.com`, which join no existing account unless that account uses the relay address). Apple has no fixed client secret: the API signs one (ES256 JWT, 150 days) with the Sign in with Apple key and makes a new one after 30 days while it runs (`apps/api/src/apple-sign-in.ts`); Apple comes back with a cross-site form POST, which the API answers with a 303 to the same callback as a GET, so the browser sends the sign-in's state cookie and Better Auth's origin check never sees appleid.apple.com. Microsoft: a personal account (tenant `9188040d-6c67-4c5b-b112-36a304b66dad`: Outlook.com, Hotmail, Live), or a work account whose ID token carries `xms_edov` (the tenant owns the email's domain; an optional claim the app registration must add) or lists the address in `verified_primary_email`; a work account's plain `email` claim is not proof, any tenant can set it. GitHub (`apps/api/src/github-sign-in.ts`, scopes `read:user` and `user:email`): the account's primary address from `GET /user/emails`, only when GitHub verified it; the public profile address and other addresses are never used. OIDC: `email_verified`, or, opted in with `OIDC_TRUST_EMAIL_DOMAINS` (only when the provider sends no such claim), an address on exactly one of the listed domains the provider owns. A sign-in that does not prove its address has no email: Better Auth stops with `email_not_found` before it looks up or creates a user, and the sign-in page says the provider didn't confirm the address. No provider is trusted by name (`trustedProviders` is empty) and `requireLocalEmailVerified` is off, so a proven provider email also joins an account whose own address was never verified; Better Auth then marks it verified, and an `account.create` hook removes what got in without proof (`dropUnprovenAccessOf`: other sign-in accounts, passkeys, sessions, API keys, webhooks, pending invitations, calendar connections) (otherwise someone who signed up with another person's address and a password would keep a way in). A first email-code sign-in that proves an unverified address does the same (`dropUnprovenAccessAfterCodeSignIn`, a `user.update` hook on `/sign-in/email-otp`). What `dropUnprovenAccessOf` removes: every other sign-in account (password, providers; the provider account being linked stays), passkeys, sessions, push subscriptions, API keys and AI agent setup links the account created (revoked), webhook endpoints and calendar connections it created and invitations it sent that are still pending, and in the workspaces it owns and created (its member row is the workspace's first; not one an instance admin or owner added it to) the assistants' warm transfer (switch and on-call number) and numbers set to forward every call go back to the defaults, recorded in the audit log per workspace as `call_routing_reset`. Workspaces it created stay, with their members. An unconfirmed address cannot add a passkey at all (403 `EMAIL_NOT_VERIFIED`). Better Auth's email link ("Confirm your email", `/send-verification-email`, `/verify-email`) is off (`disabledPaths`, auth.ts): addresses are confirmed only by an email code (typed, or the sign-in email's button, which redeems the same code) or a provider that proves them. Pending workspace invitations stay pending and can be accepted afterwards. A provider sign-in for an address with an account or a pending invitation works; any other is refused with `SIGNUP_CLOSED`. Provider accounts are keyed on the provider's stable id (Google `sub`, Microsoft `oid`, GitHub's numeric id).**Passkeys.** Better Auth's passkey plugin (`@better-auth/passkey`, `apps/api/src/passkeys.ts`, table `passkey`), on unless `AUTH_PASSKEY_ENABLED=false`; the sign-in page offers "Continue with Passkey" when the server has it on and the browser supports WebAuthn (https or localhost). The relying party is the address people open: its host name is the `rpID` and its origin the only accepted origin, from `PUBLIC_URL`, else `WEB_ORIGIN` (with docker compose both are `PUBLIC_URL`). Changing that address makes existing passkeys unusable (people sign in another way and add a new one). A passkey signs in an existing account only: it is added under Account, Sign-in & security, by a signed-in member whose session is less than a day old (the plugin's fresh-session check), to that member's own account; there is no passkey-first sign-up (`registration.requireSession`, no `resolveUser`), so closed sign-up cannot be bypassed with one. Removing a passkey also needs a session less than a day old (a before-hook; the plugin itself only asks for a session) and works only on the member's own passkeys. Once an account has a passkey, or belongs to an instance admin, passkeys are its second factor (`guardPasskeyChanges`, a before-hook): adding, renaming or removing one then needs a session started by a passkey sign-in in the last 12 hours (`passkeyVerifiedAt`, 12 hours), else 403 `PASSKEY_CONFIRMATION_REQUIRED`, so someone with only the mailbox, the password or the Google account can neither add their own passkey nor remove the real ones. An instance admin's first passkey needs a one-time enrolment code (`apps/api/src/passkey-enrolment.ts`, else 403 `PASSKEY_ENROLMENT_REQUIRED`): `instanceAdmin.grant`, `user.invite` with admin, `user.resetPasskeys` and `user.issuePasskeyEnrolment` return it once to the admin who ran them (shown in a dialog, `secretResult`, never in the command log), and `pnpm --filter @linedesk/api user:passkeys --enrol --email …` (in Docker `docker compose exec api node apps/api/src/user-passkeys.ts --enrol --email …`) prints it for the first admin of an install, one set by `INSTANCE_ADMIN_EMAILS` or any admin without a passkey; the API's log at start has one too (above). **Only a code, nothing ends:** `user.issuePasskeyEnrolment` (Server admin › Users, "Give passkey code…"; the CLI's `--enrol`) is for an instance admin who has no passkey yet: it issues the code, emails them and alerts the admins, and removes nothing, so their sessions and AI agent setup links keep working (an agent that asks the admin to add a passkey keeps its link). The code is written in one statement only while no passkey row exists (`issueFirstPasskeyEnrolment`, also used by `instanceAdmin.grant`), so a passkey added at the same moment refuses it. It is refused when they have a passkey (that is the reset below), for a non-admin (no code needed), for a disabled account and on one's own account; it needs Server admin (the passkey check) like the reset. The email to them says who issued it and that nothing ended. Every handler that returns an enrolment code refuses an AI agent's setup key, an API key and an impersonation, also when passkey-confirmed. Only its SHA-256 is stored (`user.passkey_enrolment_hash`), it lasts 24 hours and is used up by the first passkey; the browser sends it as `x-passkey-enrolment` with `verify-registration` (asking for options only needs one to be pending), and Account shows an Enrolment code field while `/v1/me` says `passkeyEnrolment`. Non-admins without a passkey keep Better Auth's fresh-session rule. The account is emailed whenever a passkey is added or removed, and both are in the audit log. **Recovery** that needs none of the user's passkeys (a lost device, or a passkey someone else added with the first factor): an instance admin runs Reset passkeys on the user's page (`user.resetPasskeys`, audited; needs `instance:admin`, so never while impersonating): every passkey of the user is removed and all their sessions and AI agent setup links end in the same transaction, also when there was no passkey to remove (never on the admin's own account), they are emailed (an instance admin always, also with no passkey to remove), and an instance admin gets a new enrolment code. Granting instance admin to someone who already has passkeys lists them with their dates in the dialog, since they become the admin's second factor, and offers "Reset passkeys and make admin" instead. The last admin, or one without a working passkey, does the same on the server: `pnpm --filter @linedesk/api user:passkeys --remove --email …` (runs the same action as the operator; it says before and after that it signs them out and ends their setup links, with the counts). `ADMIN_SECOND_FACTOR=off` is not needed for any of this. A disabled user's passkey creates no session (the `session.create` hook). While impersonating, passkeys cannot be added, renamed, removed or listed (`impersonation-guard.ts`).diff --git a/packages/actions/src/admin.ts b/packages/actions/src/admin.tsindex a302d77c..b14bd6f0 100644--- a/packages/actions/src/admin.ts+++ b/packages/actions/src/admin.ts@@ -400,6 +400,16 @@ const guides = {],costKey: msg('admin.provider.guide.fcm.cost'),},+ apple: {+ url: 'https://developer.apple.com/account/resources/identifiers/list/serviceId',+ stepKeys: [+ msg('admin.provider.guide.apple.step1'),+ msg('admin.provider.guide.apple.step2'),+ msg('admin.provider.guide.apple.step3'),+ msg('admin.provider.guide.apple.step4'),+ ],+ costKey: msg('admin.provider.guide.apple.cost'),+ },github: {url: 'https://github.com/settings/developers',steps: [@@ -992,6 +1002,24 @@ export const providers = {},help: 'In Microsoft Entra, register an app (Web) with the redirect URIs below and the delegated permissions Calendars.ReadWrite, Mail.Read (support mailboxes), offline_access and User.Read. Work accounts sign in only with the optional ID-token claims xms_edov and email (Token configuration). Tenant: an ID limits sign-in to one organization.',},+ apple: {+ label: 'Apple',+ category: 'sign_in',+ guide: guides.apple,+ fields: {+ client_id: { labelKey: msg('admin.provider.field.servicesId'), env: 'APPLE_CLIENT_ID', secret: false },+ team_id: { labelKey: msg('admin.provider.field.teamId'), env: 'APPLE_TEAM_ID', secret: false },+ key_id: { labelKey: msg('admin.provider.field.keyId'), env: 'APPLE_KEY_ID', secret: false },+ private_key: { labelKey: msg('admin.provider.field.privateKeyP8'), env: 'APPLE_PRIVATE_KEY', secret: true },+ app_bundle_id: {+ labelKey: msg('admin.provider.field.iosBundleId'),+ env: 'APPLE_APP_BUNDLE_ID',+ secret: false,+ optional: true,+ },+ },+ helpKey: msg('admin.provider.help.apple'),+ },// Calendar apps of scheduling tools: a business connects by consent page. Without one, it pastes a key.calendly: {label: 'Calendly',diff --git a/packages/actions/src/provider-status.ts b/packages/actions/src/provider-status.tsindex c4c7c640..4e7e79f6 100644--- a/packages/actions/src/provider-status.ts+++ b/packages/actions/src/provider-status.ts@@ -48,7 +48,7 @@ export type ProviderGroupSpec = {/** The OAuth apps that connect calendars: Google's and Microsoft's also serve sign-in; Calendly's and Cal.com's only calendars. */export const CALENDAR_APPS: readonly ProviderName[] = ['google', 'microsoft', 'calendly', 'calcom']/** The apps people sign in with (the rest of the sign-in category connects calendars only). */-export const SIGN_IN_APPS: readonly ProviderName[] = ['google', 'microsoft', 'github', 'oidc']+export const SIGN_IN_APPS: readonly ProviderName[] = ['google', 'apple', 'microsoft', 'github', 'oidc']/** The three stages that answer calls when no realtime model does. */export const STAGE_CATEGORIES = ['stt', 'llm', 'tts'] as const satisfies readonly ProviderCategory[]diff --git a/packages/i18n/glossary.json b/packages/i18n/glossary.jsonindex fd5bcde0..328e672e 100644--- a/packages/i18n/glossary.json+++ b/packages/i18n/glossary.json@@ -17,6 +17,7 @@"Outlook","Excel","GitHub",+ "Apple","Deepgram","Cloudflare for SaaS","ElevenLabs",diff --git a/packages/i18n/locales/en/admin.json b/packages/i18n/locales/en/admin.jsonindex 5204bc50..734a3e15 100644--- a/packages/i18n/locales/en/admin.json+++ b/packages/i18n/locales/en/admin.json@@ -1275,6 +1275,7 @@"provider.answeredByEach": "Answered by {names}, as each assistant chose.","provider.blurb.anthropic": "Claude models.","provider.blurb.apns": "Push notifications to the iOS app.",+ "provider.blurb.apple": "Sign in with Apple.","provider.blurb.assemblyai_stt": "Streaming speech recognition with Universal-3.6 Pro.","provider.blurb.brevo": "Email with an SMTP key.","provider.blurb.calcom": "One-click connecting for Cal.com event types.",@@ -1348,9 +1349,12 @@"provider.field.cnameTarget": "CNAME target","provider.field.customOrigin": "Custom origin (empty: the fallback origin)","provider.field.fcmServiceAccount": "Service account (JSON)",+ "provider.field.iosBundleId": "iOS app bundle ID (only with an iOS app)","provider.field.iosBundleIdApp": "iOS app bundle ID","provider.field.keyId": "Key ID",+ "provider.field.privateKeyP8": "Private key (.p8)","provider.field.publicAppApproved": "Public app approved in the Shopify App Store",+ "provider.field.servicesId": "Services ID","provider.field.signingSecret": "Signing secret","provider.field.teamId": "Team ID","provider.field.waitForCaller": "Wait for callers to finish",@@ -1384,6 +1388,11 @@"provider.guide.apns.step1": "Apple Developer › Certificates, Identifiers & Profiles › Keys › New key with Apple Push Notifications service (APNs), for Sandbox & Production.","provider.guide.apns.step2": "Download the .p8 file (Apple gives it only once) and note the key ID and your team ID.","provider.guide.apns.step3": "Paste the content of the .p8 file, the key ID, the team ID and your iOS app's bundle ID here.",+ "provider.guide.apple.cost": "Free with a membership in the Apple Developer Program (99 USD a year).",+ "provider.guide.apple.step1": "Apple Developer › Certificates, Identifiers & Profiles › Identifiers: an App ID with Sign in with Apple (for an iOS app, its bundle ID).",+ "provider.guide.apple.step2": "Identifiers › Services IDs › New: this is the Services ID. Turn on Sign in with Apple and configure it with your domain and the return URL shown below.",+ "provider.guide.apple.step3": "Keys › New key with Sign in with Apple for that App ID. Download the .p8 file (Apple gives it only once) and note the key ID.",+ "provider.guide.apple.step4": "Paste the Services ID, your team ID (top right in the Apple Developer account), the key ID and the content of the .p8 file here.","provider.guide.assemblyai_stt.cost": "About $0.0075 per call minute with Universal-3.6 Pro streaming.","provider.guide.assemblyai_stt.step1": "Sign up at assemblyai.com and add a payment method.","provider.guide.assemblyai_stt.step2": "Dashboard › API Keys: copy the key.",@@ -1425,6 +1434,7 @@"provider.guide.zoho.step2": "In the client's Settings tab, turn on every data centre (Multi-DC) and tick “Use the same OAuth credentials for all data centers”, so businesses whose Zoho account is in the EU, India, Australia or another region can connect too.","provider.guide.zoho.step3": "Copy the client ID and client secret from the Client Secret tab and paste them here.","provider.help.apns": "Pushes to the iOS app. One key works for the app's development and App Store builds.",+ "provider.help.apple": "Sign in with Apple, on the web and in an iOS app. Apple proves the address, also its private relay addresses.","provider.help.assemblyai_stt": "The assistant answers when AssemblyAI says the caller is done. With Wait for callers to finish on (the default), it waits as long as Deepgram Flux does. Off, it answers about a quarter of a second sooner, but it often starts while the caller only pauses (before a house number, for example). It can’t understand Polish, Ukrainian, Czech, Greek, Hungarian or Indonesian: with Deepgram set up too, calls in these languages use Deepgram (Nova-3); without it, assistants are not offered them.","provider.help.cloudflare_saas": "Lets white-label partners give their clients an address of their own, like app.theiragency.com. Partners point their address at the CNAME target.","provider.help.fcm": "Pushes to the Android app, through Google's Firebase Cloud Messaging.",diff --git a/packages/i18n/locales/en/server.json b/packages/i18n/locales/en/server.jsonindex 1bd84818..33fd0823 100644--- a/packages/i18n/locales/en/server.json+++ b/packages/i18n/locales/en/server.json@@ -252,6 +252,7 @@"api.providerTest.apns.bundle": "Apple refused the bundle ID: it must be an app of this team with Push Notifications on.","api.providerTest.apns.key": "Apple refused the key: check the .p8 key, the key ID and the team ID (the key needs Apple Push Notifications service).","api.providerTest.apns.unreachable": "Apple's push service could not be reached.",+ "api.providerTest.apple.keyNotP8": "The private key is not a Sign in with Apple key: paste the whole content of the .p8 file Apple gave.","api.providerTest.cartesia.noVoice": "The voice {voice} is not available to this Cartesia key. Pick another or clear the field.","api.providerTest.cloudflareSaas.zoneId": "The zone ID is 32 hex digits. Copy it from the zone's Overview page in Cloudflare.","api.providerTest.connected": "Connected",