@openparachute/hub 0.7.3-rc.3 → 0.7.3-rc.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -21,7 +21,13 @@ import {
21
21
  getPendingLogin,
22
22
  parsePendingLoginCookie,
23
23
  } from "./pending-login.ts";
24
- import { checkAndRecord, clientIpFromRequest, totpRateLimiter } from "./rate-limit.ts";
24
+ import {
25
+ authIpCeilingRateLimiter,
26
+ clientIpFromRequest,
27
+ compositeKey,
28
+ loginRateLimiter,
29
+ totpRateLimiter,
30
+ } from "./rate-limit.ts";
25
31
  import { isHttpsRequest } from "./request-protocol.ts";
26
32
  import {
27
33
  SESSION_TTL_MS,
@@ -167,24 +173,42 @@ export async function handleAdminLoginPost(
167
173
  );
168
174
  }
169
175
  // Rate-limit gate fires *after* CSRF (so a junk cross-site POST doesn't
170
- // burn a bucket slot for the victim's IP) but *before* credential check.
176
+ // burn a bucket slot for the victim) but *before* credential check.
171
177
  // Every legitimate login attempt — wrong password, missing user, eventually
172
- // failed-2FA (#186) — counts toward the same bucket so an attacker can't
173
- // partition the cooldown across stages.
178
+ // failed-2FA — counts toward the same bucket so an attacker can't partition
179
+ // the cooldown across stages.
180
+ //
181
+ // Two tiers (the shared-egress-IP fix): a coarse per-IP CEILING (60/15min)
182
+ // backstops username-rotation, then a per-(ip,username) FLOOR (5/15min) so
183
+ // each account behind a shared NAT / Cloudflare egress IP gets its own
184
+ // bucket instead of the whole room pooling into one 5-slot per-IP bucket.
185
+ // `username` is hoisted above the gate because the floor keys on it. The same
186
+ // `loginRateLimiter` + `compositeKey(ip, username)` scheme backs the
187
+ // `/oauth/authorize` password door, so both doors share ONE per-account
188
+ // bucket.
189
+ const username = String(form.get("username") ?? "");
174
190
  const clientIp = clientIpFromRequest(req);
175
191
  const now = deps.now ? deps.now() : new Date();
176
- const gate = checkAndRecord(clientIp, now);
177
- if (!gate.allowed) {
192
+ // Both checks always run (no short-circuit): a denied `checkAndRecord` does
193
+ // NOT append a timestamp, so running the floor after a denied ceiling never
194
+ // double-counts. We need both recorded so each independently tracks its own
195
+ // bucket (the floor still gates per-account even when the ceiling is fine).
196
+ const ceiling = authIpCeilingRateLimiter.checkAndRecord(clientIp, now);
197
+ const floor = loginRateLimiter.checkAndRecord(compositeKey(clientIp, username), now);
198
+ if (!ceiling.allowed || !floor.allowed) {
199
+ const retryAfterSeconds = Math.max(
200
+ ceiling.allowed ? 0 : (ceiling.retryAfterSeconds ?? 1),
201
+ floor.allowed ? 0 : (floor.retryAfterSeconds ?? 1),
202
+ );
178
203
  return htmlResponse(
179
204
  renderAdminError({
180
205
  title: "Too many login attempts",
181
- message: `Too many login attempts from this IP. Try again in ${gate.retryAfterSeconds ?? 1} seconds.`,
206
+ message: `Too many login attempts. Try again in ${retryAfterSeconds} seconds.`,
182
207
  }),
183
208
  429,
184
- { "retry-after": String(gate.retryAfterSeconds ?? 1) },
209
+ { "retry-after": String(retryAfterSeconds) },
185
210
  );
186
211
  }
187
- const username = String(form.get("username") ?? "");
188
212
  const password = String(form.get("password") ?? "");
189
213
  const next = safeNext(String(form.get("next") ?? ""));
190
214
  const csrfToken = typeof formCsrf === "string" ? formCsrf : "";
@@ -314,23 +338,36 @@ export async function handleAdminLoginTotpPost(
314
338
  const next = safeNext(String(form.get("next") ?? ""));
315
339
  const code = String(form.get("code") ?? "");
316
340
 
317
- // Rate-limit BEFORE resolving the pending login or verifying the factor.
341
+ // Rate-limit BEFORE verifying the factor. Resolve the pending login FIRST so
342
+ // the per-account floor can key on the STABLE userId (NOT the pendingToken,
343
+ // which a fresh /login success rotates and would reset the bucket). Resolving
344
+ // here also lets a bad/expired pending token fall back to keying the floor by
345
+ // IP alone — never by the rotating pendingToken.
318
346
  const clientIp = clientIpFromRequest(req);
319
347
  const now = deps.now ? deps.now() : new Date();
320
- const gate = totpRateLimiter.checkAndRecord(clientIp, now);
321
- if (!gate.allowed) {
348
+ const pendingToken = parsePendingLoginCookie(req.headers.get("cookie"));
349
+ const pending = getPendingLogin(pendingToken, () => now);
350
+ // Two tiers (the shared-egress-IP fix): coarse per-IP CEILING (60/15min) +
351
+ // per-(ip,userId) FLOOR (5/15min). When userId can't be resolved (bad/expired
352
+ // pending token), key the floor by IP alone — do NOT key by the pendingToken.
353
+ const ceiling = authIpCeilingRateLimiter.checkAndRecord(clientIp, now);
354
+ const floorKey = pending ? compositeKey(clientIp, pending.userId) : clientIp;
355
+ const floor = totpRateLimiter.checkAndRecord(floorKey, now);
356
+ if (!ceiling.allowed || !floor.allowed) {
357
+ const retryAfterSeconds = Math.max(
358
+ ceiling.allowed ? 0 : (ceiling.retryAfterSeconds ?? 1),
359
+ floor.allowed ? 0 : (floor.retryAfterSeconds ?? 1),
360
+ );
322
361
  return htmlResponse(
323
362
  renderAdminError({
324
363
  title: "Too many attempts",
325
- message: `Too many verification attempts from this IP. Try again in ${gate.retryAfterSeconds ?? 1} seconds.`,
364
+ message: `Too many verification attempts. Try again in ${retryAfterSeconds} seconds.`,
326
365
  }),
327
366
  429,
328
- { "retry-after": String(gate.retryAfterSeconds ?? 1) },
367
+ { "retry-after": String(retryAfterSeconds) },
329
368
  );
330
369
  }
331
370
 
332
- const pendingToken = parsePendingLoginCookie(req.headers.get("cookie"));
333
- const pending = getPendingLogin(pendingToken, () => now);
334
371
  if (!pending) {
335
372
  // No live pending login — expired, missing, or tampered. Send the user
336
373
  // back to the start; clear any stale pending cookie.
@@ -175,7 +175,16 @@ export interface InviteSetupProps {
175
175
  role: string;
176
176
  /** Whether redemption provisions a vault at all (shows the vault row iff true). */
177
177
  provisionVault: boolean;
178
+ /**
179
+ * Whether to collect the redeemer's email (B2). True for public-signup
180
+ * (multi-use) links — the operator must be able to reach the stranger who
181
+ * signed up; false for legacy single-use admin/friends invites. Default
182
+ * false (omitted) preserves the friends flow's no-email form.
183
+ */
184
+ collectEmail?: boolean;
178
185
  username?: string;
186
+ /** Echoed email value on a re-render so the redeemer doesn't retype it. */
187
+ email?: string;
179
188
  vaultName?: string;
180
189
  errorMessage?: string;
181
190
  }
@@ -194,12 +203,28 @@ export function renderInviteSetup(props: InviteSetupProps): string {
194
203
  pinnedUsername,
195
204
  role,
196
205
  provisionVault,
206
+ collectEmail,
197
207
  username,
208
+ email,
198
209
  vaultName,
199
210
  errorMessage,
200
211
  } = props;
201
212
  const error = errorMessage ? `<p class="error-banner">${escapeHtml(errorMessage)}</p>` : "";
202
213
  const usernameAttr = username ? ` value="${escapeAttr(username)}"` : "";
214
+ const emailAttr = email ? ` value="${escapeAttr(email)}"` : "";
215
+
216
+ // Email row (B2): shown ONLY for public-signup (multi-use) links so the
217
+ // operator can reach the stranger who signed up. `type=email` gets the
218
+ // browser's built-in client-side format check (the server re-validates).
219
+ const emailRow = collectEmail
220
+ ? `
221
+ <label class="field">
222
+ <span class="field-label">Email</span>
223
+ <input type="email" name="email" autocomplete="email" required
224
+ spellcheck="false" autocapitalize="off"${emailAttr} />
225
+ <span class="field-hint">So your hub operator can reach you.</span>
226
+ </label>`
227
+ : "";
203
228
 
204
229
  // Username row: pre-named → read-only display (the server ENFORCES the
205
230
  // invite's username; the disabled input never submits and the handler
@@ -304,6 +329,7 @@ export function renderInviteSetup(props: InviteSetupProps): string {
304
329
  <form method="POST" action="/account/setup/${escapeAttr(token)}" class="auth-form">
305
330
  ${renderCsrfHiddenInput(csrfToken)}
306
331
  ${usernameRow}
332
+ ${emailRow}
307
333
  <label class="field">
308
334
  <span class="field-label">Password</span>
309
335
  <input type="password" name="password" autocomplete="new-password"
@@ -405,7 +431,7 @@ const STYLES = `
405
431
  letter-spacing: 0.01em;
406
432
  font-family: ${FONT_MONO};
407
433
  }
408
- input[type=text], input[type=password] {
434
+ input[type=text], input[type=password], input[type=email] {
409
435
  font: inherit;
410
436
  width: 100%;
411
437
  padding: 0.6rem 0.75rem;
@@ -415,7 +441,7 @@ const STYLES = `
415
441
  color: ${PALETTE.fg};
416
442
  transition: border-color 0.15s ease, background 0.15s ease;
417
443
  }
418
- input[type=text]:focus, input[type=password]:focus {
444
+ input[type=text]:focus, input[type=password]:focus, input[type=email]:focus {
419
445
  outline: none;
420
446
  border-color: ${PALETTE.accent};
421
447
  background: ${PALETTE.cardBg};
@@ -461,10 +487,10 @@ const STYLES = `
461
487
  .card { background: #25221d; border-color: #3a362f; box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3); }
462
488
  h1 { color: #f0ece4; }
463
489
  .subtitle, .field-label { color: #a8a29a; }
464
- input[type=text], input[type=password] {
490
+ input[type=text], input[type=password], input[type=email] {
465
491
  background: #1f1c18; border-color: #3a362f; color: #e8e4dc;
466
492
  }
467
- input[type=text]:focus, input[type=password]:focus {
493
+ input[type=text]:focus, input[type=password]:focus, input[type=email]:focus {
468
494
  background: #25221d;
469
495
  }
470
496
  .brand-tag { border-color: #3a362f; color: #a8a29a; }
@@ -68,6 +68,7 @@ import { revokeTokensNamingVault, signAccessToken } from "./jwt-sign.ts";
68
68
  import { findService, type readManifest, readManifestLenient } from "./services-manifest.ts";
69
69
  import { enrichedPath } from "./spawn-path.ts";
70
70
  import { removeVaultAssignments } from "./users.ts";
71
+ import { removeVaultCap } from "./vault-caps.ts";
71
72
  import { RESERVED_VAULT_NAMES, VAULT_NAME_CHARSET_RE } from "./vault-name.ts";
72
73
  import { type WellKnownVaultEntry, isVaultEntry, vaultInstanceNameFor } from "./well-known.ts";
73
74
 
@@ -577,6 +578,7 @@ interface CascadeSummary {
577
578
  grants_dropped: number;
578
579
  user_vaults_removed: number;
579
580
  invites_invalidated: number;
581
+ vault_cap_removed: boolean;
580
582
  connections_torn_down: number;
581
583
  /**
582
584
  * Vault-backed channel-daemon entries still referencing the deleted vault
@@ -596,6 +598,7 @@ function emptyCascadeSummary(): CascadeSummary {
596
598
  grants_dropped: 0,
597
599
  user_vaults_removed: 0,
598
600
  invites_invalidated: 0,
601
+ vault_cap_removed: false,
599
602
  connections_torn_down: 0,
600
603
  orphaned_channels: [],
601
604
  vault_removed: false,
@@ -648,7 +651,8 @@ function listVaultInstanceNames(manifestPath: string): Set<string> {
648
651
  * it empties — a (user,client) grant can span multiple vaults);
649
652
  * 3. `user_vaults` rows;
650
653
  * 4. unredeemed invites pinned to the vault (redemption would resurrect
651
- * the name);
654
+ * the name); the per-vault storage-cap row (v15) so a re-created
655
+ * same-name vault doesn't inherit a stale cap;
652
656
  * 5. connections whose source/provisioned vault is the deleted vault
653
657
  * (via `teardownConnection`, which post-B0 also revokes the registered
654
658
  * long-lived mints) + a report-only scan of the agent's `/api/channels`
@@ -753,6 +757,10 @@ export async function handleDeleteVault(
753
757
  // --- 4. Unredeemed invites pinned to the vault. ----------------------------
754
758
  summary.invites_invalidated = revokeInvitesForVault(deps.db, name, now);
755
759
 
760
+ // --- 4b. Per-vault storage cap row (v15). ----------------------------------
761
+ // A re-created same-name vault must not inherit a stale cap; drop it.
762
+ summary.vault_cap_removed = removeVaultCap(deps.db, name) > 0;
763
+
756
764
  // --- 5. Connections teardown (+ legacy channel scan, report-only). --------
757
765
  // Runs BEFORE the CLI remove so the vault daemon is still alive to accept
758
766
  // the trigger-deregister calls.
@@ -15,6 +15,18 @@
15
15
  *
16
16
  * Wire shape is snake_case (matches `/api/users`). An invite's raw token
17
17
  * NEVER appears in a GET/list response — only in the POST-create `url`.
18
+ *
19
+ * v15 (DEMO-PREP Workstream B) extends POST /api/invites with `max_uses`
20
+ * (multi-use public-signup links, default 1 = single-use) and
21
+ * `vault_cap_bytes` (per-vault storage cap stamped at provision, B4). A
22
+ * multi-use PROVISIONING link with no explicit `vault_cap_bytes` auto-defaults
23
+ * to ~1 GB (DEFAULT_VAULT_CAP_BYTES) so a public link never provisions
24
+ * uncapped by omission; single-use friends links stay uncapped unless opted
25
+ * in. The list/create wire shape gains `max_uses`, `used_count`, `email`
26
+ * (latest redeemer, B2), and `vault_cap_bytes`. `expires_in` already bounded
27
+ * the link lifetime (B1's expiry). A multi-use link can't pre-name a username
28
+ * or pin a single new vault name (every seat past the first would collide —
29
+ * rejected at mint).
18
30
  */
19
31
  import type { Database } from "bun:sqlite";
20
32
  import { type AdminAuthError, adminAuthErrorResponse, requireScope } from "./admin-auth.ts";
@@ -32,6 +44,7 @@ import {
32
44
  usernameReservedByPendingInvite,
33
45
  } from "./invites.ts";
34
46
  import { getUserByUsernameCI, validateUsername } from "./users.ts";
47
+ import { DEFAULT_VAULT_CAP_BYTES } from "./vault-caps.ts";
35
48
  import { VAULT_NAME_CHARSET_RE } from "./vault-name.ts";
36
49
  import { listVaultNamesFromPath } from "./vault-names.ts";
37
50
 
@@ -47,6 +60,18 @@ export interface ApiInvitesDeps {
47
60
  const ALLOWED_ROLES = new Set(["read", "write"]);
48
61
  /** Cap an invite TTL so a typo can't mint a ~forever link. 90 days. */
49
62
  const MAX_INVITE_TTL_SECONDS = 90 * 24 * 60 * 60;
63
+ /**
64
+ * Cap `max_uses` (v15) so a typo can't mint a runaway public-signup link on a
65
+ * shared box. 1000 is comfortably above any demo cohort while still bounding
66
+ * the abuse surface. The DEMO-PREP shared box uses small values (tens of seats).
67
+ */
68
+ const MAX_INVITE_USES = 1000;
69
+ /**
70
+ * Ceiling on a per-vault cap an invite may carry (v15, B4). 100 GiB — far
71
+ * above the ~1 GB default, but bounds a fat-finger that would make the cap
72
+ * meaningless on a shared box. The minimum is 1 byte (a positive integer).
73
+ */
74
+ const MAX_VAULT_CAP_BYTES = 100 * 1024 * 1024 * 1024;
50
75
 
51
76
  interface InviteWireShape {
52
77
  /** sha256 hash — the stable id for list/revoke. NOT the raw token. */
@@ -57,6 +82,14 @@ interface InviteWireShape {
57
82
  role: string;
58
83
  provision_vault: boolean;
59
84
  default_mirror: string | null;
85
+ /** v15 — how many accounts this link may create (1 = single-use). */
86
+ max_uses: number;
87
+ /** v15 — how many it has created so far. */
88
+ used_count: number;
89
+ /** v15 — most-recent redeemer's email (B2), or null. */
90
+ email: string | null;
91
+ /** v15 — per-vault storage cap to stamp at provision (B4), or null (uncapped). */
92
+ vault_cap_bytes: number | null;
60
93
  expires_at: string;
61
94
  used_at: string | null;
62
95
  redeemed_user_id: string | null;
@@ -73,6 +106,10 @@ function toWire(invite: Invite, status: InviteStatus): InviteWireShape {
73
106
  role: invite.role,
74
107
  provision_vault: invite.provisionVault,
75
108
  default_mirror: invite.defaultMirror,
109
+ max_uses: invite.maxUses,
110
+ used_count: invite.usedCount,
111
+ email: invite.email,
112
+ vault_cap_bytes: invite.vaultCapBytes,
76
113
  expires_at: invite.expiresAt,
77
114
  used_at: invite.usedAt,
78
115
  redeemed_user_id: invite.redeemedUserId,
@@ -100,6 +137,10 @@ interface CreateInviteBody {
100
137
  provisionVault: boolean;
101
138
  defaultMirror: string | null;
102
139
  expiresInSeconds: number;
140
+ /** v15 — how many accounts the link may create (default 1 = single-use). */
141
+ maxUses: number;
142
+ /** v15 — per-vault storage cap (bytes) to stamp at provision, or null (uncapped). */
143
+ vaultCapBytes: number | null;
103
144
  }
104
145
 
105
146
  interface ParseErr {
@@ -283,9 +324,71 @@ async function parseCreateBody(
283
324
  expiresInSeconds = Math.floor(rawExpiry);
284
325
  }
285
326
 
327
+ // max_uses — v15. Default 1 (single-use, the legacy shape). A positive
328
+ // integer ≤ MAX_INVITE_USES. >1 = a multi-use public-signup link.
329
+ let maxUses = 1;
330
+ const rawMaxUses =
331
+ Object.hasOwn(obj, "max_uses") && obj.max_uses !== undefined
332
+ ? obj.max_uses
333
+ : Object.hasOwn(obj, "maxUses") && obj.maxUses !== undefined
334
+ ? obj.maxUses
335
+ : undefined;
336
+ if (rawMaxUses !== undefined && rawMaxUses !== null) {
337
+ if (
338
+ typeof rawMaxUses !== "number" ||
339
+ !Number.isInteger(rawMaxUses) ||
340
+ rawMaxUses < 1 ||
341
+ rawMaxUses > MAX_INVITE_USES
342
+ ) {
343
+ return {
344
+ ok: false,
345
+ status: 400,
346
+ error: "invalid_request",
347
+ description: `"max_uses" must be an integer between 1 and ${MAX_INVITE_USES}`,
348
+ };
349
+ }
350
+ maxUses = rawMaxUses;
351
+ }
352
+
353
+ // vault_cap_bytes — v15, B4. Optional per-vault storage cap stamped at
354
+ // provision. null/omitted = uncapped (legacy). A positive integer
355
+ // ≤ MAX_VAULT_CAP_BYTES.
356
+ let vaultCapBytes: number | null = null;
357
+ const rawCap =
358
+ Object.hasOwn(obj, "vault_cap_bytes") && obj.vault_cap_bytes !== undefined
359
+ ? obj.vault_cap_bytes
360
+ : Object.hasOwn(obj, "vaultCapBytes") && obj.vaultCapBytes !== undefined
361
+ ? obj.vaultCapBytes
362
+ : undefined;
363
+ if (rawCap !== undefined && rawCap !== null) {
364
+ if (
365
+ typeof rawCap !== "number" ||
366
+ !Number.isInteger(rawCap) ||
367
+ rawCap < 1 ||
368
+ rawCap > MAX_VAULT_CAP_BYTES
369
+ ) {
370
+ return {
371
+ ok: false,
372
+ status: 400,
373
+ error: "invalid_request",
374
+ description: `"vault_cap_bytes" must be a positive integer ≤ ${MAX_VAULT_CAP_BYTES} (100 GiB)`,
375
+ };
376
+ }
377
+ vaultCapBytes = rawCap;
378
+ }
379
+
286
380
  return {
287
381
  ok: true,
288
- body: { vaultName, username, role, provisionVault, defaultMirror, expiresInSeconds },
382
+ body: {
383
+ vaultName,
384
+ username,
385
+ role,
386
+ provisionVault,
387
+ defaultMirror,
388
+ expiresInSeconds,
389
+ maxUses,
390
+ vaultCapBytes,
391
+ },
289
392
  };
290
393
  }
291
394
 
@@ -303,8 +406,16 @@ export async function handleCreateInvite(req: Request, deps: ApiInvitesDeps): Pr
303
406
  }
304
407
  const parsed = await parseCreateBody(req);
305
408
  if (!parsed.ok) return jsonError(parsed.status, parsed.error, parsed.description);
306
- const { vaultName, username, role, provisionVault, defaultMirror, expiresInSeconds } =
307
- parsed.body;
409
+ const {
410
+ vaultName,
411
+ username,
412
+ role,
413
+ provisionVault,
414
+ defaultMirror,
415
+ expiresInSeconds,
416
+ maxUses,
417
+ vaultCapBytes,
418
+ } = parsed.body;
308
419
  const now = (deps.now ?? (() => new Date()))();
309
420
 
310
421
  // Shape gates over the three supported invite shapes:
@@ -330,6 +441,42 @@ export async function handleCreateInvite(req: Request, deps: ApiInvitesDeps): Pr
330
441
  'a provisioned vault\'s sole user must hold write — use role "write", or share an existing vault (provision_vault=false + vault_name) for read-only access',
331
442
  );
332
443
  }
444
+
445
+ // Multi-use coherence gates (v15). A link that creates many accounts can't:
446
+ // - pre-name a username (one name can't be reused across redeemers), or
447
+ // - pin a single NEW vault name (every redeemer would collide on it —
448
+ // the redeem path's freshly-created invariant rejects the 2nd onward).
449
+ // Either combination would make every seat past the first dead-on-arrival,
450
+ // so reject at mint. (A multi-use SHARED-vault invite — provision_vault=false
451
+ // + an existing vault_name — IS coherent: many users joining one vault; it's
452
+ // not blocked here.)
453
+ if (maxUses > 1) {
454
+ if (username !== null) {
455
+ return jsonError(
456
+ 400,
457
+ "invalid_request",
458
+ "a multi-use link (max_uses > 1) can't pre-name a username — one username can't be shared across signups. Omit \"username\".",
459
+ );
460
+ }
461
+ if (provisionVault && vaultName !== null) {
462
+ return jsonError(
463
+ 400,
464
+ "invalid_request",
465
+ 'a multi-use provisioning link (max_uses > 1) can\'t pin a single vault name — every signup would collide on it. Omit "vault_name" so each signup names their own vault.',
466
+ );
467
+ }
468
+ }
469
+
470
+ // A per-vault cap only applies to a vault THIS link provisions. Pinning a
471
+ // cap on a non-provisioning invite (account-only or shared-existing-vault)
472
+ // has nothing to stamp — reject the contradiction at mint.
473
+ if (vaultCapBytes !== null && !provisionVault) {
474
+ return jsonError(
475
+ 400,
476
+ "invalid_request",
477
+ '"vault_cap_bytes" only applies to a provisioning invite (provision_vault=true) — a non-provisioning link has no vault to cap',
478
+ );
479
+ }
333
480
  if (vaultName !== null && !provisionVault) {
334
481
  const manifestPath = deps.manifestPath ?? SERVICES_MANIFEST_PATH;
335
482
  const known = new Set(listVaultNamesFromPath(manifestPath));
@@ -358,6 +505,17 @@ export async function handleCreateInvite(req: Request, deps: ApiInvitesDeps): Pr
358
505
  }
359
506
  }
360
507
 
508
+ // Auto-apply the ~1 GB default cap to a PUBLIC-SIGNUP (multi-use,
509
+ // provisioning) link when the admin didn't set one explicitly — the
510
+ // DEMO-PREP decision is "1 GB per vault, configurable," so a multi-use
511
+ // signup link on a shared box should never provision UNcapped by omission.
512
+ // An explicit cap (any value, validated above) is honored as-is; a
513
+ // single-use friends link stays uncapped unless the admin opts in.
514
+ const effectiveVaultCapBytes =
515
+ vaultCapBytes === null && maxUses > 1 && provisionVault
516
+ ? DEFAULT_VAULT_CAP_BYTES
517
+ : vaultCapBytes;
518
+
361
519
  const issued = issueInvite(deps.db, {
362
520
  createdBy: authUserId,
363
521
  vaultName,
@@ -366,6 +524,8 @@ export async function handleCreateInvite(req: Request, deps: ApiInvitesDeps): Pr
366
524
  provisionVault,
367
525
  defaultMirror,
368
526
  expiresInSeconds,
527
+ maxUses,
528
+ vaultCapBytes: effectiveVaultCapBytes,
369
529
  ...(deps.now !== undefined ? { now: deps.now } : {}),
370
530
  });
371
531
  const status = inviteStatus(issued.invite, now);
package/src/api-users.ts CHANGED
@@ -88,6 +88,8 @@ export interface UserWireShape {
88
88
  id: string;
89
89
  username: string;
90
90
  password_changed: boolean;
91
+ /** Contactable email captured at signup (v15, B2), or null. Visible to admin. */
92
+ email: string | null;
91
93
  assigned_vaults: string[];
92
94
  created_at: string;
93
95
  }
@@ -97,6 +99,7 @@ function toWire(u: User): UserWireShape {
97
99
  id: u.id,
98
100
  username: u.username,
99
101
  password_changed: u.passwordChanged,
102
+ email: u.email,
100
103
  assigned_vaults: [...u.assignedVaults],
101
104
  created_at: u.createdAt,
102
105
  };
package/src/hub-db.ts CHANGED
@@ -4,7 +4,10 @@
4
4
  * issuer — signing keys (v1), users + opaque refresh tokens (v2), OAuth
5
5
  * clients + auth-codes + grants + browser sessions (v3), TOTP 2FA
6
6
  * enrollment on the users row (v11, hub#473), and one-time invite links
7
- * (v12, the `invites` table; v13 adds the pre-named `username` column).
7
+ * (v12, the `invites` table; v13 adds the pre-named `username` column;
8
+ * v14 adds refresh-token rotation grace; v15 generalizes invites into
9
+ * multi-use public-signup links + email-as-username + the `vault_caps`
10
+ * per-vault storage-cap table).
8
11
  *
9
12
  * Each open() runs `migrate()` to bring the schema up to date. A
10
13
  * `schema_version` table records every applied migration so re-opens are
@@ -474,6 +477,87 @@ const MIGRATIONS: readonly Migration[] = [
474
477
  ALTER TABLE tokens ADD COLUMN rotated_to TEXT;
475
478
  `,
476
479
  },
480
+ {
481
+ version: 15,
482
+ sql: `
483
+ -- Multi-use public signup links + email-as-username + per-vault caps
484
+ -- (DEMO-PREP-2026-06-25 Workstream B: B1 multi-use invite, B2 email
485
+ -- capture, B4 public signup page; the cap value is persisted now so
486
+ -- B3's vault-side enforcement — a separate Phase-2 PR — can read it).
487
+ --
488
+ -- (1) FOUR columns on \`invites\` generalize the single-use link into a
489
+ -- multi-use, capped one. Backwards compatible: every pre-v15 invite
490
+ -- redeems exactly as before because the defaults reproduce the old
491
+ -- single-use semantics.
492
+ --
493
+ -- * max_uses (INTEGER NOT NULL DEFAULT 1) — how many accounts ONE link
494
+ -- may create. DEFAULT 1 = the historical single-use invite, so every
495
+ -- pre-v15 row and every default-shaped new row stays single-use. A
496
+ -- public signup link mints with a higher value (e.g. 25 demo seats).
497
+ -- * used_count (INTEGER NOT NULL DEFAULT 0) — how many accounts the link
498
+ -- HAS created. Redeem refuses once used_count >= max_uses. Replaces
499
+ -- the boolean used_at as the exhaustion signal for multi-use links;
500
+ -- used_at is RETAINED (stamped on the FIRST redeem) so legacy
501
+ -- single-use lookups + the admin list's "redeemed" status keep
502
+ -- working unchanged.
503
+ -- * email (TEXT, nullable) — the redeemer's email captured at signup
504
+ -- as the contactable identity (B2). NULL on every pre-v15 invite and
505
+ -- on admin-issued links that don't collect email; set per-redemption
506
+ -- for public-signup links. Stored so the operator can reach signups.
507
+ -- (One link → many signups means one invite row can't hold every
508
+ -- redeemer's email; this column holds the MOST-RECENT redeemer's
509
+ -- email for a single-use link, and the per-account email lives on the
510
+ -- users row — see (3). For multi-use the canonical per-user email is
511
+ -- users.email.)
512
+ -- * vault_cap_bytes (INTEGER, nullable) — the per-vault storage cap to
513
+ -- STAMP onto each vault this link provisions (B4). NULL on every
514
+ -- pre-v15 invite + admin-issued links that don't set a cap (those
515
+ -- provision uncapped, the historical behavior); set to ~1 GB on a
516
+ -- public-signup link so each provisioned vault gets a vault_caps row
517
+ -- for the Phase-2 enforcement PR to read. The cap travels on the
518
+ -- invite (not a server-wide default) so different links can carry
519
+ -- different caps.
520
+ --
521
+ -- (2) ONE column on \`users\`: email-as-contactable-identity (B2). The
522
+ -- username stays the login + URL identity ([a-z0-9_-]); email is the
523
+ -- separate contact field the operator sees + uses to reach a signup.
524
+ -- Nullable: every pre-v15 account (wizard admin, env-seeded admin,
525
+ -- pre-named friend invites) predates email capture and keeps NULL.
526
+ -- NOT UNIQUE — two people behind one shared mailbox, or an operator
527
+ -- re-using their address across test accounts, shouldn't be blocked
528
+ -- at the schema. Validation (format) happens at the API/redeem edge.
529
+ --
530
+ -- (3) NEW \`vault_caps\` table — the per-vault storage cap, persisted at
531
+ -- provision time (B4: "persist a per-vault cap value at provision
532
+ -- time EVEN THOUGH vault-side enforcement lands in a separate
533
+ -- Phase-2 PR — at minimum store the cap so the later PR can read +
534
+ -- enforce it"). Keyed by vault_name (the same instance-name space
535
+ -- used across services.json / user_vaults / invites.vault_name; no
536
+ -- FK — vault names resolve through services.json, not a DB row, the
537
+ -- established pattern). cap_bytes is the byte ceiling (default
538
+ -- ~1 GB stamped by the public-signup flow), guarded by a
539
+ -- CHECK (cap_bytes > 0) so a direct DB write can't seed a 0/negative
540
+ -- cap the Phase-2 reader would misinterpret. No backfill — existing
541
+ -- vaults have no cap row, which the Phase-2 enforcement reads as
542
+ -- "uncapped" (only vaults provisioned through a capped signup get a
543
+ -- row).
544
+ ALTER TABLE invites ADD COLUMN max_uses INTEGER NOT NULL DEFAULT 1;
545
+ ALTER TABLE invites ADD COLUMN used_count INTEGER NOT NULL DEFAULT 0;
546
+ ALTER TABLE invites ADD COLUMN email TEXT;
547
+ ALTER TABLE invites ADD COLUMN vault_cap_bytes INTEGER;
548
+ ALTER TABLE users ADD COLUMN email TEXT;
549
+ CREATE TABLE vault_caps (
550
+ vault_name TEXT PRIMARY KEY,
551
+ -- CHECK (cap_bytes > 0): guard against a 0/negative cap from a direct
552
+ -- DB write making the Phase-2 enforcement reader treat the vault as
553
+ -- "0-byte ceiling" (everything over cap) or nonsense. The mint + redeem
554
+ -- paths already validate positivity; this is the at-rest backstop.
555
+ cap_bytes INTEGER NOT NULL CHECK (cap_bytes > 0),
556
+ created_at TEXT NOT NULL,
557
+ updated_at TEXT NOT NULL
558
+ );
559
+ `,
560
+ },
477
561
  ];
478
562
 
479
563
  export function openHubDb(path: string = hubDbPath()): Database {