create-ailk 0.34.1 → 0.36.0

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.
Files changed (139) hide show
  1. package/README.md +1 -1
  2. package/component-catalog.json +37 -4
  3. package/component-catalog.md +11 -9
  4. package/dist/add-module.js +7 -2
  5. package/dist/derive-architecture.js +2 -0
  6. package/dist/index.d.ts +1 -1
  7. package/dist/index.js +1 -1
  8. package/dist/lib/env-catalog.js +8 -0
  9. package/dist/module-architecture.js +9 -0
  10. package/dist/programmatic.js +5 -2
  11. package/dist/site-listing-path.d.ts +8 -0
  12. package/dist/site-listing-path.js +8 -0
  13. package/dist/surfaces.d.ts +20 -0
  14. package/dist/surfaces.js +32 -3
  15. package/dist/template-record.js +2 -0
  16. package/dist/topology.d.ts +4 -4
  17. package/dist/topology.js +104 -60
  18. package/dist/update.js +11 -0
  19. package/package.json +3 -3
  20. package/templates/.env.example +21 -0
  21. package/templates/apps/api/.env.example +7 -0
  22. package/templates/apps/api/CLAUDE.md +14 -9
  23. package/templates/apps/mcp/CLAUDE.md +18 -7
  24. package/templates/apps/web/.env.example +16 -0
  25. package/templates/apps/web/CLAUDE.md +46 -5
  26. package/templates/apps/web/app/[locale]/(auth)/__tests__/password-reset.test.tsx +2 -0
  27. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/page.test.tsx +52 -1
  28. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/remembered-method.test.ts +43 -0
  29. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/sign-in-card.test.tsx +108 -1
  30. package/templates/apps/web/app/[locale]/(auth)/sign-in/page.tsx +36 -3
  31. package/templates/apps/web/app/[locale]/(auth)/sign-in/remembered-method.ts +37 -0
  32. package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-card.tsx +90 -33
  33. package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-text.ts +9 -4
  34. package/templates/apps/web/app/[locale]/(authed)/__tests__/gate.test.tsx +79 -348
  35. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/billing.test.tsx +12 -1
  36. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/hub-mode.test.tsx +55 -2
  37. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/item.test.tsx +43 -0
  38. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/layout-sign-out.test.tsx +10 -5
  39. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/page.test.tsx +6 -5
  40. package/templates/apps/web/app/[locale]/(authed)/account/account-frame.tsx +1 -1
  41. package/templates/apps/web/app/[locale]/(authed)/account/billing/page.tsx +60 -6
  42. package/templates/apps/web/app/[locale]/(authed)/account/billing-source.ts +32 -3
  43. package/templates/apps/web/app/[locale]/(authed)/account/connect/__tests__/page.test.tsx +8 -1
  44. package/templates/apps/web/app/[locale]/(authed)/account/connect/page.tsx +7 -3
  45. package/templates/apps/web/app/[locale]/(authed)/account/general/__tests__/phone-verification.test.tsx +215 -0
  46. package/templates/apps/web/app/[locale]/(authed)/account/general/__tests__/seam-imports.test.ts +65 -0
  47. package/templates/apps/web/app/[locale]/(authed)/account/general/page.tsx +47 -0
  48. package/templates/apps/web/app/[locale]/(authed)/account/general/phone-actions.ts +122 -0
  49. package/templates/apps/web/app/[locale]/(authed)/account/general/phone-verification.tsx +214 -0
  50. package/templates/apps/web/app/[locale]/(authed)/account/inbox/[kind]/[id]/page.tsx +6 -1
  51. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/__tests__/invitation-id.test.ts +35 -0
  52. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/__tests__/page.test.tsx +266 -0
  53. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/actions.ts +116 -0
  54. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/invitation-id.ts +12 -0
  55. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/page.tsx +154 -0
  56. package/templates/apps/web/app/[locale]/(authed)/account/layout.tsx +6 -4
  57. package/templates/apps/web/app/[locale]/(authed)/account/security/page.tsx +3 -1
  58. package/templates/apps/web/app/[locale]/(authed)/layout.tsx +15 -13
  59. package/templates/apps/web/app/[locale]/(authed)/signed-out-gate.generated.tsx +20 -52
  60. package/templates/apps/web/app/[locale]/flows/[slug]/FlowStepperClient.tsx +43 -4
  61. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.deliverable.test.tsx +23 -9
  62. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.invite.test.tsx +15 -0
  63. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.permalink.test.tsx +74 -0
  64. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.test.tsx +34 -1
  65. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/magnet-page.test.tsx +257 -4
  66. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/save.actions.test.ts +72 -92
  67. package/templates/apps/web/app/[locale]/flows/[slug]/email-moment.ts +2 -2
  68. package/templates/apps/web/app/[locale]/flows/[slug]/magnet-page.tsx +164 -65
  69. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/LevelChart.tsx +100 -0
  70. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/ResultsCard.tsx +99 -0
  71. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/ResultsClient.tsx +415 -253
  72. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/ResultsEmailStep.tsx +113 -32
  73. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/ResultsClient.no-commerce.test.tsx +16 -17
  74. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/ResultsClient.report.test.tsx +284 -0
  75. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/by-result.test.tsx +52 -19
  76. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/cards.test.tsx +402 -0
  77. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/page.test.tsx +100 -12
  78. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/score.test.tsx +153 -101
  79. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/meeting-seam.ts +36 -0
  80. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/page.tsx +121 -33
  81. package/templates/apps/web/app/[locale]/flows/[slug]/save.actions.ts +27 -17
  82. package/templates/apps/web/app/[locale]/flows/[slug]/served-flow.ts +91 -0
  83. package/templates/apps/web/app/[locale]/layout.tsx +42 -76
  84. package/templates/apps/web/app/[locale]/purchase/__tests__/success.test.tsx +50 -0
  85. package/templates/apps/web/app/[locale]/purchase/success/page.tsx +48 -7
  86. package/templates/apps/web/app/api/auth/hub/__tests__/entry-routes.test.ts +749 -0
  87. package/templates/apps/web/app/api/auth/hub/authorize/__tests__/route.test.ts +189 -6
  88. package/templates/apps/web/app/api/auth/hub/authorize/route.ts +101 -31
  89. package/templates/apps/web/app/api/auth/hub/continuation.ts +51 -2
  90. package/templates/apps/web/app/api/auth/hub/email/route.ts +111 -0
  91. package/templates/apps/web/app/api/auth/hub/entry-shared.ts +163 -0
  92. package/templates/apps/web/app/api/auth/hub/purchase/route.ts +230 -0
  93. package/templates/apps/web/app/api/auth/hub/purchase-link/route.ts +174 -0
  94. package/templates/apps/web/app/api/auth/hub/sign-up/route.ts +60 -0
  95. package/templates/apps/web/app/api/auth/hub/sign-up-evidence.ts +97 -0
  96. package/templates/apps/web/app/api/hub-session/__tests__/routes.test.ts +475 -7
  97. package/templates/apps/web/app/api/hub-session/callback/route.ts +13 -47
  98. package/templates/apps/web/app/api/hub-session/email/route.ts +125 -0
  99. package/templates/apps/web/app/api/hub-session/one-tap/nonce/route.ts +49 -0
  100. package/templates/apps/web/app/api/hub-session/one-tap/route.ts +106 -0
  101. package/templates/apps/web/app/api/hub-session/open/route.ts +111 -0
  102. package/templates/apps/web/app/api/hub-session/sign-in/route.ts +23 -40
  103. package/templates/apps/web/app/api/hub-session/sign-out/route.ts +1 -10
  104. package/templates/apps/web/app/llms.txt/__tests__/site-listing.test.ts +122 -0
  105. package/templates/apps/web/app/llms.txt/route.ts +14 -2
  106. package/templates/apps/web/app/sitemap.xml/__tests__/site-listing.test.ts +98 -0
  107. package/templates/apps/web/app/sitemap.xml/route.ts +13 -2
  108. package/templates/apps/web/auth.ts +133 -6
  109. package/templates/apps/web/components/sign-out-trigger.tsx +1 -1
  110. package/templates/apps/web/lib/__tests__/auth-email.test.ts +141 -0
  111. package/templates/apps/web/lib/__tests__/auth-phone.test.ts +445 -0
  112. package/templates/apps/web/lib/__tests__/auth-sms.test.ts +140 -0
  113. package/templates/apps/web/lib/__tests__/fixtures/tsconfig.flow.json +18 -0
  114. package/templates/apps/web/lib/__tests__/site-header.test.ts +13 -0
  115. package/templates/apps/web/lib/__tests__/telemetry-scrub.test.ts +19 -1
  116. package/templates/apps/web/lib/account-config.ts +24 -9
  117. package/templates/apps/web/lib/auth-email.ts +62 -6
  118. package/templates/apps/web/lib/auth-env.ts +13 -0
  119. package/templates/apps/web/lib/auth-sms.ts +180 -0
  120. package/templates/apps/web/lib/hub-session/__tests__/hub-session.test.ts +28 -0
  121. package/templates/apps/web/lib/hub-session/__tests__/spoke-sign-in.test.tsx +332 -0
  122. package/templates/apps/web/lib/hub-session/config.ts +7 -1
  123. package/templates/apps/web/lib/hub-session/entry.ts +238 -0
  124. package/templates/apps/web/lib/hub-session/index.ts +1 -4
  125. package/templates/apps/web/lib/hub-session/one-tap.tsx +148 -0
  126. package/templates/apps/web/lib/hub-session/session.ts +120 -2
  127. package/templates/apps/web/lib/hub-session/spoke-sign-in.tsx +277 -0
  128. package/templates/apps/web/lib/site-header.ts +14 -1
  129. package/templates/apps/web/lib/site-listing.ts +7 -0
  130. package/templates/apps/web/lib/telemetry-scrub.ts +11 -0
  131. package/templates/apps/web/lib/topology.generated.ts +39 -0
  132. package/templates/apps/web/messages/en.json +125 -21
  133. package/templates/apps/web/middleware.ts +34 -2
  134. package/templates/apps/web/security-headers.config.ts +21 -0
  135. package/versions.json +47 -47
  136. package/templates/apps/web/app/[locale]/(authed)/sign-in-gate.tsx +0 -162
  137. package/templates/apps/web/components/signed-in-nav.tsx +0 -79
  138. package/templates/apps/web/lib/hub-session/__tests__/sign-in-gate.test.tsx +0 -180
  139. package/templates/apps/web/lib/hub-session/sign-in-gate.tsx +0 -162
@@ -22,17 +22,25 @@
22
22
  * #9966 D2 (AC-4): a person who has not said yes to the spoke is sent to the
23
23
  * hub's consent page with a sealed ref; only that page's same-origin POST
24
24
  * sends `consent: true` — the GET a spoke can trigger on page load never does.
25
+ *
26
+ * #11096 D4 (AC-3): a single `provider_hint=google` with no session and Google
27
+ * on goes straight to Google through `auth.api.signInSocial`, carrying the
28
+ * state cookie Better Auth set; anything else is today's `/sign-in` redirect.
25
29
  */
26
30
 
27
31
  // --- Mocks set up BEFORE imports ---
28
32
 
29
33
  const mockGetSession = jest.fn();
34
+ const mockSignInSocial = jest.fn();
30
35
  const mockSecret = "k".repeat(43);
31
36
  // eslint-disable-next-line no-restricted-syntax -- auth.ts is the Better Auth singleton (its adapter needs a live database); this stand-in for the session read is the repo-standard double for that boundary (see the sibling suites under app/[locale]/(authed)/account/__tests__).
32
37
  jest.mock("../../../../../../auth", () => ({
33
38
  __esModule: true,
34
39
  auth: {
35
- api: { getSession: (...args: unknown[]) => mockGetSession(...args) },
40
+ api: {
41
+ getSession: (...args: unknown[]) => mockGetSession(...args),
42
+ signInSocial: (...args: unknown[]) => mockSignInSocial(...args),
43
+ },
36
44
  },
37
45
  resolveSecret: () => mockSecret,
38
46
  }));
@@ -640,7 +648,7 @@ describe("the consent step (#9966 D2, AC-4)", () => {
640
648
  expect("x-internal-auth" in init.headers).toBe(false);
641
649
  });
642
650
 
643
- it("POST: a same-origin Continue mints with consent: true and 303s to the registered URI with code and state", async () => {
651
+ it("POST: a same-origin Continue mints with consent: true and answers a 200 page that navigates to the registered URI with code and state — never a 303, which Chrome blocks under form-action 'self' (#11091)", async () => {
644
652
  mockGetSession.mockResolvedValue({ user: { id: "u1" } });
645
653
  mockCreateCode.mockResolvedValue({
646
654
  ok: true,
@@ -649,11 +657,16 @@ describe("the consent step (#9966 D2, AC-4)", () => {
649
657
 
650
658
  const res = await POST(post([ref()]));
651
659
 
652
- expect(res.status).toBe(303);
653
- expect(res.headers.get("location")).toBe(
654
- `${SPOKE_CALLBACK}?code=${CODE}&state=${STATE}`,
655
- );
660
+ expect(res.status).toBe(200);
661
+ expect(res.headers.get("location")).toBeNull();
662
+ expect(res.headers.get("content-type")).toBe("text/html; charset=utf-8");
663
+ expect(res.headers.get("cache-control")).toBe("no-store");
656
664
  expect(res.headers.get("referrer-policy")).toBe("no-referrer");
665
+ const html = await res.text();
666
+ const target = `${SPOKE_CALLBACK}?code=${CODE}&state=${STATE}`;
667
+ expect(html).toContain(`<meta http-equiv="refresh" content="0;url=${target}">`);
668
+ expect(html).toContain(`<a href="${target}">`);
669
+ expect(html).toContain(`<meta name="referrer" content="no-referrer">`);
657
670
  expect(mockCreateCode).toHaveBeenCalledWith(
658
671
  {
659
672
  clientId: "spoke_abc",
@@ -687,6 +700,30 @@ describe("the consent step (#9966 D2, AC-4)", () => {
687
700
  expect(init.headers["x-internal-auth"]).toBe("internal-secret");
688
701
  });
689
702
 
703
+ it("POST: a hub that holds its own spoke key still carries x-internal-auth (#10941)", async () => {
704
+ process.env = {
705
+ ...process.env,
706
+ OSS_API_INTERNAL_SECRET: "internal-secret",
707
+ AILK_API_URL: "https://api.example.com",
708
+ AILK_SPOKE_KEY: "ailk_spk_the_hubs_own_key",
709
+ };
710
+ mockGetSession.mockResolvedValue({ user: { id: "u1" } });
711
+ mockCreateCode.mockResolvedValue({
712
+ ok: true,
713
+ body: { code: CODE, redirectUri: SPOKE_CALLBACK },
714
+ });
715
+
716
+ const res = await POST(post([ref()]));
717
+
718
+ expect(res.status).toBe(200);
719
+ const [body, init] = mockCreateCode.mock.calls[0] as [
720
+ Record<string, unknown>,
721
+ { headers: Record<string, string> },
722
+ ];
723
+ expect(body.consent).toBe(true);
724
+ expect(init.headers["x-internal-auth"]).toBe("internal-secret");
725
+ });
726
+
690
727
  it("POST: withholds x-internal-auth from a plain-http API", async () => {
691
728
  process.env = {
692
729
  ...process.env,
@@ -778,4 +815,150 @@ describe("the consent step (#9966 D2, AC-4)", () => {
778
815
  expect(refused.status).toBe(400);
779
816
  expect(refused.headers.get("location")).toBeNull();
780
817
  });
818
+
819
+ // #11095 AC-10 (D10, folded from #11094): the navigating page is built
820
+ // only for an https: or loopback http: callback.
821
+ it.each([
822
+ "http://spoke.example.com/api/hub-session/callback",
823
+ "javascript:alert(1)",
824
+ "data:text/html,x",
825
+ ])(
826
+ "POST: an echoed redirect URI %s answers a JSON 503 before any HTML is built",
827
+ async (redirectUri) => {
828
+ mockGetSession.mockResolvedValue({ user: { id: "u1" } });
829
+ mockCreateCode.mockResolvedValue({
830
+ ok: true,
831
+ body: { code: CODE, redirectUri },
832
+ });
833
+
834
+ const res = await POST(post([ref()]));
835
+
836
+ expect(res.status).toBe(503);
837
+ expect(res.headers.get("content-type")).toBe("application/json");
838
+ expect(res.headers.get("location")).toBeNull();
839
+ expect(await res.text()).toBe(
840
+ JSON.stringify({ error: "temporarily_unavailable" }),
841
+ );
842
+ },
843
+ );
844
+
845
+ it.each([
846
+ SPOKE_CALLBACK,
847
+ "http://localhost:3000/api/hub-session/callback",
848
+ ])(
849
+ "POST: an echoed redirect URI %s still answers the 200 page",
850
+ async (redirectUri) => {
851
+ mockGetSession.mockResolvedValue({ user: { id: "u1" } });
852
+ mockCreateCode.mockResolvedValue({
853
+ ok: true,
854
+ body: { code: CODE, redirectUri },
855
+ });
856
+
857
+ const res = await POST(post([ref()]));
858
+
859
+ expect(res.status).toBe(200);
860
+ expect(res.headers.get("content-type")).toBe("text/html; charset=utf-8");
861
+ expect(await res.text()).toContain('<meta http-equiv="refresh"');
862
+ },
863
+ );
864
+ });
865
+
866
+ describe("the provider hint, provider_hint=google (#11096 D4, AC-3)", () => {
867
+ const GOOGLE_URL = "https://accounts.google.com/o/oauth2/v2/auth?x";
868
+ const STATE_COOKIE =
869
+ "better-auth.state=abc; Path=/; HttpOnly; Secure; SameSite=Lax";
870
+
871
+ beforeEach(() => {
872
+ process.env.GOOGLE_CLIENT_ID = "google-client";
873
+ process.env.GOOGLE_CLIENT_SECRET = "google-secret";
874
+ mockGetSession.mockResolvedValue(null);
875
+ mockSignInSocial.mockResolvedValue({
876
+ headers: new Headers([["set-cookie", STATE_COOKIE]]),
877
+ response: { url: GOOGLE_URL, redirect: true },
878
+ });
879
+ });
880
+
881
+ it("no session + Google on: 303 to Google's URL with the state cookie, no sign-in card", async () => {
882
+ const res = await GET(request(`${query()}&provider_hint=google`));
883
+
884
+ expect(res.status).toBe(303);
885
+ expect(res.headers.get("location")).toBe(GOOGLE_URL);
886
+ expect(res.headers.getSetCookie()).toEqual([STATE_COOKIE]);
887
+ expect(res.headers.get("cache-control")).toBe("no-store");
888
+ expect(mockSignInSocial).toHaveBeenCalledTimes(1);
889
+ const [call] = mockSignInSocial.mock.calls[0] as [
890
+ {
891
+ body: { provider: string; callbackURL: string; errorCallbackURL: string };
892
+ returnHeaders: boolean;
893
+ },
894
+ ];
895
+ expect(call.body.provider).toBe("google");
896
+ expect(call.returnHeaders).toBe(true);
897
+ expect(call.body.callbackURL.startsWith(`${CONTINUE}/`)).toBe(true);
898
+ const ref = call.body.callbackURL.slice(`${CONTINUE}/`.length);
899
+ expect(openContinuation(ref, mockSecret)).toBe(query());
900
+ expect(call.body.errorCallbackURL).toBe(
901
+ `/sign-in?next=${encodeURIComponent(call.body.callbackURL)}`,
902
+ );
903
+ });
904
+
905
+ it("with prompt=create and a login_hint, the Google hint still wins and neither rides along", async () => {
906
+ const res = await GET(
907
+ request(`${query()}&provider_hint=google&prompt=create&login_hint=a%40b.example`),
908
+ );
909
+ expect(res.headers.get("location")).toBe(GOOGLE_URL);
910
+ });
911
+
912
+ it.each([
913
+ ["Google off", () => {
914
+ delete process.env.GOOGLE_CLIENT_ID;
915
+ }],
916
+ ["signInSocial throwing", () => {
917
+ mockSignInSocial.mockRejectedValue(new Error("boom"));
918
+ }],
919
+ ["signInSocial answering no url", () => {
920
+ mockSignInSocial.mockResolvedValue({ headers: new Headers(), response: {} });
921
+ }],
922
+ ])("%s: today's 303 to /sign-in?next=<continue path>", async (_name, arrange) => {
923
+ arrange();
924
+ const res = await GET(request(`${query()}&provider_hint=google`));
925
+ expect(res.status).toBe(303);
926
+ expect(res.headers.get("location")).toMatch(
927
+ new RegExp(`^/sign-in\\?next=${encodeURIComponent(`${CONTINUE}/`)}`),
928
+ );
929
+ expect(res.headers.getSetCookie()).toEqual([]);
930
+ });
931
+
932
+ it.each(["github", "", "GOOGLE"])(
933
+ "provider_hint=%s does nothing: /sign-in, no social call",
934
+ async (hint) => {
935
+ const res = await GET(request(`${query()}&provider_hint=${hint}`));
936
+ expect(res.headers.get("location")).toMatch(/^\/sign-in\?next=/);
937
+ expect(mockSignInSocial).not.toHaveBeenCalled();
938
+ },
939
+ );
940
+
941
+ it("two provider_hint values: 400 before the session read", async () => {
942
+ const res = await GET(
943
+ request(`${query()}&provider_hint=google&provider_hint=google`),
944
+ );
945
+ expect(res.status).toBe(400);
946
+ expect(await res.json()).toEqual({ error: "invalid_request" });
947
+ expect(mockGetSession).not.toHaveBeenCalled();
948
+ expect(mockSignInSocial).not.toHaveBeenCalled();
949
+ });
950
+
951
+ it("with a session: createCode is called and signInSocial is not", async () => {
952
+ mockGetSession.mockResolvedValue({ user: { id: "u1" } });
953
+ mockCreateCode.mockResolvedValue({
954
+ ok: true,
955
+ body: { code: CODE, redirectUri: SPOKE_CALLBACK },
956
+ });
957
+
958
+ const res = await GET(request(`${query()}&provider_hint=google`));
959
+
960
+ expect(res.status).toBe(303);
961
+ expect(mockCreateCode).toHaveBeenCalledTimes(1);
962
+ expect(mockSignInSocial).not.toHaveBeenCalled();
963
+ });
781
964
  });
@@ -56,6 +56,16 @@
56
56
  * continuation to `/sign-in` — nor a code or a cookie, and with a session it
57
57
  * is ignored: the person has an account, and the spoke signs them in.
58
58
  *
59
+ * `provider_hint=google` (#11096 D4) is the spoke's "Continue with Google":
60
+ * read by the same once-only rule (repeated → 400, before the session read).
61
+ * On the no-session branch, exactly `google` with Google an active provider
62
+ * calls `auth.api.signInSocial` with the continue path as its callback and
63
+ * answers a 303 straight to Google, carrying every `Set-Cookie` the call
64
+ * returned (Better Auth's state cookie) — no sign-in card renders. Any other
65
+ * value, Google off, or a call that throws or answers no URL falls back to
66
+ * the redirect above. With a session it is ignored; with it, `prompt` and
67
+ * `login_hint` are ignored.
68
+ *
59
69
  * POST /api/auth/hub/authorize (form field `ref`, #9966 D2)
60
70
  *
61
71
  * - the consent page's Continue. Accepted only with `Sec-Fetch-Site:
@@ -64,6 +74,10 @@
64
74
  * and its query re-validated, and the session branch runs as GET's does,
65
75
  * with `consent: true` — and `x-internal-auth` where the API requires it —
66
76
  * on the code request. This is the one call site that sends consent.
77
+ * Its success is a 200 page that navigates to the spoke, never a 303:
78
+ * Chrome holds a form submission's redirects to the hub's own
79
+ * `form-action 'self'`, so a 303 to the spoke is blocked and the person
80
+ * stays on the consent page with a console error (#11091).
67
81
  *
68
82
  * `BETTER_AUTH_URL` pins the `Origin` sent with the cookie-authenticated write
69
83
  * (Node's `fetch` sets none). Unset, the step answers 503: it needs a pinned
@@ -83,24 +97,16 @@ import {
83
97
 
84
98
  import { auth, resolveSecret } from "../../../../../auth";
85
99
  import { browserApiOrigin } from "../../../../../lib/api-origin.generated";
100
+ import { getActiveProviderIds } from "../../../../../lib/auth-env";
86
101
  import { TOPOLOGY } from "../../../../../lib/topology.generated";
87
102
  import {
88
- CONTINUATION_REF_MAX,
103
+ AUTHORIZE_QUERY_KEYS as QUERY_KEYS,
89
104
  CONTINUE_PATH,
90
- mintContinuation,
91
105
  openContinuation,
106
+ pinnedOrigin,
107
+ sealQuery,
92
108
  } from "../continuation";
93
109
 
94
- /** The six query keys, each read exactly once. */
95
- const QUERY_KEYS = [
96
- "response_type",
97
- "client_id",
98
- "redirect_uri",
99
- "state",
100
- "code_challenge",
101
- "code_challenge_method",
102
- ] as const;
103
-
104
110
  /** Where an unverified person is sent to verify: the hub's own account page. */
105
111
  const VERIFY_EMAIL_PATH = "/account/settings";
106
112
 
@@ -132,27 +138,73 @@ function see(location: string): Response {
132
138
  });
133
139
  }
134
140
 
135
- /** The pinned origin of the hub's own web app, or `null` when unset/invalid. */
136
- function pinnedOrigin(): string | null {
137
- const raw = process.env.BETTER_AUTH_URL;
138
- if (!raw) return null;
141
+ /** `&`, `<`, `>`, `"` and `'` as entities, so a URL sits safely in an attribute. */
142
+ function escapeHtml(value: string): string {
143
+ return value
144
+ .replace(/&/g, "&amp;")
145
+ .replace(/</g, "&lt;")
146
+ .replace(/>/g, "&gt;")
147
+ .replace(/"/g, "&quot;")
148
+ .replace(/'/g, "&#39;");
149
+ }
150
+
151
+ /**
152
+ * The consent POST's success: a 200 page that navigates to the spoke. A 303
153
+ * here is what Chrome blocks under the hub's `form-action 'self'` (#11091);
154
+ * a meta refresh and a link are navigations, which that directive never
155
+ * governs. The code rides the URL, so the page is `no-store` and sends no
156
+ * referrer.
157
+ */
158
+ function arrive(location: string): Response {
159
+ const href = escapeHtml(location);
160
+ const html =
161
+ `<!doctype html><html lang="en"><head><meta charset="utf-8">` +
162
+ `<meta name="referrer" content="no-referrer">` +
163
+ `<meta http-equiv="refresh" content="0;url=${href}">` +
164
+ `<title>Signing you in</title></head>` +
165
+ `<body><p><a href="${href}">Continue</a></p></body></html>`;
166
+ return new Response(html, {
167
+ status: 200,
168
+ headers: {
169
+ "Content-Type": "text/html; charset=utf-8",
170
+ "Cache-Control": "no-store",
171
+ "Referrer-Policy": "no-referrer",
172
+ },
173
+ });
174
+ }
175
+
176
+ /**
177
+ * #11096 D4 — straight to Google for the continue path, or `null` to fall
178
+ * back to the sign-in card. The 303 carries every `Set-Cookie` the call
179
+ * returned: Better Auth's state cookie is what its callback checks.
180
+ */
181
+ async function googleRedirect(
182
+ request: Request,
183
+ continuePath: string,
184
+ ): Promise<Response | null> {
185
+ if (!getActiveProviderIds().includes("google")) return null;
139
186
  try {
140
- return new URL(raw).origin;
187
+ const { headers, response } = await auth.api.signInSocial({
188
+ body: {
189
+ provider: "google",
190
+ callbackURL: continuePath,
191
+ errorCallbackURL: `/sign-in?${new URLSearchParams({ next: continuePath }).toString()}`,
192
+ },
193
+ headers: request.headers,
194
+ returnHeaders: true,
195
+ });
196
+ const url = (response as { url?: unknown } | undefined)?.url;
197
+ if (typeof url !== "string" || !url.startsWith("https://")) return null;
198
+ const res = see(url);
199
+ for (const cookie of headers.getSetCookie()) {
200
+ res.headers.append("Set-Cookie", cookie);
201
+ }
202
+ return res;
141
203
  } catch {
142
204
  return null;
143
205
  }
144
206
  }
145
207
 
146
- /** The six validated keys as a sealed continuation ref, or `null` past the cap. */
147
- function sealQuery(query: HubAuthorizeQuery): string | null {
148
- // Only the six validated keys, in QUERY_KEYS order: a ref carries nothing
149
- // that did not pass the schema, and extra or reordered keys are dropped.
150
- const canonical = new URLSearchParams();
151
- for (const key of QUERY_KEYS) canonical.set(key, query[key]);
152
- const ref = mintContinuation(canonical.toString(), resolveSecret());
153
- return ref.length > CONTINUATION_REF_MAX ? null : ref;
154
- }
155
-
156
208
  /**
157
209
  * `x-internal-auth` for the consent-bearing code request, under the Offerings
158
210
  * buy route's `startHeaders` rule: only from a site that is not a spoke, and
@@ -161,7 +213,11 @@ function sealQuery(query: HubAuthorizeQuery): string | null {
161
213
  */
162
214
  function internalAuthHeader(): Record<string, string> {
163
215
  const secret = process.env.OSS_API_INTERNAL_SECRET;
164
- const spoke = TOPOLOGY === "spoke" || !!process.env.AILK_SPOKE_KEY?.trim();
216
+ // The topology alone says "spoke" (#10941). A hub also holds a spoke key —
217
+ // its own, for server-side reads — and reading that key as "this site is a
218
+ // spoke" dropped the header on the one site that mints codes, so no consent
219
+ // ever completed.
220
+ const spoke = TOPOLOGY === "spoke";
165
221
  if (!secret || spoke) return {};
166
222
  try {
167
223
  const api = new URL(
@@ -223,7 +279,14 @@ async function codeRedirect(
223
279
  }
224
280
  target.searchParams.set("code", result.body.code);
225
281
  target.searchParams.set("state", query.state);
226
- return see(target.toString());
282
+ if (!consent) return see(target.toString());
283
+ // The navigating page is markup, so it is built only for the schemes
284
+ // registration admits (#11095 D10, #11094); the GET's 303 is a header.
285
+ const safe =
286
+ target.protocol === "https:" ||
287
+ (target.protocol === "http:" && LOOPBACK_HOSTS.has(target.hostname));
288
+ if (!safe) return json(503, "temporarily_unavailable");
289
+ return arrive(target.toString());
227
290
  }
228
291
 
229
292
  const code = (result.body as { error?: { code?: unknown } } | null)?.error
@@ -234,7 +297,7 @@ async function codeRedirect(
234
297
  // Not yet said yes to this spoke: ask, on the hub's own page. The POST that
235
298
  // page sends already carries consent, so it never comes back here.
236
299
  if (!consent && result.status === 403 && code === "consent_required") {
237
- const ref = sealQuery(query);
300
+ const ref = sealQuery(query, resolveSecret());
238
301
  if (ref === null) return json(400, "invalid_request");
239
302
  return see(`${CONSENT_PATH}?${new URLSearchParams({ ref }).toString()}`);
240
303
  }
@@ -258,6 +321,9 @@ export async function GET(request: Request): Promise<Response> {
258
321
  // #9912 D3 — the sign-up hint, by the same rule; only `create` acts.
259
322
  const prompts = url.searchParams.getAll("prompt");
260
323
  if (prompts.length > 1) return json(400, "invalid_request");
324
+ // #11096 D4 — the Google hint, by the same rule; only `google` acts.
325
+ const providerHints = url.searchParams.getAll("provider_hint");
326
+ if (providerHints.length > 1) return json(400, "invalid_request");
261
327
  const parsed = hubAuthorizeQuerySchema.safeParse(raw);
262
328
  if (!parsed.success) return json(400, "invalid_request");
263
329
  const query = parsed.data;
@@ -265,8 +331,12 @@ export async function GET(request: Request): Promise<Response> {
265
331
 
266
332
  const session = await auth.api.getSession({ headers: request.headers });
267
333
  if (!session) {
268
- const ref = sealQuery(query);
334
+ const ref = sealQuery(query, resolveSecret());
269
335
  if (ref === null) return json(400, "invalid_request");
336
+ if (providerHints[0] === "google") {
337
+ const google = await googleRedirect(request, `${CONTINUE_PATH}/${ref}`);
338
+ if (google) return google;
339
+ }
270
340
  const signIn = new URLSearchParams({ next: `${CONTINUE_PATH}/${ref}` });
271
341
  if (prompts[0] === "create") return see(`/sign-up?${signIn.toString()}`);
272
342
  if (hint.success) signIn.set("email", hint.data);
@@ -14,7 +14,14 @@
14
14
  * purpose), with its expiry inside. The ref is opaque but is NOT a secret: it
15
15
  * carries what the cleartext `next` carried before (spec § 9 SEC-8146-1).
16
16
  * Nothing here logs a ref.
17
+ *
18
+ * #11096: `sealQuery` and `pinnedOrigin` live here so every hub web route
19
+ * under `api/auth/hub/` seals the same six keys and pins the same origin, and
20
+ * `mintContinuation` takes an optional life so a purchase claim (sealed under
21
+ * its own name, `hub-purchase`) can outlive the 600 s a continuation needs.
17
22
  */
23
+ import type { HubAuthorizeQuery } from "@working-theory/validation";
24
+
18
25
  import { seal, unseal } from "../../../../lib/hub-session/seal";
19
26
 
20
27
  /** The same-origin path a ref is appended to. */
@@ -38,21 +45,63 @@ const AAD = "hub-continue";
38
45
 
39
46
  const BASE64URL = /^[A-Za-z0-9_-]+$/;
40
47
 
41
- /** `search` (the canonical authorize query, no leading `?`) as a sealed ref. */
48
+ /** The authorize step's six keys, in the order every ref carries them. */
49
+ export const AUTHORIZE_QUERY_KEYS = [
50
+ "response_type",
51
+ "client_id",
52
+ "redirect_uri",
53
+ "state",
54
+ "code_challenge",
55
+ "code_challenge_method",
56
+ ] as const;
57
+
58
+ /**
59
+ * `search` (the canonical authorize query, no leading `?`) as a sealed ref.
60
+ * `ttlSeconds` defaults to a continuation's 600 s (#11096 D9's claim passes
61
+ * its 72 hours).
62
+ */
42
63
  export function mintContinuation(
43
64
  search: string,
44
65
  secret: string,
45
66
  now: number = Date.now(),
46
67
  name: string = AAD,
68
+ ttlSeconds: number = CONTINUATION_TTL_SECONDS,
47
69
  ): string {
48
70
  return seal(
49
- { v: 1, q: search, exp: now + CONTINUATION_TTL_SECONDS * 1000 },
71
+ { v: 1, q: search, exp: now + ttlSeconds * 1000 },
50
72
  secret,
51
73
  "continue",
52
74
  name,
53
75
  );
54
76
  }
55
77
 
78
+ /**
79
+ * The six validated keys as a sealed continuation ref, or `null` past the
80
+ * cap. Only the six keys, in `AUTHORIZE_QUERY_KEYS` order: a ref carries
81
+ * nothing that did not pass the schema, and extra or reordered keys are
82
+ * dropped.
83
+ */
84
+ export function sealQuery(
85
+ query: HubAuthorizeQuery,
86
+ secret: string,
87
+ ): string | null {
88
+ const canonical = new URLSearchParams();
89
+ for (const key of AUTHORIZE_QUERY_KEYS) canonical.set(key, query[key]);
90
+ const ref = mintContinuation(canonical.toString(), secret);
91
+ return ref.length > CONTINUATION_REF_MAX ? null : ref;
92
+ }
93
+
94
+ /** The pinned origin of the hub's own web app, or `null` when unset/invalid. */
95
+ export function pinnedOrigin(): string | null {
96
+ const raw = process.env.BETTER_AUTH_URL;
97
+ if (!raw) return null;
98
+ try {
99
+ return new URL(raw).origin;
100
+ } catch {
101
+ return null;
102
+ }
103
+ }
104
+
56
105
  /**
57
106
  * The authorize query a ref holds, or `null` when the ref is too long, is not
58
107
  * base64url, does not open, is not the expected shape, or has expired.
@@ -0,0 +1,111 @@
1
+ /**
2
+ * `POST /api/auth/hub/email` — the hub web's half of a spoke-hosted email
3
+ * sign-in (#11096 D2, spec docs/specs/11096-the-spoke-hosts-the-sign-spec.md).
4
+ *
5
+ * A spoke's server (never a browser) posts the email a person typed on the
6
+ * spoke's own `/account`, with the six authorize keys of the flow it just
7
+ * started and, only when a box was ticked, the agreement ids. In order:
8
+ *
9
+ * 1. `BETTER_AUTH_URL` pins the origin, else 503. Body ≤ 4 KB of JSON.
10
+ * 2. `hubEmailEntryBodySchema` (`.strict()`): anything else — `password`
11
+ * among it — is 400 `invalid_request` (D5).
12
+ * 3. A caller refused ten times in ten minutes is 429 before any API
13
+ * call (`refusedCallerLimit`); a missing or non-`Basic` header is a
14
+ * refusal. The hub API's `POST /v1/hub-sign-in/entry` authenticates
15
+ * the spoke with the `Authorization` and `x-ailk-spoke-key` it sent, as received,
16
+ * and checks the redirect URI is registered for it. A non-200 is passed
17
+ * on as its status with `{ error }`, and nothing is sent.
18
+ * 4. The six keys are sealed into a continuation ref.
19
+ * 5. Better Auth's `signInMagicLink` sends the hub's own link, its callback
20
+ * the continue path. Its headers carry only the pinned `Origin`: the
21
+ * spoke's two headers never reach Better Auth (SEC-11096-12). The
22
+ * agreements plugin's before-hook runs for this server call as for
23
+ * HTTP, so a sign-up request without full agreements is
24
+ * `400 agreements_required` before any lookup, and `400 sign_up_closed`
25
+ * on a closed site.
26
+ * 6. 202 `{ sent: true }` for a known and an unknown address alike.
27
+ *
28
+ * The link's use then runs verify (302), continue, authorize and the spoke's
29
+ * callback (303s) — a redirect at every hop, never a hub page. Nothing here
30
+ * logs an email, a header or a ref. Under `app/api/auth`, a spoke removal
31
+ * seed, so no spoke carries it.
32
+ */
33
+ import { hubSignIn } from "@working-theory/api-client";
34
+ import { hubEmailEntryBodySchema } from "@working-theory/validation";
35
+
36
+ import { auth, resolveSecret } from "../../../../../auth";
37
+ import { CONTINUE_PATH, pinnedOrigin, sealQuery } from "../continuation";
38
+ import {
39
+ apiErrorCode,
40
+ betterAuthCode,
41
+ forwardedClientAuth,
42
+ json,
43
+ noteRefusedCaller,
44
+ parseJson,
45
+ readRawBody,
46
+ refusedCallerLimit,
47
+ refuse,
48
+ } from "../entry-shared";
49
+
50
+ // platform-decisions-waiver: api-versioning — a hub sign-in step, not a versioned API contract (spec 11096 § 6)
51
+ export async function POST(request: Request): Promise<Response> {
52
+ const origin = pinnedOrigin();
53
+ if (origin === null) return refuse(503, "temporarily_unavailable");
54
+
55
+ const raw = await readRawBody(request);
56
+ if (raw === null) return refuse(400, "invalid_request");
57
+ const parsed = hubEmailEntryBodySchema.safeParse(parseJson(raw));
58
+ if (!parsed.success) return refuse(400, "invalid_request");
59
+ const body = parsed.data;
60
+
61
+ const limited = refusedCallerLimit(request);
62
+ if (limited !== null) return limited;
63
+ const client = forwardedClientAuth(request);
64
+ if (client === null) {
65
+ noteRefusedCaller(request);
66
+ return refuse(401, "invalid_client");
67
+ }
68
+
69
+ try {
70
+ const checked = await hubSignIn.entry(client, {
71
+ clientId: body.client_id,
72
+ redirectUri: body.redirect_uri,
73
+ email: body.email,
74
+ });
75
+ if (!checked.ok) {
76
+ if (checked.status === 401 || checked.status === 403) {
77
+ noteRefusedCaller(request);
78
+ }
79
+ return refuse(
80
+ checked.status,
81
+ apiErrorCode(checked.body, "invalid_request"),
82
+ );
83
+ }
84
+ } catch {
85
+ return refuse(503, "temporarily_unavailable");
86
+ }
87
+
88
+ const ref = sealQuery({ response_type: "code", ...body }, resolveSecret());
89
+ if (ref === null) return refuse(400, "invalid_request");
90
+
91
+ try {
92
+ await auth.api.signInMagicLink({
93
+ body: {
94
+ email: body.email,
95
+ callbackURL: `${CONTINUE_PATH}/${ref}`,
96
+ ...(body.agreements
97
+ ? { metadata: { agreements: body.agreements, locale: body.locale } }
98
+ : {}),
99
+ },
100
+ headers: new Headers({ origin }),
101
+ });
102
+ } catch (err) {
103
+ const code = betterAuthCode(err);
104
+ if (code === "AGREEMENTS_REQUIRED")
105
+ return refuse(400, "agreements_required");
106
+ if (code === "SIGN_UP_CLOSED") return refuse(400, "sign_up_closed");
107
+ return refuse(503, "temporarily_unavailable");
108
+ }
109
+
110
+ return json(202, { sent: true });
111
+ }