@mupt-ai/dari-gateway 1.0.376 → 1.0.378

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.
@@ -1187,7 +1187,7 @@ async function homePage(approval, authorize, session) {
1187
1187
  if (current instanceof Response)
1188
1188
  return current;
1189
1189
  if (session === null)
1190
- return introPage(approval, authorize);
1190
+ return introPage(approval, authorize, approval.signIn?.phone === undefined ? undefined : {});
1191
1191
  const subscriptions = await approval.subscriptions(session.subject);
1192
1192
  return shareable(authorize, subscriptions).length > 0
1193
1193
  ? choosePage(authorize, session, subscriptions, current)
@@ -1218,7 +1218,10 @@ async function authorizeSubmit(link, request, form) {
1218
1218
  const secret = approval.sessionSecret();
1219
1219
  const session = sessionFrom(request, approval);
1220
1220
  if (session === null && approval.signIn !== undefined && !["deny", "sign_out"].includes(form.get("decision") ?? "")) {
1221
- return signIn(request, approval.signIn, secret, `${AUTHORIZE_PATH}?${authorizeQuery(authorize)}`);
1221
+ const phone = approval.signIn.phone;
1222
+ return phone === undefined || form.get("decision") === "sign_in"
1223
+ ? signIn(request, approval.signIn, secret, `${AUTHORIZE_PATH}?${authorizeQuery(authorize)}`)
1224
+ : await phoneSignIn(request, approval, phone, authorize, form);
1222
1225
  }
1223
1226
  const endConnect = clearCookie(request, CONNECT_COOKIE);
1224
1227
  // A plan's or a key provider's row on the select page is its own submit button.
@@ -1681,7 +1684,92 @@ const KINDS = {
1681
1684
  vercel_token_pass: { name: "Vercel Token Pass", plan: "Token Pass", at: "Vercel", pastedKey: true },
1682
1685
  };
1683
1686
  // The first page a new user sees: what connecting means, and one button.
1684
- function introPage(approval, authorize) {
1687
+ // Signing in by text message, on the intro card: a number, then the code
1688
+ // sent to it. A right code makes the browser that number's user.
1689
+ async function phoneSignIn(request, approval, phone, authorize, form) {
1690
+ const decision = form.get("decision");
1691
+ const number = phoneNumber(form);
1692
+ if (decision === "send_code" || decision === "resend") {
1693
+ if (number === null)
1694
+ return introPage(approval, authorize, { error: "Enter your phone number with its country code." });
1695
+ const keys = [`n:${number}`, ...[phone.callerAddress(request)].filter((a) => a !== null).map((a) => `a:${a}`)];
1696
+ const throttled = phoneThrottle.take(keys);
1697
+ if (throttled !== null)
1698
+ return introPage(approval, authorize, decision === "resend" ? { number, error: throttled } : { error: throttled });
1699
+ try {
1700
+ await phone.sendCode(number, form.get("cf-turnstile-response") || undefined);
1701
+ }
1702
+ catch (error) {
1703
+ phoneThrottle.release(keys);
1704
+ if (!userFacing(error))
1705
+ throw error;
1706
+ return introPage(approval, authorize, decision === "resend" ? { number, error: error.message } : { error: error.message });
1707
+ }
1708
+ return introPage(approval, authorize, { number });
1709
+ }
1710
+ if (decision === "verify_code" && number !== null) {
1711
+ const code = form.get("code")?.replace(/\s/g, "") ?? "";
1712
+ if (!/^\d{6}$/.test(code))
1713
+ return introPage(approval, authorize, { number, error: "Enter the 6-digit code we sent you." });
1714
+ let subject;
1715
+ try {
1716
+ subject = await phone.verifyCode(number, code);
1717
+ }
1718
+ catch (error) {
1719
+ if (!userFacing(error))
1720
+ throw error;
1721
+ return introPage(approval, authorize, { number, error: error.message });
1722
+ }
1723
+ return seeAuthorize(authorize, [userCookie(request, approval, subject)]);
1724
+ }
1725
+ return introPage(approval, authorize, {});
1726
+ }
1727
+ // The number as E.164: the country code and the number typed, or a whole
1728
+ // number posted back from the code step.
1729
+ function phoneNumber(form) {
1730
+ const digits = (value) => (value ?? "").replace(/[\s().-]/g, "");
1731
+ const whole = form.get("phone") !== null
1732
+ ? digits(form.get("phone"))
1733
+ : `+${digits(form.get("country")).replace(/^\+/, "")}${digits(form.get("number"))}`;
1734
+ return /^\+[1-9]\d{6,14}$/.test(whole) ? whole : null;
1735
+ }
1736
+ function userFacing(error) {
1737
+ return error instanceof HttpError && (error.status === 400 || error.status === 429);
1738
+ }
1739
+ // Texts cost money and can harass a number, so a number gets five codes an
1740
+ // hour and one a minute, and a caller ten an hour. A text is counted before it
1741
+ // goes, so parallel requests cannot burst past, and given back if it fails.
1742
+ // Per instance, in memory.
1743
+ class PhoneThrottle {
1744
+ times = new Map();
1745
+ take(keys, now = Date.now()) {
1746
+ const [number, ...callers] = keys.map((key) => this.recent(key, now));
1747
+ if (number.some((at) => now - at < 60 * 1000))
1748
+ return "We just sent a code. Wait a minute before asking for another.";
1749
+ if (number.length >= 5 || callers.some((times) => times.length >= 10))
1750
+ return "Too many codes requested. Try again later.";
1751
+ if (this.times.size > 10_000) {
1752
+ for (const [key, times] of this.times)
1753
+ if (times.every((at) => now - at >= 60 * 60 * 1000))
1754
+ this.times.delete(key);
1755
+ }
1756
+ for (const key of keys)
1757
+ this.times.set(key, [...this.recent(key, now), now]);
1758
+ return null;
1759
+ }
1760
+ release(keys) {
1761
+ for (const key of keys)
1762
+ this.times.set(key, (this.times.get(key) ?? []).slice(0, -1));
1763
+ }
1764
+ recent(key, now) {
1765
+ return (this.times.get(key) ?? []).filter((at) => now - at < 60 * 60 * 1000);
1766
+ }
1767
+ }
1768
+ const phoneThrottle = new PhoneThrottle();
1769
+ const TURNSTILE_SCRIPT = "https://challenges.cloudflare.com/turnstile/v0/api.js";
1770
+ // The intro card. On a platform with phone sign-in, a signed-out user enters
1771
+ // their number here (`phone` without `number`), then the code texted to it.
1772
+ function introPage(approval, authorize, phone) {
1685
1773
  const app = escapeHtml(authorize.app.name);
1686
1774
  const kinds = connectKinds(approval, authorize);
1687
1775
  const keys = keyProviders(approval, authorize);
@@ -1690,6 +1778,45 @@ function introPage(approval, authorize) {
1690
1778
  }
1691
1779
  const names = [...kinds.map((kind) => KINDS[kind].name), ...(keys.length > 0 ? ["an API key"] : [])];
1692
1780
  const ways = names.length > 1 ? `${names.slice(0, -1).join(", ")} or ${names.at(-1)}` : names[0];
1781
+ const pair = `<div class="pair"><span class="tile">${escapeHtml(authorize.app.name.trim().charAt(0).toUpperCase())}</span><span class="join"></span>${DARI_MARK}</div>`;
1782
+ const sms = approval.signIn?.phone;
1783
+ if (phone !== undefined && sms !== undefined) {
1784
+ const siteKey = sms.captchaSiteKey();
1785
+ const captcha = siteKey === null ? "" : `<div class="cf-turnstile" data-sitekey="${escapeHtml(siteKey)}" data-theme="dark" data-size="flexible"></div>`;
1786
+ if (phone.number !== undefined) {
1787
+ return pane(authorize, {
1788
+ title: `Connect ${authorize.app.name}`,
1789
+ step: "connect_subscription",
1790
+ error: phone.error,
1791
+ captcha: siteKey !== null,
1792
+ body: `${pair}
1793
+ <h1 class="lead">Enter Your Code</h1>
1794
+ <p class="returns">Sent to ${escapeHtml(phone.number)}</p>
1795
+ <input type="hidden" name="phone" value="${escapeHtml(phone.number)}">
1796
+ <label class="field" for="code">Code</label>
1797
+ <input id="code" type="text" name="code" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6" placeholder="123456" required autofocus>
1798
+ ${captcha}`,
1799
+ // The main button comes first, so Enter submits it.
1800
+ footer: `<button class="btn primary" type="submit" name="decision" value="verify_code">Continue</button>
1801
+ <div class="actions"><button class="btn ghost" type="submit" name="decision" value="resend" formnovalidate>Resend Code</button><button class="btn ghost" type="submit" name="decision" value="change_number" formnovalidate>Change Number</button></div>`,
1802
+ });
1803
+ }
1804
+ return pane(authorize, {
1805
+ title: `Connect ${authorize.app.name}`,
1806
+ step: "connect_subscription",
1807
+ error: phone.error,
1808
+ captcha: siteKey !== null,
1809
+ body: `${pair}
1810
+ <h1 class="lead">${app} Uses Dari To Connect Your AI ${kinds.length > 0 ? "Subscriptions" : "API Keys"}</h1>
1811
+ <p class="returns">Returns to ${escapeHtml(new URL(authorize.redirectUri).host)}</p>
1812
+ <label class="field" for="number">Phone Number</label>
1813
+ <div class="phone"><input id="country" type="tel" name="country" aria-label="Country Code" inputmode="tel" value="+1" maxlength="5" required><input id="number" name="number" type="tel" inputmode="tel" autocomplete="tel-national" placeholder="Phone Number" required autofocus></div>
1814
+ <p class="hint">We text you a code to sign in. Message and data rates may apply.</p>
1815
+ ${captcha}`,
1816
+ footer: `<button class="btn primary" type="submit" name="decision" value="send_code">Continue</button>
1817
+ <button class="link-alt" type="submit" name="decision" value="sign_in" formnovalidate>Use Another Way</button>`,
1818
+ });
1819
+ }
1693
1820
  return pane(authorize, {
1694
1821
  title: `Connect ${authorize.app.name}`,
1695
1822
  step: "connect_subscription",
@@ -1892,7 +2019,7 @@ ${options.error === undefined ? "" : `<p role="alert">${escapeHtml(options.error
1892
2019
  ${options.footer === undefined ? "" : `<div class="foot">${options.footer}</div>`}
1893
2020
  ${options.back === undefined ? "" : `<button class="nav back" type="submit" name="decision" value="${options.back}" formnovalidate aria-label="Back">${ICONS.back}</button>`}
1894
2021
  <button class="nav close" type="submit" name="decision" value="deny" formnovalidate aria-label="Close">${ICONS.close}</button>
1895
- </form>`, { cookies: options.cookies, event: eventFor(authorize, options.step), refresh: options.refresh });
2022
+ </form>`, { cookies: options.cookies, event: eventFor(authorize, options.step), refresh: options.refresh, captcha: options.captcha });
1896
2023
  }
1897
2024
  function page(title, body, options = {}) {
1898
2025
  // Every page: a pressed button shows it is working until the next page loads.
@@ -1916,6 +2043,9 @@ document.addEventListener("change", (event) => {
1916
2043
  if (window.opener) window.opener.postMessage(event, eventOrigin);</script>`;
1917
2044
  options = { ...options, scriptNonce: nonce };
1918
2045
  }
2046
+ if (options.captcha)
2047
+ body += `\n<script nonce="${options.scriptNonce}" src="${TURNSTILE_SCRIPT}" async defer></script>`;
2048
+ const captchaOrigin = new URL(TURNSTILE_SCRIPT).origin;
1919
2049
  const html = `<!doctype html>
1920
2050
  <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
1921
2051
  ${options.refresh === undefined ? "" : `<meta http-equiv="refresh" content="${options.refresh}">\n`}<title>${escapeHtml(title)}</title>
@@ -1926,7 +2056,7 @@ ${body}
1926
2056
  const headers = new Headers({
1927
2057
  "Content-Type": "text/html; charset=utf-8",
1928
2058
  "Cache-Control": "no-store",
1929
- "Content-Security-Policy": `default-src 'none'; style-src 'unsafe-inline'; font-src 'self'; ${options.scriptNonce ? `script-src 'nonce-${options.scriptNonce}'; ` : ""}frame-ancestors 'none'`,
2059
+ "Content-Security-Policy": `default-src 'none'; style-src 'unsafe-inline'; font-src 'self'; ${options.scriptNonce ? `script-src 'nonce-${options.scriptNonce}'${options.captcha ? ` ${captchaOrigin}` : ""}; ` : ""}${options.captcha ? `frame-src ${captchaOrigin}; connect-src ${captchaOrigin}; ` : ""}frame-ancestors 'none'`,
1930
2060
  "X-Frame-Options": "DENY",
1931
2061
  // No other site sees these pages' URLs. Not no-referrer: under it a form
1932
2062
  // posts Origin: null, which an http gateway (sent no Sec-Fetch-Site) refuses.
@@ -1983,10 +2113,12 @@ input[type=checkbox]:checked::after{content:"";width:9px;height:5px;margin-top:-
1983
2113
  .step{display:flex;gap:12px;margin:0 0 20px}.step>div{flex:1;min-width:0}.step p,.step label{display:block;color:var(--muted);margin:0 0 10px}
1984
2114
  .n{flex:none;display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;border-radius:4px;background:rgba(237,237,237,.07);color:var(--muted);font-size:12px}
1985
2115
  .field{display:block;font-size:13px;font-weight:550;margin:0 0 8px}
1986
- input[type=text],input[type=password]{display:block;width:100%;height:36px;padding:0 12px;border:1px solid var(--edge);border-radius:6px;background:var(--page);color:var(--ink);font:13px "Geist Mono",ui-monospace,SFMono-Regular,Menlo,monospace}
2116
+ input[type=text],input[type=password],input[type=tel]{display:block;width:100%;height:36px;padding:0 12px;border:1px solid var(--edge);border-radius:6px;background:var(--page);color:var(--ink);font:13px "Geist Mono",ui-monospace,SFMono-Regular,Menlo,monospace}
1987
2117
  input::placeholder{color:var(--faint);font-family:Geist,ui-sans-serif,system-ui,sans-serif}
1988
- input[type=text]:focus-visible,input[type=password]:focus-visible{outline:1px solid var(--mint);border-color:var(--mint)}
2118
+ input[type=text]:focus-visible,input[type=password]:focus-visible,input[type=tel]:focus-visible{outline:1px solid var(--mint);border-color:var(--mint)}
1989
2119
  .hint{color:var(--faint);font-size:12px;margin:10px 0 0}
2120
+ .phone{display:flex;gap:8px}.phone input:first-child{flex:none;width:72px}.phone input:last-child{flex:1;min-width:0}
2121
+ .cf-turnstile{margin:16px 0 0}
1990
2122
  .code{margin:0 0 16px;padding:18px 12px;border:1px solid var(--rule);border-radius:8px;background:rgba(237,237,237,.03);color:var(--ink);font:550 20px "Geist Mono",ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.1em;text-align:center;user-select:all}
1991
2123
  .wait{display:flex;align-items:center;gap:10px;font-size:13px}
1992
2124
  .spin{flex:none;width:14px;height:14px;border:2px solid var(--edge);border-top-color:var(--ink);border-radius:50%;animation:spin .8s linear infinite}
@@ -2000,6 +2132,7 @@ input[type=text]:focus-visible,input[type=password]:focus-visible{outline:1px so
2000
2132
  .meter{display:flex;flex-wrap:wrap;align-items:baseline;gap:0 8px}.meter small{flex:1;min-width:0}
2001
2133
  .pct{flex:none;color:var(--muted);font-size:12px;font-variant-numeric:tabular-nums}.full .pct{color:#e5484d}
2002
2134
  .bar{flex:0 0 100%;height:4px;margin:8px 0 2px;border-radius:999px;background:rgba(237,237,237,.08);overflow:hidden}.bar>span{display:block;height:100%;border-radius:999px;background:var(--mint)}.full .bar>span{background:#d64548}
2135
+ .link-alt{display:block;margin:12px auto 0;padding:4px 8px;border:0;background:none;font:inherit;font-size:13px;color:var(--muted);cursor:pointer}.link-alt:hover{color:var(--ink);text-decoration:underline;text-underline-offset:3px}
2003
2136
  .actions{display:flex;justify-content:space-between;margin:4px -8px 0}.actions .btn.ghost{margin:0}.actions span{display:flex}
2004
2137
  .fine{color:var(--faint);font-size:12px;margin:12px 0 0;text-align:center}
2005
2138
  .card:has(details[open]) .logos{display:none}
@@ -306,6 +306,22 @@ export type LinkSignIn = {
306
306
  state: string;
307
307
  issuedAt: number;
308
308
  } | null>;
309
+ /** Sign-in by text message on the page itself; the page offers it only when present. */
310
+ phone?: LinkPhoneSignIn;
311
+ };
312
+ /**
313
+ * Sign-in by a code the platform texts to an E.164 number. Each throws
314
+ * HttpError 400 (wrong or expired code, a number it cannot text) or 429 with a
315
+ * message the page shows the user.
316
+ */
317
+ export type LinkPhoneSignIn = {
318
+ /** The Cloudflare Turnstile site key the page shows a challenge for; null for none. */
319
+ captchaSiteKey(): string | null;
320
+ /** The caller's address as the platform's proxy saw it, to limit texts per caller; null when unknown. */
321
+ callerAddress(request: Request): string | null;
322
+ sendCode(phone: string, captchaToken?: string): Promise<void>;
323
+ /** The Link subject of the number's user, made on their first sign-in. */
324
+ verifyCode(phone: string, code: string): Promise<string>;
309
325
  };
310
326
  /** A plan or API key the user added, and who they are now. */
311
327
  export type LinkPlanAdded = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mupt-ai/dari-gateway",
3
- "version": "1.0.376",
3
+ "version": "1.0.378",
4
4
  "description": "Self-hostable LLM gateway for coding agents and APIs: one endpoint for Anthropic Messages, OpenAI Chat Completions, and OpenAI Responses, with subscription pooling, failover, and prompt-cache-aware routing.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -52,7 +52,7 @@
52
52
  },
53
53
  "dependencies": {
54
54
  "@aws-sdk/client-sts": "3.1063.0",
55
- "@mupt-ai/dari-router": "1.0.376",
55
+ "@mupt-ai/dari-router": "1.0.378",
56
56
  "@mupt-ai/pi-ai": "1.5.2-mupt.3"
57
57
  },
58
58
  "devDependencies": {
@@ -79,6 +79,7 @@ import type {
79
79
  LinkUsageTotals,
80
80
  LinkUsageWindow,
81
81
  LinkPlatform,
82
+ LinkPhoneSignIn,
82
83
  LinkSignIn,
83
84
  LinkBudget,
84
85
  LinkBudgetStanding,
@@ -1331,7 +1332,7 @@ async function authorizePage(link: LinkPlatform, request: Request, params: URLSe
1331
1332
  async function homePage(approval: LinkApprovalPage, authorize: AuthorizeRequest, session: Session | null): Promise<Response> {
1332
1333
  const current = await grantToUpdate(approval, authorize, session);
1333
1334
  if (current instanceof Response) return current;
1334
- if (session === null) return introPage(approval, authorize);
1335
+ if (session === null) return introPage(approval, authorize, approval.signIn?.phone === undefined ? undefined : {});
1335
1336
  const subscriptions = await approval.subscriptions(session.subject);
1336
1337
  return shareable(authorize, subscriptions).length > 0
1337
1338
  ? choosePage(authorize, session, subscriptions, current)
@@ -1367,7 +1368,10 @@ async function authorizeSubmit(link: LinkPlatform, request: Request, form: URLSe
1367
1368
  const secret = approval.sessionSecret();
1368
1369
  const session = sessionFrom(request, approval);
1369
1370
  if (session === null && approval.signIn !== undefined && !["deny", "sign_out"].includes(form.get("decision") ?? "")) {
1370
- return signIn(request, approval.signIn, secret, `${AUTHORIZE_PATH}?${authorizeQuery(authorize)}`);
1371
+ const phone = approval.signIn.phone;
1372
+ return phone === undefined || form.get("decision") === "sign_in"
1373
+ ? signIn(request, approval.signIn, secret, `${AUTHORIZE_PATH}?${authorizeQuery(authorize)}`)
1374
+ : await phoneSignIn(request, approval, phone, authorize, form);
1371
1375
  }
1372
1376
  const endConnect = clearCookie(request, CONNECT_COOKIE);
1373
1377
  // A plan's or a key provider's row on the select page is its own submit button.
@@ -1879,7 +1883,98 @@ const KINDS: Record<SubscriptionKind, { name: string; plan: string; at: string;
1879
1883
  };
1880
1884
 
1881
1885
  // The first page a new user sees: what connecting means, and one button.
1882
- function introPage(approval: LinkApprovalPage, authorize: AuthorizeRequest): Response {
1886
+ // Signing in by text message, on the intro card: a number, then the code
1887
+ // sent to it. A right code makes the browser that number's user.
1888
+ async function phoneSignIn(
1889
+ request: Request,
1890
+ approval: LinkApprovalPage,
1891
+ phone: LinkPhoneSignIn,
1892
+ authorize: AuthorizeRequest,
1893
+ form: URLSearchParams,
1894
+ ): Promise<Response> {
1895
+ const decision = form.get("decision");
1896
+ const number = phoneNumber(form);
1897
+ if (decision === "send_code" || decision === "resend") {
1898
+ if (number === null) return introPage(approval, authorize, { error: "Enter your phone number with its country code." });
1899
+ const keys = [`n:${number}`, ...[phone.callerAddress(request)].filter((a) => a !== null).map((a) => `a:${a}`)];
1900
+ const throttled = phoneThrottle.take(keys);
1901
+ if (throttled !== null) return introPage(approval, authorize, decision === "resend" ? { number, error: throttled } : { error: throttled });
1902
+ try {
1903
+ await phone.sendCode(number, form.get("cf-turnstile-response") || undefined);
1904
+ } catch (error) {
1905
+ phoneThrottle.release(keys);
1906
+ if (!userFacing(error)) throw error;
1907
+ return introPage(approval, authorize, decision === "resend" ? { number, error: error.message } : { error: error.message });
1908
+ }
1909
+ return introPage(approval, authorize, { number });
1910
+ }
1911
+ if (decision === "verify_code" && number !== null) {
1912
+ const code = form.get("code")?.replace(/\s/g, "") ?? "";
1913
+ if (!/^\d{6}$/.test(code)) return introPage(approval, authorize, { number, error: "Enter the 6-digit code we sent you." });
1914
+ let subject: string;
1915
+ try {
1916
+ subject = await phone.verifyCode(number, code);
1917
+ } catch (error) {
1918
+ if (!userFacing(error)) throw error;
1919
+ return introPage(approval, authorize, { number, error: error.message });
1920
+ }
1921
+ return seeAuthorize(authorize, [userCookie(request, approval, subject)]);
1922
+ }
1923
+ return introPage(approval, authorize, {});
1924
+ }
1925
+
1926
+ // The number as E.164: the country code and the number typed, or a whole
1927
+ // number posted back from the code step.
1928
+ function phoneNumber(form: URLSearchParams): string | null {
1929
+ const digits = (value: string | null) => (value ?? "").replace(/[\s().-]/g, "");
1930
+ const whole = form.get("phone") !== null
1931
+ ? digits(form.get("phone"))
1932
+ : `+${digits(form.get("country")).replace(/^\+/, "")}${digits(form.get("number"))}`;
1933
+ return /^\+[1-9]\d{6,14}$/.test(whole) ? whole : null;
1934
+ }
1935
+
1936
+ function userFacing(error: unknown): error is HttpError {
1937
+ return error instanceof HttpError && (error.status === 400 || error.status === 429);
1938
+ }
1939
+
1940
+ // Texts cost money and can harass a number, so a number gets five codes an
1941
+ // hour and one a minute, and a caller ten an hour. A text is counted before it
1942
+ // goes, so parallel requests cannot burst past, and given back if it fails.
1943
+ // Per instance, in memory.
1944
+ class PhoneThrottle {
1945
+ private readonly times = new Map<string, number[]>();
1946
+
1947
+ take(keys: string[], now = Date.now()): string | null {
1948
+ const [number, ...callers] = keys.map((key) => this.recent(key, now));
1949
+ if (number!.some((at) => now - at < 60 * 1000)) return "We just sent a code. Wait a minute before asking for another.";
1950
+ if (number!.length >= 5 || callers.some((times) => times.length >= 10)) return "Too many codes requested. Try again later.";
1951
+ if (this.times.size > 10_000) {
1952
+ for (const [key, times] of this.times) if (times.every((at) => now - at >= 60 * 60 * 1000)) this.times.delete(key);
1953
+ }
1954
+ for (const key of keys) this.times.set(key, [...this.recent(key, now), now]);
1955
+ return null;
1956
+ }
1957
+
1958
+ release(keys: string[]): void {
1959
+ for (const key of keys) this.times.set(key, (this.times.get(key) ?? []).slice(0, -1));
1960
+ }
1961
+
1962
+ private recent(key: string, now: number): number[] {
1963
+ return (this.times.get(key) ?? []).filter((at) => now - at < 60 * 60 * 1000);
1964
+ }
1965
+ }
1966
+
1967
+ const phoneThrottle = new PhoneThrottle();
1968
+
1969
+ const TURNSTILE_SCRIPT = "https://challenges.cloudflare.com/turnstile/v0/api.js";
1970
+
1971
+ // The intro card. On a platform with phone sign-in, a signed-out user enters
1972
+ // their number here (`phone` without `number`), then the code texted to it.
1973
+ function introPage(
1974
+ approval: LinkApprovalPage,
1975
+ authorize: AuthorizeRequest,
1976
+ phone?: { number?: string; error?: string },
1977
+ ): Response {
1883
1978
  const app = escapeHtml(authorize.app.name);
1884
1979
  const kinds = connectKinds(approval, authorize);
1885
1980
  const keys = keyProviders(approval, authorize);
@@ -1892,6 +1987,45 @@ function introPage(approval: LinkApprovalPage, authorize: AuthorizeRequest): Res
1892
1987
  }
1893
1988
  const names = [...kinds.map((kind) => KINDS[kind].name), ...(keys.length > 0 ? ["an API key"] : [])];
1894
1989
  const ways = names.length > 1 ? `${names.slice(0, -1).join(", ")} or ${names.at(-1)}` : names[0]!;
1990
+ const pair = `<div class="pair"><span class="tile">${escapeHtml(authorize.app.name.trim().charAt(0).toUpperCase())}</span><span class="join"></span>${DARI_MARK}</div>`;
1991
+ const sms = approval.signIn?.phone;
1992
+ if (phone !== undefined && sms !== undefined) {
1993
+ const siteKey = sms.captchaSiteKey();
1994
+ const captcha = siteKey === null ? "" : `<div class="cf-turnstile" data-sitekey="${escapeHtml(siteKey)}" data-theme="dark" data-size="flexible"></div>`;
1995
+ if (phone.number !== undefined) {
1996
+ return pane(authorize, {
1997
+ title: `Connect ${authorize.app.name}`,
1998
+ step: "connect_subscription",
1999
+ error: phone.error,
2000
+ captcha: siteKey !== null,
2001
+ body: `${pair}
2002
+ <h1 class="lead">Enter Your Code</h1>
2003
+ <p class="returns">Sent to ${escapeHtml(phone.number)}</p>
2004
+ <input type="hidden" name="phone" value="${escapeHtml(phone.number)}">
2005
+ <label class="field" for="code">Code</label>
2006
+ <input id="code" type="text" name="code" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6" placeholder="123456" required autofocus>
2007
+ ${captcha}`,
2008
+ // The main button comes first, so Enter submits it.
2009
+ footer: `<button class="btn primary" type="submit" name="decision" value="verify_code">Continue</button>
2010
+ <div class="actions"><button class="btn ghost" type="submit" name="decision" value="resend" formnovalidate>Resend Code</button><button class="btn ghost" type="submit" name="decision" value="change_number" formnovalidate>Change Number</button></div>`,
2011
+ });
2012
+ }
2013
+ return pane(authorize, {
2014
+ title: `Connect ${authorize.app.name}`,
2015
+ step: "connect_subscription",
2016
+ error: phone.error,
2017
+ captcha: siteKey !== null,
2018
+ body: `${pair}
2019
+ <h1 class="lead">${app} Uses Dari To Connect Your AI ${kinds.length > 0 ? "Subscriptions" : "API Keys"}</h1>
2020
+ <p class="returns">Returns to ${escapeHtml(new URL(authorize.redirectUri).host)}</p>
2021
+ <label class="field" for="number">Phone Number</label>
2022
+ <div class="phone"><input id="country" type="tel" name="country" aria-label="Country Code" inputmode="tel" value="+1" maxlength="5" required><input id="number" name="number" type="tel" inputmode="tel" autocomplete="tel-national" placeholder="Phone Number" required autofocus></div>
2023
+ <p class="hint">We text you a code to sign in. Message and data rates may apply.</p>
2024
+ ${captcha}`,
2025
+ footer: `<button class="btn primary" type="submit" name="decision" value="send_code">Continue</button>
2026
+ <button class="link-alt" type="submit" name="decision" value="sign_in" formnovalidate>Use Another Way</button>`,
2027
+ });
2028
+ }
1895
2029
  return pane(authorize, {
1896
2030
  title: `Connect ${authorize.app.name}`,
1897
2031
  step: "connect_subscription",
@@ -2115,6 +2249,8 @@ function pane(
2115
2249
  error?: string;
2116
2250
  cookies?: string[];
2117
2251
  refresh?: number;
2252
+ // The page shows a Cloudflare Turnstile challenge.
2253
+ captcha?: boolean;
2118
2254
  },
2119
2255
  ): Response {
2120
2256
  return page(
@@ -2129,14 +2265,14 @@ ${options.footer === undefined ? "" : `<div class="foot">${options.footer}</div>
2129
2265
  ${options.back === undefined ? "" : `<button class="nav back" type="submit" name="decision" value="${options.back}" formnovalidate aria-label="Back">${ICONS.back}</button>`}
2130
2266
  <button class="nav close" type="submit" name="decision" value="deny" formnovalidate aria-label="Close">${ICONS.close}</button>
2131
2267
  </form>`,
2132
- { cookies: options.cookies, event: eventFor(authorize, options.step), refresh: options.refresh },
2268
+ { cookies: options.cookies, event: eventFor(authorize, options.step), refresh: options.refresh, captcha: options.captcha },
2133
2269
  );
2134
2270
  }
2135
2271
 
2136
2272
  function page(
2137
2273
  title: string,
2138
2274
  body: string,
2139
- options: { status?: number; cookies?: string[]; scriptNonce?: string; event?: PageEvent; refresh?: number } = {},
2275
+ options: { status?: number; cookies?: string[]; scriptNonce?: string; event?: PageEvent; refresh?: number; captcha?: boolean } = {},
2140
2276
  ): Response {
2141
2277
  // Every page: a pressed button shows it is working until the next page loads.
2142
2278
  const busyNonce = options.scriptNonce ?? randomUUID();
@@ -2159,6 +2295,8 @@ document.addEventListener("change", (event) => {
2159
2295
  if (window.opener) window.opener.postMessage(event, eventOrigin);</script>`;
2160
2296
  options = { ...options, scriptNonce: nonce };
2161
2297
  }
2298
+ if (options.captcha) body += `\n<script nonce="${options.scriptNonce}" src="${TURNSTILE_SCRIPT}" async defer></script>`;
2299
+ const captchaOrigin = new URL(TURNSTILE_SCRIPT).origin;
2162
2300
  const html = `<!doctype html>
2163
2301
  <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
2164
2302
  ${options.refresh === undefined ? "" : `<meta http-equiv="refresh" content="${options.refresh}">\n`}<title>${escapeHtml(title)}</title>
@@ -2169,7 +2307,7 @@ ${body}
2169
2307
  const headers = new Headers({
2170
2308
  "Content-Type": "text/html; charset=utf-8",
2171
2309
  "Cache-Control": "no-store",
2172
- "Content-Security-Policy": `default-src 'none'; style-src 'unsafe-inline'; font-src 'self'; ${options.scriptNonce ? `script-src 'nonce-${options.scriptNonce}'; ` : ""}frame-ancestors 'none'`,
2310
+ "Content-Security-Policy": `default-src 'none'; style-src 'unsafe-inline'; font-src 'self'; ${options.scriptNonce ? `script-src 'nonce-${options.scriptNonce}'${options.captcha ? ` ${captchaOrigin}` : ""}; ` : ""}${options.captcha ? `frame-src ${captchaOrigin}; connect-src ${captchaOrigin}; ` : ""}frame-ancestors 'none'`,
2173
2311
  "X-Frame-Options": "DENY",
2174
2312
  // No other site sees these pages' URLs. Not no-referrer: under it a form
2175
2313
  // posts Origin: null, which an http gateway (sent no Sec-Fetch-Site) refuses.
@@ -2226,10 +2364,12 @@ input[type=checkbox]:checked::after{content:"";width:9px;height:5px;margin-top:-
2226
2364
  .step{display:flex;gap:12px;margin:0 0 20px}.step>div{flex:1;min-width:0}.step p,.step label{display:block;color:var(--muted);margin:0 0 10px}
2227
2365
  .n{flex:none;display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;border-radius:4px;background:rgba(237,237,237,.07);color:var(--muted);font-size:12px}
2228
2366
  .field{display:block;font-size:13px;font-weight:550;margin:0 0 8px}
2229
- input[type=text],input[type=password]{display:block;width:100%;height:36px;padding:0 12px;border:1px solid var(--edge);border-radius:6px;background:var(--page);color:var(--ink);font:13px "Geist Mono",ui-monospace,SFMono-Regular,Menlo,monospace}
2367
+ input[type=text],input[type=password],input[type=tel]{display:block;width:100%;height:36px;padding:0 12px;border:1px solid var(--edge);border-radius:6px;background:var(--page);color:var(--ink);font:13px "Geist Mono",ui-monospace,SFMono-Regular,Menlo,monospace}
2230
2368
  input::placeholder{color:var(--faint);font-family:Geist,ui-sans-serif,system-ui,sans-serif}
2231
- input[type=text]:focus-visible,input[type=password]:focus-visible{outline:1px solid var(--mint);border-color:var(--mint)}
2369
+ input[type=text]:focus-visible,input[type=password]:focus-visible,input[type=tel]:focus-visible{outline:1px solid var(--mint);border-color:var(--mint)}
2232
2370
  .hint{color:var(--faint);font-size:12px;margin:10px 0 0}
2371
+ .phone{display:flex;gap:8px}.phone input:first-child{flex:none;width:72px}.phone input:last-child{flex:1;min-width:0}
2372
+ .cf-turnstile{margin:16px 0 0}
2233
2373
  .code{margin:0 0 16px;padding:18px 12px;border:1px solid var(--rule);border-radius:8px;background:rgba(237,237,237,.03);color:var(--ink);font:550 20px "Geist Mono",ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.1em;text-align:center;user-select:all}
2234
2374
  .wait{display:flex;align-items:center;gap:10px;font-size:13px}
2235
2375
  .spin{flex:none;width:14px;height:14px;border:2px solid var(--edge);border-top-color:var(--ink);border-radius:50%;animation:spin .8s linear infinite}
@@ -2243,6 +2383,7 @@ input[type=text]:focus-visible,input[type=password]:focus-visible{outline:1px so
2243
2383
  .meter{display:flex;flex-wrap:wrap;align-items:baseline;gap:0 8px}.meter small{flex:1;min-width:0}
2244
2384
  .pct{flex:none;color:var(--muted);font-size:12px;font-variant-numeric:tabular-nums}.full .pct{color:#e5484d}
2245
2385
  .bar{flex:0 0 100%;height:4px;margin:8px 0 2px;border-radius:999px;background:rgba(237,237,237,.08);overflow:hidden}.bar>span{display:block;height:100%;border-radius:999px;background:var(--mint)}.full .bar>span{background:#d64548}
2386
+ .link-alt{display:block;margin:12px auto 0;padding:4px 8px;border:0;background:none;font:inherit;font-size:13px;color:var(--muted);cursor:pointer}.link-alt:hover{color:var(--ink);text-decoration:underline;text-underline-offset:3px}
2246
2387
  .actions{display:flex;justify-content:space-between;margin:4px -8px 0}.actions .btn.ghost{margin:0}.actions span{display:flex}
2247
2388
  .fine{color:var(--faint);font-size:12px;margin:12px 0 0;text-align:center}
2248
2389
  .card:has(details[open]) .logos{display:none}
@@ -288,6 +288,23 @@ export type LinkSignIn = {
288
288
  signOutUrl(): string;
289
289
  /** Who a ticket signed in, for which state, and when (epoch ms); null for no ticket. */
290
290
  redeem(ticket: string): Promise<{ subject: string; state: string; issuedAt: number } | null>;
291
+ /** Sign-in by text message on the page itself; the page offers it only when present. */
292
+ phone?: LinkPhoneSignIn;
293
+ };
294
+
295
+ /**
296
+ * Sign-in by a code the platform texts to an E.164 number. Each throws
297
+ * HttpError 400 (wrong or expired code, a number it cannot text) or 429 with a
298
+ * message the page shows the user.
299
+ */
300
+ export type LinkPhoneSignIn = {
301
+ /** The Cloudflare Turnstile site key the page shows a challenge for; null for none. */
302
+ captchaSiteKey(): string | null;
303
+ /** The caller's address as the platform's proxy saw it, to limit texts per caller; null when unknown. */
304
+ callerAddress(request: Request): string | null;
305
+ sendCode(phone: string, captchaToken?: string): Promise<void>;
306
+ /** The Link subject of the number's user, made on their first sign-in. */
307
+ verifyCode(phone: string, code: string): Promise<string>;
291
308
  };
292
309
 
293
310
  /** A plan or API key the user added, and who they are now. */