import mongoose, { Document, Schema, Types, Model } from 'mongoose'; import bcrypt from 'bcryptjs'; import crypto from 'crypto'; export type UserRole = 'user' | 'admin'; export type BotType = 'system' | 'agent' | 'bridge' | null; export type AvatarStyle = 'banana' | 'abstract' | 'minimalist' | 'cartoon' | 'geometric' | 'custom'; export type AvatarPersonality = 'friendly' | 'professional' | 'playful' | 'wise' | 'creative'; export type AvatarColorScheme = 'vibrant' | 'pastel' | 'monochrome' | 'neon'; export type AgentTone = 'friendly' | 'professional' | 'sarcastic' | 'educational' | 'humorous'; export type AgentBehavior = 'reactive' | 'proactive' | 'balanced'; export type AgentResponseStyle = 'concise' | 'detailed' | 'conversational'; export type AgentCapability = 'chat' | 'summarize' | 'curate' | 'moderate' | 'translate'; export type DigestFrequency = 'daily' | 'weekly' | 'never'; export type ActivityLevel = 'low' | 'medium' | 'high'; export interface IAgentRuntimeToken { tokenHash: string; label?: string; createdAt: Date; lastUsedAt?: Date; // Set only by a listener check-in (the events poll, the agent WebSocket // connect), never by an ordinary authenticated call such as an MCP tool. lastListenedAt?: Date; // Set only by a call from the Commonly MCP client (its User-Agent), so a // browser memory import or an attach with the same token never sets it. lastMcpSeenAt?: Date; expiresAt?: Date; } // A device-login bearer is intentionally one-way: the CLI receives it once, // while Mongo stores only this digest. It is long-lived until explicit // revocation (there is no expiresAt or transparent refresh) and is separate // from the legacy apiToken (which pre-dates per-device revocation) and agent // runtime tokens. export interface IDeviceToken { tokenHash: string; label: string; createdAt: Date; lastUsedAt?: Date; revokedAt?: Date; } export interface IFollowedThread { postId: Types.ObjectId; followedAt: Date; } // Social-login identities linked to this account. A user may have zero // (password-only), one, or several (GitHub + Google linked by verified // email). Accounts created via OAuth have no password — see the // conditional `required` on the password path below. export type AuthProviderName = 'github' | 'google'; export interface IAuthProvider { provider: AuthProviderName; providerId: string; email?: string; linkedAt: Date; } // User-level alias → agent (or human) binding. Both human and bot users // carry this list; for bots it's the agent's "contacts" — who they go to // for codex review, planning, etc. For humans it's the people they DM // most. Aliases must be lowercase URL-safe. export type ContactSource = 'user' | 'pod' | 'system'; export interface IContactEntry { alias: string; agentName?: string; instanceId?: string; targetUserId?: Types.ObjectId; role?: string; source: ContactSource; pinned?: boolean; addedAt: Date; } export interface IUser extends Document { username: string; // Previous human handles remain reserved after a rename. They are kept for // historical identity only: mention routing always uses `username`. previousUsernames: string[]; // Human-facing identity label. Usernames remain the stable, routable handle; // bots continue to own their display label under botMetadata. displayName?: string; email: string; password?: string; authProviders: IAuthProvider[]; verified: boolean; // Admin moderation (GH: admin user management). banned users cannot log in // and existing sessions are refused by the auth middleware on next request. banned: boolean; // Incrementing this invalidates every browser session without rotating JWT_SECRET. tokenVersion: number; accountDeletionRequestedAt?: Date; bannedAt?: Date; banReason?: string; profilePicture: string; role: UserRole; // Capability gate for hosted (cloud) agents. Defaults to false so opening // registration doesn't hand every new signup free Commonly-managed compute. // Admins are implicitly allowed (the gate checks role === 'admin' OR this // flag). BYO / self-hosted agents are never gated by this field — see // agentIdentityService.isCloudRuntime + routes/registry/{install,provision}. entitlements: { cloudAgents: boolean; // Paid tier. Gates capabilities that cost us money or expose the instance // to the public — today: listing a pod to Community, and unlimited message // history (free accounts keep the 30-day pgRetentionService window). // BYO agents are NEVER gated by this: "agents you bring connect free and // unlimited" is the product's standing promise, and a per-agent cap is the // thing this pricing model exists to avoid. // NEVER set from a client response. Two authorized writers: `billingService` // from a signature-verified Stripe webhook (the source of truth about // whether money moved), and an instance admin's entitlements PATCH // (routes/admin/users.ts) for pilots and design partners. pro: boolean; }; // Stripe linkage. `customerId` is the join key from webhook -> user; it is // set at checkout creation so an event can always be resolved even if the // session metadata is missing. `subscriptionStatus` mirrors Stripe rather // than being derived, so support can see WHY someone lost access. billing?: { customerId?: string; subscriptionId?: string; subscriptionStatus?: string; currentPeriodEnd?: Date; cancelAtPeriodEnd?: boolean; // When Pro last ended. Features stop at once; the retention cron keeps // this account's history for PRO_DATA_GRACE_DAYS past this instant, so a // failed card payment does not destroy history overnight. proEndedAt?: Date; }; apiToken?: string; apiTokenHash?: string; apiTokenLast4?: string; apiTokenCreatedAt?: Date; apiTokenScopes: string[]; isBot: boolean; botType: BotType; botMetadata: { displayName?: string; description?: string; runtimeId?: string; officialAgent?: boolean; capabilities?: string[]; agentName?: string; instanceId?: string; // Durable owner of a self-serve identity; uninstall keeps this User row. ownerUserId?: string; // ADR-026 D3: the machine this identity is bound to (adoption CAS). machineId?: string | null; // Set once by a foreground run with no sandbox; only ever adds a grant refusal. hostUnconfined?: boolean; // ADR-026 Phase 2: an owner's pending "run this on machine X" ask. The // daemon on X sees it in its work list and performs the adopt CAS; it is // a directive, never a binding — the CAS remains the only binding writer. requestedMachineId?: string | null; // Owner-approved request for the bound daemon to rotate the agent key. reconnectRequestedAt?: Date | null; runtime?: string; icon?: string; }; avatarMetadata: { style?: AvatarStyle; personality?: AvatarPersonality; colorScheme?: AvatarColorScheme; generatedAt?: Date; prompt?: string; source?: 'openai' | 'gemini' | 'svg' | 'manual'; model?: string; }; agentConfig: { personality: { tone: AgentTone; interests: string[]; behavior: AgentBehavior; responseStyle: AgentResponseStyle; }; systemPrompt: string; capabilities: AgentCapability[]; }; agentRuntimeTokens: IAgentRuntimeToken[]; deviceTokens: IDeviceToken[]; contacts: IContactEntry[]; subscribedPods: Types.ObjectId[]; followers: Types.ObjectId[]; following: Types.ObjectId[]; followedThreads: IFollowedThread[]; activityFeed: { lastViewedAt: Date; readItemIds: string[]; }; digestPreferences: { enabled: boolean; frequency: DigestFrequency; deliveryTime: string; includeQuotes: boolean; includeInsights: boolean; includeTimeline: boolean; minActivityLevel: ActivityLevel; }; emailPreferences: { dailyDigest: boolean; needsYou: boolean; }; digestUnsubscribeToken?: string; lastActive: Date; lastDigestSent?: Date; // IANA zone the browser reported, set once (routes/users.ts POST // /me/timezone); the daily digest goes out at 08:00 there. timezone?: string; /** * First-session milestones: write-once timestamps, set at most once per * person and never overwritten (services/onboardingMarks.ts). */ onboarding?: { /** First time this person's email link turned verified from false to true. */ verifiedAt?: Date; podOpenedAt?: Date; firstStartId?: string; firstStartAt?: Date; byoOpenedAt?: Date; /** OS the page detected on that first open, written with byoOpenedAt. */ byoOpenedOs?: 'mac' | 'linux' | 'windows' | 'other'; /** First BYO setup command copied in the browser, never overwritten. */ byoCommandCopiedAt?: Date; /** Fixed kind only; command contents and tokens are never stored. */ byoCommandType?: 'mcp' | 'cli'; /** First copy of each setup command, kept per kind (TASK-721). */ byoMcpCopiedAt?: Date; byoCliCopiedAt?: Date; /** First copy of each command type, each its own write-once mark (TASK-714). */ byoListenCopiedAt?: Date; byoMcpClaudeCopiedAt?: Date; byoMcpCursorCopiedAt?: Date; byoDaemonCopiedAt?: Date; byoTokenCopiedAt?: Date; /** The OS the result page set up for, and whether the listener could run there. */ byoSetupOs?: 'mac' | 'linux' | 'windows' | 'other'; byoListenerEligible?: boolean; /** First authenticated BYO runtime request, never overwritten. */ byoFirstConnectionAttemptAt?: Date; /** First successful `commonly daemon register`, never overwritten (TASK-661). */ byoDaemonRegisteredAt?: Date; /** First "invite a teammate" card mounted, and first dismissed. */ inviteCardShownAt?: Date; inviteCardDismissedAt?: Date; /** First Bring your own start mounted in a thread. */ byoOfferShownAt?: Date; /** First render of Scout's welcome, with a start open, in a pod they created. */ welcomeShownAt?: Date; /** First click on the welcome's "Run an agent here" to reach the server (F394). */ welcomeHostedClickAt?: Date; /** Fixed code for why the first refused click did not start (F394). */ welcomeHostedRefusal?: string; // The first-touch ref code the signup arrived with (?ref=x), set once at // account creation (utils/signupRef.ts). signupRef?: string; }; createdAt: Date; /** Browser-reported first touch, persisted only for a new human account. */ signupSource?: { ref?: string; referrer?: string; landingPath?: string; firstSeenAt?: Date; authMethod: 'password' | 'google' | 'github'; recordedAt: Date; }; // Instance methods comparePassword(password: string): Promise; generateApiToken(): string; revokeApiToken(): void; getOrCreateDigestUnsubscribeToken(): string; } export interface IUserModel extends Model { mintApiTokenIfAbsent( userId: unknown, extra?: { apiTokenScopes?: string[] }, ): Promise<{ token: string; createdAt: Date } | null>; } const userSchema = new Schema({ // Growth opts in with .select('+signupSource'); incidental profile/populate // reads must not disclose referral paths. Every field is write-once too. signupSource: { type: new Schema({ ref: { type: String, immutable: true }, referrer: { type: String, immutable: true }, landingPath: { type: String, immutable: true }, firstSeenAt: { type: Date, immutable: true }, authMethod: { type: String, enum: ['password', 'google', 'github'], required: true, immutable: true }, recordedAt: { type: Date, required: true, immutable: true }, }, { _id: false }), immutable: true, select: false, }, username: { type: String, required: true, unique: true }, previousUsernames: { type: [String], default: [] }, displayName: { type: String, trim: true }, email: { type: String, required: true, unique: true }, // Password is only required for accounts with no linked OAuth identity — // OAuth-created accounts authenticate via provider and have no password. password: { type: String, required: function (this: IUser) { return !(Array.isArray(this.authProviders) && this.authProviders.length > 0); }, }, authProviders: { type: [ new Schema({ provider: { type: String, enum: ['github', 'google'], required: true }, providerId: { type: String, required: true }, email: { type: String }, linkedAt: { type: Date, default: Date.now }, }, { _id: false }), ], default: [], }, verified: { type: Boolean, default: false }, banned: { type: Boolean, default: false }, tokenVersion: { type: Number, default: 0 }, accountDeletionRequestedAt: { type: Date }, bannedAt: { type: Date }, banReason: { type: String }, profilePicture: { type: String, default: 'default' }, role: { type: String, enum: ['user', 'admin'], default: 'user' }, // Hosted-agent entitlement gate (see IUser.entitlements). Default false; // admins bypass it. Nested object so future entitlements slot in here. entitlements: { cloudAgents: { type: Boolean, default: false }, pro: { type: Boolean, default: false }, }, billing: { // Indexed: every webhook resolves a user by this in the hot path. customerId: { type: String, index: true, sparse: true }, subscriptionId: { type: String }, subscriptionStatus: { type: String }, currentPeriodEnd: { type: Date }, cancelAtPeriodEnd: { type: Boolean, default: false }, // Indexed: the nightly retention run queries lapsed-but-in-grace accounts. proEndedAt: { type: Date, index: true, sparse: true }, }, // All credential material is hidden from incidental profile reads. apiToken // is the retired plaintext form (TASK-558) and never authenticates. It stays // declared so a leftover on an install that skipped the backfill remains // hidden and is still cleared by rotate, revoke and account deletion. apiToken: { type: String, unique: true, sparse: true, select: false, }, apiTokenHash: { type: String, select: false }, apiTokenLast4: { type: String, select: false }, apiTokenCreatedAt: { type: Date }, apiTokenScopes: [{ type: String }], isBot: { type: Boolean, default: false }, botType: { type: String, enum: ['system', 'agent', 'bridge', null], default: null, }, botMetadata: { displayName: { type: String }, description: { type: String }, runtimeId: { type: String }, officialAgent: { type: Boolean, default: false }, capabilities: [{ type: String }], agentName: { type: String }, instanceId: { type: String }, ownerUserId: { type: String }, // ADR-026 D3 — declared or Mongoose strips it (the #1282 lesson). machineId: { type: String, default: null }, hostUnconfined: { type: Boolean }, // ADR-026 Phase 2 — same lesson: declared or stripped. requestedMachineId: { type: String, default: null }, reconnectRequestedAt: { type: Date, default: null }, }, avatarMetadata: { style: { type: String, enum: ['banana', 'abstract', 'minimalist', 'cartoon', 'geometric', 'custom'], }, personality: { type: String, enum: ['friendly', 'professional', 'playful', 'wise', 'creative'], }, colorScheme: { type: String, enum: ['vibrant', 'pastel', 'monochrome', 'neon'], }, generatedAt: { type: Date }, prompt: { type: String }, source: { type: String, enum: ['openai', 'gemini', 'svg', 'manual'], }, model: { type: String }, }, agentConfig: { personality: { tone: { type: String, enum: ['friendly', 'professional', 'sarcastic', 'educational', 'humorous'], default: 'friendly', }, interests: [{ type: String, trim: true }], behavior: { type: String, enum: ['reactive', 'proactive', 'balanced'], default: 'reactive', }, responseStyle: { type: String, enum: ['concise', 'detailed', 'conversational'], default: 'conversational', }, }, systemPrompt: { type: String, default: 'You are a helpful AI assistant.', }, capabilities: [{ type: String, enum: ['chat', 'summarize', 'curate', 'moderate', 'translate'], }], }, agentRuntimeTokens: [ { tokenHash: { type: String, required: true }, label: { type: String }, createdAt: { type: Date, default: Date.now }, lastUsedAt: { type: Date }, lastListenedAt: { type: Date }, lastMcpSeenAt: { type: Date }, expiresAt: { type: Date }, }, ], // D1 device-code login. Do not mark this select:false: auth middleware must // inspect the digest, and response serializers explicitly omit the whole // array so these records never become an account-profile API surface. deviceTokens: { type: [ new Schema({ tokenHash: { type: String, required: true }, label: { type: String, required: true }, createdAt: { type: Date, default: Date.now }, lastUsedAt: { type: Date }, revokedAt: { type: Date }, }, { _id: true }), ], default: [], }, // Alias-driven contact list — see IContactEntry above. Default empty so // existing user rows return `[]` on read (never throws on `.find(...)`). contacts: { type: [ new Schema({ alias: { type: String, required: true, lowercase: true, trim: true }, agentName: { type: String, default: null }, instanceId: { type: String, default: null }, targetUserId: { type: Schema.Types.ObjectId, ref: 'User', default: null }, role: { type: String, default: null }, source: { type: String, enum: ['user', 'pod', 'system'], default: 'user' }, pinned: { type: Boolean, default: false }, addedAt: { type: Date, default: Date.now }, }, { _id: false }), ], default: [], }, subscribedPods: [{ type: Schema.Types.ObjectId, ref: 'Pod' }], followers: [{ type: Schema.Types.ObjectId, ref: 'User' }], following: [{ type: Schema.Types.ObjectId, ref: 'User' }], followedThreads: [ { postId: { type: Schema.Types.ObjectId, ref: 'Post', required: true }, followedAt: { type: Date, default: Date.now }, }, ], activityFeed: { lastViewedAt: { type: Date, default: new Date(0) }, readItemIds: { type: [String], default: [] }, }, digestPreferences: { enabled: { type: Boolean, default: true }, frequency: { type: String, enum: ['daily', 'weekly', 'never'], default: 'daily' }, deliveryTime: { type: String, default: '06:00' }, includeQuotes: { type: Boolean, default: true }, includeInsights: { type: Boolean, default: true }, includeTimeline: { type: Boolean, default: true }, minActivityLevel: { type: String, enum: ['low', 'medium', 'high'], default: 'low' }, }, emailPreferences: { dailyDigest: { type: Boolean, default: true }, needsYou: { type: Boolean, default: true }, }, // Capability token: it can only disable digest mail. Hidden from normal // User projections and generated lazily when the first email is sent. digestUnsubscribeToken: { type: String, select: false }, lastActive: { type: Date, default: Date.now }, onboarding: { verifiedAt: { type: Date }, podOpenedAt: { type: Date }, firstStartId: { type: String }, firstStartAt: { type: Date }, byoOpenedAt: { type: Date }, byoOpenedOs: { type: String, enum: ['mac', 'linux', 'windows', 'other'] }, byoCommandCopiedAt: { type: Date }, byoCommandType: { type: String, enum: ['mcp', 'cli'] }, byoMcpCopiedAt: { type: Date }, byoCliCopiedAt: { type: Date }, byoListenCopiedAt: { type: Date }, byoMcpClaudeCopiedAt: { type: Date }, byoMcpCursorCopiedAt: { type: Date }, byoDaemonCopiedAt: { type: Date }, byoTokenCopiedAt: { type: Date }, byoSetupOs: { type: String, enum: ['mac', 'linux', 'windows', 'other'] }, byoListenerEligible: { type: Boolean }, byoFirstConnectionAttemptAt: { type: Date }, byoDaemonRegisteredAt: { type: Date }, inviteCardShownAt: { type: Date }, inviteCardDismissedAt: { type: Date }, byoOfferShownAt: { type: Date }, welcomeShownAt: { type: Date }, welcomeHostedClickAt: { type: Date }, welcomeHostedRefusal: { type: String }, signupRef: { type: String }, }, lastDigestSent: { type: Date }, timezone: { type: String }, createdAt: { type: Date, default: Date.now }, }); // OAuth callback looks users up by (provider, providerId) on every social login. userSchema.index({ 'authProviders.provider': 1, 'authProviders.providerId': 1 }); // Settings lets humans choose a display label, while chat renders one label // per author. These collation indexes back the self-excluding collision check // in userController without making the labels themselves globally unique. const accountLabelCollation = { locale: 'en', strength: 2 }; // Named because the path's own unique index takes the default username_1, and // Mongo refuses a second index of that name. autoIndex hides the refusal. userSchema.index({ username: 1 }, { collation: accountLabelCollation, name: 'username_label' }); userSchema.index({ previousUsernames: 1 }, { collation: accountLabelCollation }); userSchema.index({ displayName: 1 }, { collation: accountLabelCollation }); userSchema.index({ 'botMetadata.displayName': 1 }, { collation: accountLabelCollation }); // A single index supports authentication by digest and the account's device // list. Existing users simply have no array entries, so this is additive. userSchema.index({ 'deviceTokens.tokenHash': 1 }); userSchema.index( { digestUnsubscribeToken: 1 }, { unique: true, partialFilterExpression: { digestUnsubscribeToken: { $type: 'string' } }, }, ); userSchema.pre('save', async function (next) { if (!this.isModified('password') || !this.password) return next(); if (!this.isNew) this.tokenVersion = (this.tokenVersion || 0) + 1; this.password = await bcrypt.hash(this.password, 10); next(); }); userSchema.methods.comparePassword = async function (password: string): Promise { if (!this.password) return false; // OAuth-only account — no password to compare return bcrypt.compare(password, this.password); }; userSchema.index({ apiTokenHash: 1 }, { unique: true, partialFilterExpression: { apiTokenHash: { $type: 'string' } } }); // One token shape for every mint: the bearer, and the fields stored for it. const freshApiToken = () => { const token = `cm_${crypto.randomBytes(32).toString('hex')}`; return { token, fields: { apiTokenHash: crypto.createHash('sha256').update(token).digest('hex'), apiTokenLast4: token.slice(-4), apiTokenCreatedAt: new Date(), }, }; }; userSchema.methods.generateApiToken = function (): string { const { token, fields } = freshApiToken(); this.apiTokenHash = fields.apiTokenHash; this.apiTokenLast4 = fields.apiTokenLast4; // The retired plaintext field is no longer selected, and assigning undefined // to an unselected path is not saved once the document has been saved before. // Marking it forces the $unset, so a leftover never survives a rotation. this.apiToken = undefined; this.markModified('apiToken'); this.apiTokenCreatedAt = fields.apiTokenCreatedAt; return token; }; // Mint only when the row holds no token, digest or retired plaintext, in one // conditional write. Two concurrent non-forced mints used to both pass a read // check and both save, the later replacing the earlier bearer (F61); here one // write wins and the other gets null and keeps what is stored. A rotation is // generateApiToken + save, which replaces on purpose. Callers pass the _id of // an agent row they have already resolved and authorized; this checks only // that the row holds no token. userSchema.statics.mintApiTokenIfAbsent = async function ( userId: unknown, extra: { apiTokenScopes?: string[] } = {}, ): Promise<{ token: string; createdAt: Date } | null> { const { token, fields } = freshApiToken(); const result = await this.updateOne( { _id: userId, apiTokenHash: { $not: { $type: 'string' } }, apiToken: { $not: { $type: 'string' } } }, { $set: { ...extra, ...fields }, $unset: { apiToken: 1 } }, ); return result.modifiedCount === 1 ? { token, createdAt: fields.apiTokenCreatedAt } : null; }; userSchema.methods.revokeApiToken = function (): void { // Each credential field is select:false, so mark every one (see above): a // document loaded without the digest and saved once would otherwise keep it, // and the revoked token would still authenticate. for (const path of ['apiToken', 'apiTokenHash', 'apiTokenLast4']) { this.set(path, undefined); this.markModified(path); } this.apiTokenCreatedAt = undefined; }; userSchema.methods.getOrCreateDigestUnsubscribeToken = function (): string { if (!this.digestUnsubscribeToken) { this.digestUnsubscribeToken = crypto.randomBytes(24).toString('hex'); } return this.digestUnsubscribeToken; }; // Recovery scans only authorized deletion markers, ordered for bounded retries. userSchema.index({ accountDeletionRequestedAt: 1, _id: 1 }, { partialFilterExpression: { accountDeletionRequestedAt: { $exists: true } }, }); export default mongoose.model('User', userSchema); // CJS compat: let require() return the default export directly // eslint-disable-next-line @typescript-eslint/no-require-imports module.exports = exports["default"]; Object.assign(module.exports, exports);