Skip to content
319 linesCodeBlameRaw
1/**
2 * A person's email addresses and the security of their account, on the
3 * identity service. Mirrors `crates/contracts/src/accounts.rs`.
4 */
5import type { AccountDeletion, DeletedAccount } from "./account-deletion";
6import type { ServiceBinding } from "./clients";
7import type { User } from "./identity";
8import type { Result } from "./result";
9
10/** The most addresses one account may have, confirmed or not. */
11export const MAX_EMAILS = 10;
12/** How long after signing in sensitive changes need no password, in seconds. */
13export const RECENT_AUTH_SECONDS = 10 * 60;
14/** The domain of each person's private commit address. */
15export const NOREPLY_DOMAIN = "users.noreply.g1t.sh";
16/** How many digits the code in a confirmation email has. */
17export const CONFIRM_CODE_DIGITS = 6;
18/** How long a confirmation email's code and link work, in seconds. */
19export const CONFIRM_TTL_SECONDS = 60 * 60;
20
21/**
22 * A confirmation code as typed or pasted, with spaces and hyphens taken
23 * out; null unless that leaves exactly six digits.
24 */
25export function tidyConfirmCode(code: string): string | null {
26 const digits = code.replace(/[\s-]/g, "");
27 return /^\d{6}$/.test(digits) ? digits : null;
28}
29
30/** What confirming an address did: by its link (`verifyEmail`) or its code (`confirmEmailCode`). */
31export type EmailConfirmed = {
32 username: string;
33 /** The address confirmed, as typed when it was added. */
34 email: string;
35 /** Whether the account is confirmed now: whether its primary is. */
36 verified: boolean;
37 /** The workspace the account's invite joined it to, by slug. */
38 joined?: string | null;
39 /** Why the invite the account signed up with no longer applies; the address is confirmed all the same. */
40 inviteLapsed?: string | null;
41};
42
43/**
44 * Proof that the person making a sensitive change is the account's owner:
45 * the session they signed in to within `RECENT_AUTH_SECONDS`, or their
46 * password. Without it the answer is `reauth_required`.
47 */
48export type Reauth = { sessionToken?: string | null; password?: string | null; client?: string | null };
49
50/** One of a person's addresses. */
51export type AccountEmail = {
52 /** As typed when it was added. */
53 email: string;
54 verified: boolean;
55 primary: boolean;
56 /** Gets security notices as well as the primary. */
57 backup: boolean;
58 /** RFC 3339. */
59 createdAt: string;
60 /** RFC 3339. */
61 verifiedAt: string | null;
62};
63
64export type AccountEmails = {
65 /** The primary first, then confirmed addresses, then the rest. */
66 emails: AccountEmail[];
67 /** Commits g1t makes for the person use `noreply`. */
68 privateEmail: boolean;
69 /** Refuse pushes whose commits carry one of the person's addresses. */
70 blockPrivatePushes: boolean;
71 /** `<id suffix>+<username>@users.noreply.g1t.sh`. */
72 noreply: string;
73 /** The address commits g1t makes for the person carry now. */
74 commitEmail: string;
75 limit: number;
76};
77
78/** What `updateEmailSettings` can change; each field given is changed. */
79export type EmailSettings = {
80 /** A confirmed address to make primary. */
81 primary?: string;
82 /** A confirmed address for security notices too, or "" for the primary only. */
83 backup?: string;
84 privateEmail?: boolean;
85 blockPrivatePushes?: boolean;
86};
87
88export type SecurityEvent = {
89 kind:
90 | "email_added"
91 | "email_verified"
92 | "email_removed"
93 | "primary_email_changed"
94 | "backup_email_changed"
95 | "email_privacy_changed"
96 | "password_changed"
97 | "password_locked"
98 | "ssh_key_added"
99 | "ssh_key_removed"
100 | (string & {});
101 detail: string | null;
102 byStaff: boolean;
103 reason: string | null;
104 /** The staff member; only in staff views. */
105 staff?: string | null;
106 /** RFC 3339. */
107 createdAt: string;
108};
109
110/** The account a commit's author address belongs to. */
111export type EmailOwner = { id: string; username: string; avatar: string | null };
112
113/** One account's addresses and security log, as staff see them. */
114export type AdminUser = {
115 id: string;
116 username: string;
117 /** RFC 3339. */
118 createdAt: string;
119 emails: AccountEmail[];
120 privateEmail: boolean;
121 log: SecurityEvent[];
122 /** What deleting it would take, and what stands in the way (billing is not asked for staff). */
123 deletion: AccountDeletion;
124 /** Set while it is deleted and not yet purged. */
125 deleted: DeletedAccount | null;
126};
127
128/** Where an account's two-factor authentication stands. */
129export type TwoFactorStatus = {
130 enabled: boolean;
131 /** RFC 3339. */
132 enabled_at: string | null;
133 /** Recovery codes not used yet. */
134 recovery_codes_left: number;
135 /** The workspaces the person belongs to that require it. */
136 required_by: string[];
137};
138
139/** What an authenticator app needs: the secret in base32, and the same as an `otpauth://` address for a QR code. */
140export type TwoFactorSetup = { secret: string; uri: string };
141
142/** How many recovery codes an account gets. */
143export const RECOVERY_CODES = 10;
144
145export interface AccountsApi {
146 /** The person's own addresses. People only, never an agent's or a workspace's token. */
147 listEmails(user: User): Promise<Result<AccountEmails>>;
148 /** Adds an address and emails it a confirmation link. Needs `reauth`. */
149 addEmail(user: User, email: string, reauth: Reauth): Promise<Result<AccountEmails>>;
150 /** Removes an address; never the primary nor the last confirmed one. Needs `reauth`. */
151 removeEmail(user: User, email: string, reauth: Reauth): Promise<Result<AccountEmails>>;
152 /** Sends a new confirmation code and link, at most once a minute; the ones before stop working. */
153 resendEmailVerification(user: User, email: string): Promise<Result<boolean>>;
154 /**
155 * The code from a confirmation email, typed by the signed-in person it was
156 * sent to. Wrong codes are counted against the account and `client`.
157 */
158 confirmEmailCode(user: User, code: string, client?: string | null): Promise<Result<EmailConfirmed>>;
159 /**
160 * For an account with no confirmed address: replaces the address it signed
161 * up with, and sends a new code and link there.
162 */
163 changePendingEmail(user: User, email: string): Promise<Result<AccountEmails>>;
164 /** Primary and backup need `reauth`; the privacy switches do not. */
165 updateEmailSettings(user: User, settings: EmailSettings, reauth: Reauth): Promise<Result<AccountEmails>>;
166 /** The person typed their password again for this session. */
167 reauthenticate(sessionToken: string, password: string, client?: string | null): Promise<Result<boolean>>;
168 /** The newest entries of the person's security log. */
169 securityLog(user: User): Promise<Result<SecurityEvent[]>>;
170 /** Whose commits these are, by author address: confirmed and noreply addresses only. */
171 emailOwners(emails: string[]): Promise<Record<string, EmailOwner>>;
172 /** Whether two-factor authentication is on, and which workspaces require it. */
173 twoFactorStatus(user: User): Promise<Result<TwoFactorStatus>>;
174 /** Begins turning it on: a new secret for the app. Needs `reauth`. */
175 twoFactorStart(user: User, reauth: Reauth): Promise<Result<TwoFactorSetup>>;
176 /** A code from the app confirms it; returns the recovery codes, shown once. Needs `reauth`. */
177 twoFactorEnable(user: User, code: string, reauth: Reauth): Promise<Result<{ codes: string[] }>>;
178 /** Turns it off with a code (or a recovery code). Needs `reauth`. */
179 twoFactorDisable(user: User, code: string, reauth: Reauth): Promise<Result<boolean>>;
180 /** New recovery codes, replacing the old ones. Needs `reauth`. */
181 twoFactorRecoveryCodes(user: User, reauth: Reauth): Promise<Result<{ codes: string[] }>>;
182 /** What deleting the person's own account would take, and what stands in the way, changing nothing. People only. */
183 checkAccountDeletion(user: User): Promise<Result<AccountDeletion>>;
184 /**
185 * Deletes the person's own account. `confirm` is their username, typed
186 * out; needs `reauth`. Refused for a protected account and while they are
187 * the only owner of a live workspace. Kept `ACCOUNT_RESTORE_DAYS` for
188 * staff to restore. Publishes `user.deleting`. Not offered by the API.
189 */
190 deleteAccount(user: User, confirm: string, reauth: Reauth): Promise<Result<boolean>>;
191}
192
193/** Staff only, for sudo.g1t.sh. */
194export interface AccountsAdminApi {
195 user(username: string): Promise<AdminUser | null>;
196 /** Removes an address with a reason the person sees; never the last confirmed one. */
197 removeEmail(username: string, email: string, reason: string, staff: string): Promise<Result<AdminUser>>;
198 /**
199 * Deletes an account, with the reason and the username typed out. Refused
200 * for a protected account, and while it is the only owner of a live
201 * workspace unless `withSoleWorkspaces`: then each of those is deleted
202 * first, as its owner would, and the account last. Refused whole while any
203 * of them is protected or its billing cannot settle; a workspace failing
204 * on the way stops it before the account. Recorded in sudo's audit log
205 * (`workspace_deleted` for each, `account_deleted`).
206 */
207 deleteAccount(
208 username: string,
209 reason: string,
210 confirm: string,
211 staff: string,
212 withSoleWorkspaces?: boolean,
213 ): Promise<Result<boolean>>;
214 /** Deleted accounts not purged yet, newest first. */
215 deletedAccounts(): Promise<DeletedAccount[]>;
216 /** Brings a deleted account back within its window, with the memberships it left. Publishes `user.restored`. */
217 restoreAccount(userId: string, staff: string): Promise<Result<boolean>>;
218 /** Purges a deleted account now; `confirm` is its username. Publishes `user.deleted`. */
219 purgeAccount(userId: string, staff: string, confirm: string): Promise<Result<boolean>>;
220}
221
222async function call<T>(service: ServiceBinding, method: string, args: object): Promise<T> {
223 const response = await service.fetch(`https://service/rpc/${method}`, {
224 method: "POST",
225 headers: { "content-type": "application/json" },
226 body: JSON.stringify(args),
227 });
228 if (!response.ok) throw new Error(`${method} failed with status ${response.status}`);
229 return (await response.json()) as T;
230}
231
232export function accountsClient(identity: ServiceBinding): AccountsApi {
233 return {
234 listEmails: (user) => call(identity, "list_emails", { user }),
235 addEmail: (user, email, reauth) => call(identity, "add_email", { user, email, reauth }),
236 removeEmail: (user, email, reauth) => call(identity, "remove_email", { user, email, reauth }),
237 resendEmailVerification: (user, email) => call(identity, "resend_email_verification", { user, email }),
238 confirmEmailCode: (user, code, client) => call(identity, "confirm_email_code", { user, code, client: client ?? null }),
239 changePendingEmail: (user, email) => call(identity, "change_pending_email", { user, email }),
240 updateEmailSettings: (user, settings, reauth) => call(identity, "update_email_settings", { user, ...settings, reauth }),
241 reauthenticate: (sessionToken, password, client) => call(identity, "reauthenticate", { sessionToken, password, client: client ?? null }),
242 securityLog: (user) => call(identity, "security_log", { user }),
243 emailOwners: (emails) => call(identity, "email_owners", { emails }),
244 twoFactorStatus: (user) => call(identity, "two_factor_status", { user }),
245 twoFactorStart: (user, reauth) => call(identity, "two_factor_start", { user, reauth }),
246 twoFactorEnable: (user, code, reauth) => call(identity, "two_factor_enable", { user, code, reauth }),
247 twoFactorDisable: (user, code, reauth) => call(identity, "two_factor_disable", { user, code, reauth }),
248 twoFactorRecoveryCodes: (user, reauth) => call(identity, "two_factor_recovery_codes", { user, reauth }),
249 checkAccountDeletion: (user) => call(identity, "check_account_deletion", { user }),
250 deleteAccount: (user, confirm, reauth) => call(identity, "delete_account", { user, confirm, reauth }),
251 };
252}
253
254export function accountsAdminClient(identity: ServiceBinding): AccountsAdminApi {
255 return {
256 user: (username) => call(identity, "admin_user", { username }),
257 removeEmail: (username, email, reason, staff) => call(identity, "admin_remove_email", { username, email, reason, staff }),
258 deleteAccount: (username, reason, confirm, staff, withSoleWorkspaces) =>
259 call(identity, "admin_delete_account", { username, reason, confirm, staff, withSoleWorkspaces: withSoleWorkspaces ?? false }),
260 deletedAccounts: () => call(identity, "admin_deleted_accounts", {}),
261 restoreAccount: (userId, staff) => call(identity, "admin_restore_account", { userId, staff }),
262 purgeAccount: (userId, staff, confirm) => call(identity, "admin_purge_account", { userId, staff, confirm }),
263 };
264}
265
266/** Words for a security log entry, as the person reads it. */
267export function securityEventLabel(event: Pick<SecurityEvent, "kind" | "detail">): string {
268 const detail = event.detail ?? "";
269 switch (event.kind) {
270 case "email_added":
271 return `Added ${detail}`;
272 case "email_verified":
273 return `Confirmed ${detail}`;
274 case "email_changed_before_confirming":
275 return `Changed the address to confirm to ${detail}`;
276 case "email_removed":
277 return `Removed ${detail}`;
278 case "primary_email_changed":
279 return `Made ${detail} primary`;
280 case "backup_email_changed":
281 return detail === "primary only" ? "Security notices go to the primary only" : `Made ${detail} the backup`;
282 case "email_privacy_changed":
283 return `Email privacy: ${detail}`;
284 case "password_changed":
285 return "Changed the password";
286 case "password_locked":
287 return `Password sign-in paused after ${detail}`;
288 case "two_factor_enabled":
289 return "Turned on two-factor authentication";
290 case "two_factor_disabled":
291 return "Turned off two-factor authentication";
292 case "recovery_codes_regenerated":
293 return "Made new recovery codes";
294 case "recovery_code_used":
295 return "Signed in with a recovery code";
296 case "token_created":
297 return `Created access token ${detail}`;
298 case "token_deleted":
299 return `Deleted access token ${detail}`;
300 case "token_rescoped":
301 return `Changed the scopes of access token ${detail}`;
302 case "ssh_key_added":
303 return `Added SSH key ${detail}`;
304 case "ssh_key_removed":
305 return `Removed SSH key ${detail}`;
306 case "oauth_grant_created":
307 return `Authorized ${detail}`;
308 case "oauth_grant_revoked":
309 return `Revoked ${detail}`;
310 case "oauth_grant_rescoped":
311 return `Changed what ${detail} may do`;
312 case "account_deleted":
313 return "Deleted the account";
314 case "account_restored":
315 return "Restored the account";
316 default:
317 return detail ? `${event.kind}: ${detail}` : event.kind;
318 }
319}