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