Something went wrong. Try again.
Mirror — see github.com/blacksky-algorithms/blacksky.community
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240import {TID} from '@atproto/common-web'import {type Client} from '@atproto/lex'import {PasswordSession} from '@atproto/lex-password-session'import {toDatetimeString} from '@atproto/syntax'import {overwriteSavedFeeds, setPersonalDetails} from '@bsky/sdk'
import {upsertProfile} from '#/lib/api/upsert-profile'import {networkRetry} from '#/lib/async/retry'import {DEFAULT_BRAND_CONFIG} from '#/lib/community/BrandContext'import {IS_PROD_SERVICE} from '#/lib/constants'import {prioritizeForYouForBlackskyPds} from '#/lib/default-feeds'import {getAge} from '#/lib/strings/time'import {logger} from '#/logger'import {snoozeBirthdateUpdateAllowedForDid} from '#/state/birthdate'import {snoozeEmailConfirmationPrompt} from '#/state/shell/reminders'import {features} from '#/analytics'import {app, chat, com} from '#/lexicons'import {verifyAndRepairAccountIndexing} from './account-indexing'import {configureModerationForAccount} from './moderation'import { buildBundle, finishPreparation, liveSessionData, makeSessionHooks, type OnSessionChange, type PasswordSessionBundle, registerBundleKillSwitch,} from './session-core'import {sessionDataToSessionAccount} from './session-data'import {type SessionAccount} from './types'
/** Create an account, prepare its session, and start post-signup writes. */export async function createSessionBundleAndCreateAccount( { service, email, password, handle, birthDate, inviteCode, verificationPhone, verificationCode, }: { service: string email: string password: string handle: string birthDate: Date inviteCode?: string verificationPhone?: string verificationCode?: string }, onSessionChange: OnSessionChange,): Promise<{account: SessionAccount; bundle: PasswordSessionBundle}> { let bundle!: PasswordSessionBundle let accountDid = '' const hooks = makeSessionHooks({ onSessionChange, getBundle: () => bundle, getDid: () => accountDid, })
const session = await PasswordSession.createAccount( { email, password, /* the lexicon types handle as `${string}.${string}`; user input is a plain string */ handle: handle as `${string}.${string}`, inviteCode, verificationPhone, verificationCode, }, {...hooks, service}, )
bundle = buildBundle(session) registerBundleKillSwitch(bundle, hooks.kill) // Seed the hook and the deferred writes with refresh-stable account fields. const earlyAccount = snapshotNewAccount(session, email) accountDid = earlyAccount.did
const gates = features.refresh({strategy: 'prefer-fresh-gates'}) configureModerationForAccount(bundle, earlyAccount)
const createdAt = toDatetimeString(new Date())
snoozeBirthdateUpdateAllowedForDid(earlyAccount.did) // Post-signup writes all target the account's own repo and actor store. const pdsClient = bundle.pdsClient
const isProd = Boolean(IS_PROD_SERVICE(service)) const postSignupTasks: Promise<unknown>[] = [ savePersonalDetails(pdsClient, birthDate), initializeProfile(pdsClient, {handle, createdAt, isProd}), ] if (isProd) { postSignupTasks.push(initializeSavedFeeds(pdsClient, service)) if (getAge(birthDate) < 18) { postSignupTasks.push(restrictIncomingChat(pdsClient, earlyAccount.did)) } } // Post-signup writes are not required to enter onboarding. void reportPostSignupFailures(postSignupTasks)
try { // snooze first prompt after signup, defer to next prompt snoozeEmailConfirmationPrompt() } catch (e) { logger.error(e instanceof Error ? e : String(e), { message: `session: failed snoozeEmailConfirmationPrompt`, }) }
/* * The appview occasionally misses the new-account event and never indexes * the account. This re-emits the identity event if the profile never shows * up. Not awaited: it must not block onboarding. */ void verifyAndRepairAccountIndexing({ getProfile: () => bundle.appviewClient.call(app.bsky.actor.getProfile, { actor: earlyAccount.did, }), getHandle: () => liveSessionData(bundle)?.handle, updateHandle: handle => bundle.pdsClient.call(com.atproto.identity.updateHandle, { handle: handle as `${string}.${string}`, }), })
// Preparation may auto-refresh the session while hooks are still disarmed. const account = await finishPreparation(bundle, gates, () => snapshotNewAccount(session, email), ) hooks.arm() return {account, bundle}}
/** * Snapshot a just-created session as a `SessionAccount`. * * `com.atproto.server.createAccount` returns only tokens, handle, did and * didDoc, so the session carries no email state or `active` flag until the * first refresh. Synthesize those fields from the creation input so the * persisted account does not briefly claim the email is unknown. */function snapshotNewAccount( session: PasswordSession, email: string,): SessionAccount { const account = sessionDataToSessionAccount( session.session, session.session.service, ) if (!account) { throw Error('Expected an active session') } return { ...account, email: account.email ?? email, emailConfirmed: account.emailConfirmed ?? false, emailAuthFactor: account.emailAuthFactor ?? false, active: account.active ?? true, }}
function savePersonalDetails(client: Client, birthDate: Date) { return retryPostSignupTask('set birthDate', 3, () => client.call(setPersonalDetails, {birthDate}), )}
function initializeProfile( client: Client, { handle, createdAt, isProd, }: { handle: string createdAt: ReturnType<typeof toDatetimeString> isProd: boolean },) { return retryPostSignupTask('set initial profile', 3, () => client.call(upsertProfile, prev => { const next: Partial<app.bsky.actor.profile.Main> = prev || {} if (isProd) { next.displayName = handle next.createdAt = createdAt } else { next.createdAt = prev?.createdAt || toDatetimeString(new Date()) } return next }), )}
function initializeSavedFeeds(client: Client, service: string) { return retryPostSignupTask('set initial feeds', 1, () => client.call( overwriteSavedFeeds, prioritizeForYouForBlackskyPds( DEFAULT_BRAND_CONFIG.feeds.defaultPinned, service, ).map(feed => ({...feed, id: TID.nextStr()})), ), )}
function restrictIncomingChat(client: Client, did: string) { return retryPostSignupTask('set chat declaration', 3, () => client.put( chat.bsky.actor.declaration, {allowIncoming: 'none'}, {repo: did as `did:${string}:${string}`, rkey: 'self'}, ), )}
function retryPostSignupTask<T>( description: string, retries: number, task: () => Promise<T>,) { return networkRetry(retries, task).catch(e => { logger.info(`createSessionBundleAndCreateAccount: failed to ${description}`) throw e })}
async function reportPostSignupFailures(tasks: Promise<unknown>[]) { const results = await Promise.allSettled(tasks) if (results.some(result => result.status === 'rejected')) { logger.error( `session: createSessionBundleAndCreateAccount failed to save post-signup settings`, ) }}