Skip to content
308 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. Recorded in sudo's audit log (`account_deleted`).
202 */
203 deleteAccount(username: string, reason: string, confirm: string, staff: string): Promise<Result<boolean>>;
204 /** Deleted accounts not purged yet, newest first. */
205 deletedAccounts(): Promise<DeletedAccount[]>;
206 /** Brings a deleted account back within its window, with the memberships it left. Publishes `user.restored`. */
207 restoreAccount(userId: string, staff: string): Promise<Result<boolean>>;
208 /** Purges a deleted account now; `confirm` is its username. Publishes `user.deleted`. */
209 purgeAccount(userId: string, staff: string, confirm: string): Promise<Result<boolean>>;
210}
211
212async function call<T>(service: ServiceBinding, method: string, args: object): Promise<T> {
213 const response = await service.fetch(`https://service/rpc/${method}`, {
214 method: "POST",
215 headers: { "content-type": "application/json" },
216 body: JSON.stringify(args),
217 });
218 if (!response.ok) throw new Error(`${method} failed with status ${response.status}`);
219 return (await response.json()) as T;
220}
221
222export function accountsClient(identity: ServiceBinding): AccountsApi {
223 return {
224 listEmails: (user) => call(identity, "list_emails", { user }),
225 addEmail: (user, email, reauth) => call(identity, "add_email", { user, email, reauth }),
226 removeEmail: (user, email, reauth) => call(identity, "remove_email", { user, email, reauth }),
227 resendEmailVerification: (user, email) => call(identity, "resend_email_verification", { user, email }),
228 confirmEmailCode: (user, code, client) => call(identity, "confirm_email_code", { user, code, client: client ?? null }),
229 changePendingEmail: (user, email) => call(identity, "change_pending_email", { user, email }),
230 updateEmailSettings: (user, settings, reauth) => call(identity, "update_email_settings", { user, ...settings, reauth }),
231 reauthenticate: (sessionToken, password, client) => call(identity, "reauthenticate", { sessionToken, password, client: client ?? null }),
232 securityLog: (user) => call(identity, "security_log", { user }),
233 emailOwners: (emails) => call(identity, "email_owners", { emails }),
234 twoFactorStatus: (user) => call(identity, "two_factor_status", { user }),
235 twoFactorStart: (user, reauth) => call(identity, "two_factor_start", { user, reauth }),
236 twoFactorEnable: (user, code, reauth) => call(identity, "two_factor_enable", { user, code, reauth }),
237 twoFactorDisable: (user, code, reauth) => call(identity, "two_factor_disable", { user, code, reauth }),
238 twoFactorRecoveryCodes: (user, reauth) => call(identity, "two_factor_recovery_codes", { user, reauth }),
239 checkAccountDeletion: (user) => call(identity, "check_account_deletion", { user }),
240 deleteAccount: (user, confirm, reauth) => call(identity, "delete_account", { user, confirm, reauth }),
241 };
242}
243
244export function accountsAdminClient(identity: ServiceBinding): AccountsAdminApi {
245 return {
246 user: (username) => call(identity, "admin_user", { username }),
247 removeEmail: (username, email, reason, staff) => call(identity, "admin_remove_email", { username, email, reason, staff }),
248 deleteAccount: (username, reason, confirm, staff) => call(identity, "admin_delete_account", { username, reason, confirm, staff }),
249 deletedAccounts: () => call(identity, "admin_deleted_accounts", {}),
250 restoreAccount: (userId, staff) => call(identity, "admin_restore_account", { userId, staff }),
251 purgeAccount: (userId, staff, confirm) => call(identity, "admin_purge_account", { userId, staff, confirm }),
252 };
253}
254
255/** Words for a security log entry, as the person reads it. */
256export function securityEventLabel(event: Pick<SecurityEvent, "kind" | "detail">): string {
257 const detail = event.detail ?? "";
258 switch (event.kind) {
259 case "email_added":
260 return `Added ${detail}`;
261 case "email_verified":
262 return `Confirmed ${detail}`;
263 case "email_changed_before_confirming":
264 return `Changed the address to confirm to ${detail}`;
265 case "email_removed":
266 return `Removed ${detail}`;
267 case "primary_email_changed":
268 return `Made ${detail} primary`;
269 case "backup_email_changed":
270 return detail === "primary only" ? "Security notices go to the primary only" : `Made ${detail} the backup`;
271 case "email_privacy_changed":
272 return `Email privacy: ${detail}`;
273 case "password_changed":
274 return "Changed the password";
275 case "password_locked":
276 return `Password sign-in paused after ${detail}`;
277 case "two_factor_enabled":
278 return "Turned on two-factor authentication";
279 case "two_factor_disabled":
280 return "Turned off two-factor authentication";
281 case "recovery_codes_regenerated":
282 return "Made new recovery codes";
283 case "recovery_code_used":
284 return "Signed in with a recovery code";
285 case "token_created":
286 return `Created access token ${detail}`;
287 case "token_deleted":
288 return `Deleted access token ${detail}`;
289 case "token_rescoped":
290 return `Changed the scopes of access token ${detail}`;
291 case "ssh_key_added":
292 return `Added SSH key ${detail}`;
293 case "ssh_key_removed":
294 return `Removed SSH key ${detail}`;
295 case "oauth_grant_created":
296 return `Authorized ${detail}`;
297 case "oauth_grant_revoked":
298 return `Revoked ${detail}`;
299 case "oauth_grant_rescoped":
300 return `Changed what ${detail} may do`;
301 case "account_deleted":
302 return "Deleted the account";
303 case "account_restored":
304 return "Restored the account";
305 default:
306 return detail ? `${event.kind}: ${detail}` : event.kind;
307 }
308}