@rebasepro/server-core 0.0.1-canary.f81da60 → 0.1.2

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.
@@ -6,12 +6,42 @@ export interface GoogleUserInfo {
6
6
  photoUrl: string | null;
7
7
  emailVerified: boolean;
8
8
  }
9
+ export interface GoogleProviderConfig {
10
+ clientId: string;
11
+ /**
12
+ * The OAuth 2.0 client secret from Google Cloud Console.
13
+ *
14
+ * Required for the **authorization code flow** (Path 3), where the
15
+ * frontend sends an authorization `code` and the backend exchanges it
16
+ * server-side for tokens. This is the most secure flow because tokens
17
+ * never touch the browser.
18
+ *
19
+ * When omitted, only ID-token and access-token verification are available
20
+ * (Paths 1 & 2), which rely on the frontend obtaining tokens directly.
21
+ */
22
+ clientSecret?: string;
23
+ }
9
24
  /**
10
25
  * Creates a Google OAuth Provider integration.
11
- * Supports both ID-token verification (One Tap / renderButton) and
12
- * access-token verification (popup via initTokenClient).
26
+ *
27
+ * Supports three verification paths:
28
+ *
29
+ * **Path 1 – ID Token** (One Tap / Sign In With Google button):
30
+ * Frontend sends `idToken`. Backend verifies cryptographically using
31
+ * Google's public keys. No secret required.
32
+ *
33
+ * **Path 2 – Access Token** (popup via `initTokenClient`):
34
+ * Frontend sends `accessToken`. Backend validates by calling Google's
35
+ * userinfo endpoint. No secret required.
36
+ *
37
+ * **Path 3 – Authorization Code** (most secure, requires `clientSecret`):
38
+ * Frontend sends `code` + `redirectUri`. Backend exchanges the code
39
+ * server-side for an ID token using `clientId` + `clientSecret`, then
40
+ * verifies the ID token. Tokens never touch the browser.
13
41
  */
14
- export declare function createGoogleProvider(clientId: string): OAuthProvider<{
42
+ export declare function createGoogleProvider(config: GoogleProviderConfig | string): OAuthProvider<{
15
43
  idToken?: string;
16
44
  accessToken?: string;
45
+ code?: string;
46
+ redirectUri?: string;
17
47
  }>;
@@ -4,6 +4,7 @@ export type { JwtConfig, AccessTokenPayload } from "./jwt";
4
4
  export { hashPassword, verifyPassword, validatePasswordStrength } from "./password";
5
5
  export type { PasswordValidationResult } from "./password";
6
6
  export { createGoogleProvider } from "./google-oauth";
7
+ export type { GoogleProviderConfig } from "./google-oauth";
7
8
  export { createLinkedinProvider } from "./linkedin-oauth";
8
9
  export { createGitHubProvider } from "./github-oauth";
9
10
  export { createMicrosoftProvider } from "./microsoft-oauth";
@@ -29,6 +29,7 @@ export interface RebaseAuthConfig {
29
29
  email?: EmailConfig;
30
30
  google?: {
31
31
  clientId: string;
32
+ clientSecret?: string;
32
33
  };
33
34
  linkedin?: {
34
35
  clientId: string;
@@ -80,8 +80,14 @@ export type AuthController<USER extends User = User, ExtraData = unknown> = {
80
80
  export interface AuthControllerExtended<USER extends User = User, ExtraData = unknown> extends AuthController<USER, ExtraData> {
81
81
  /** Login with email and password */
82
82
  emailPasswordLogin?(email: string, password: string): Promise<void>;
83
- /** Login with a Google token (ID token or access token from popup) */
84
- googleLogin?(token: string, tokenType?: "idToken" | "accessToken"): Promise<void>;
83
+ /** Login with a Google token or authorization code */
84
+ googleLogin?: {
85
+ (token: string, tokenType?: "idToken" | "accessToken"): Promise<void>;
86
+ (payload: {
87
+ code: string;
88
+ redirectUri: string;
89
+ }): Promise<void>;
90
+ };
85
91
  /** Register a new user */
86
92
  register?(email: string, password: string, displayName?: string): Promise<void>;
87
93
  /** Skip login (for anonymous access if enabled) */
@@ -167,4 +167,17 @@ export interface RebaseClient<DB = unknown> {
167
167
  email?: EmailService;
168
168
  /** Admin API for user and role management */
169
169
  admin?: AdminAPI;
170
+ /**
171
+ * The base HTTP URL of the backend server.
172
+ * Exposed by the SDK client (`@rebasepro/client`) and used to auto-derive
173
+ * the `ApiConfigProvider` URL.
174
+ */
175
+ baseUrl?: string;
176
+ /**
177
+ * WebSocket client for realtime subscriptions and admin capabilities.
178
+ * Exposed by the SDK client (`@rebasepro/client`). The shape is intentionally
179
+ * left as `unknown` in the base interface — callers should narrow via feature
180
+ * detection (e.g. `typeof ws.executeSql === "function"`).
181
+ */
182
+ ws?: unknown;
170
183
  }
@@ -144,17 +144,18 @@ export interface AppView {
144
144
  * It will still be accessible if you reach the specified path
145
145
  */
146
146
  hideFromNavigation?: boolean;
147
+ /**
148
+ * Navigation group for this view.
149
+ * Views sharing the same group name will be visually grouped
150
+ * together in the drawer and home page. If not set, the view
151
+ * falls into the default "Views" group.
152
+ */
153
+ group?: string;
147
154
  /**
148
155
  * Component to be rendered. This can be any React component, and can use
149
156
  * any of the provided hooks
150
157
  */
151
158
  view: React.ReactNode;
152
- /**
153
- * Optional field used to group top level navigation entries under a
154
- * navigation view.
155
- * This prop is ignored for admin views.
156
- */
157
- group?: string;
158
159
  /**
159
160
  * If true, a wildcard route (slug/*) is automatically registered
160
161
  * alongside the base route, enabling nested navigation within this view.
@@ -193,6 +194,17 @@ export interface NavigationGroupMapping {
193
194
  * List of collection ids or view paths that belong to this group.
194
195
  */
195
196
  entries: string[];
197
+ /**
198
+ * Configure which groups start collapsed.
199
+ * Set to `true` to collapse in both drawer and home page,
200
+ * or use an object to control each independently.
201
+ *
202
+ * @defaultValue false (expanded)
203
+ */
204
+ collapsedByDefault?: boolean | {
205
+ drawer?: boolean;
206
+ home?: boolean;
207
+ };
196
208
  }
197
209
  export interface NavigationEntry {
198
210
  id: string;
@@ -3,7 +3,7 @@ import type { EntityCollection } from "../types/collections";
3
3
  import type { EntityCollectionsBuilder } from "../types/builders";
4
4
  import type { EntityCustomView } from "../types/entity_views";
5
5
  import type { EntityAction } from "../types/entity_actions";
6
- import type { AppView } from "./navigation";
6
+ import type { AppView, NavigationGroupMapping } from "./navigation";
7
7
  /**
8
8
  * Options to enable the built-in collection editor.
9
9
  * When provided to `<RebaseCMS>`, the editor is auto-wired as a native feature.
@@ -25,6 +25,14 @@ export interface RebaseCMSConfig<EC extends EntityCollection = any> {
25
25
  entityViews?: EntityCustomView<any>[];
26
26
  entityActions?: EntityAction[];
27
27
  plugins?: any[];
28
+ /**
29
+ * Centralized configuration for how collections and views are grouped
30
+ * in the navigation sidebar and home page.
31
+ * Each mapping defines a named group and the collection/view slugs
32
+ * that belong to it. The array order determines group display order.
33
+ * Entry order within each group determines card order.
34
+ */
35
+ navigationGroupMappings?: NavigationGroupMapping[];
28
36
  /**
29
37
  * Enable the built-in visual collection/schema editor.
30
38
  * Pass `true` for zero-config, or an options object for fine-grained control.
@@ -62,6 +62,13 @@ export interface EntitySidePanelProps<M extends Record<string, unknown> = Record
62
62
  * Allow the user to open the entity fullscreen
63
63
  */
64
64
  allowFullScreen?: boolean;
65
+ /**
66
+ * Pre-populate the form with these values when creating a new entity.
67
+ * Only applied when `entityId` is not set (i.e. the form is in "new" mode).
68
+ * Useful for actions that fetch data from an external source (e.g. a URL)
69
+ * and want to pre-fill the document before the user saves.
70
+ */
71
+ defaultValues?: Partial<M>;
65
72
  }
66
73
  /**
67
74
  * Controller to open the side dialog displaying entity forms
@@ -3,6 +3,7 @@ import type { AuthController } from "./controllers/auth";
3
3
  import type { StorageSource } from "./controllers/storage";
4
4
  import type { UserConfigurationPersistence } from "./controllers/local_config_persistence";
5
5
  import type { DatabaseAdmin } from "./types/backend";
6
+ import type { RebaseClient } from "./controllers/client";
6
7
  import type { RebaseData } from "./controllers/data";
7
8
  import type { User } from "./users";
8
9
  import type { UserManagementDelegate } from "./types/user_management_delegate";
@@ -12,6 +13,22 @@ import type { UserManagementDelegate } from "./types/user_management_delegate";
12
13
  * @group Hooks and utilities
13
14
  */
14
15
  export type RebaseCallContext<USER extends User = User> = {
16
+ /**
17
+ * The Rebase client instance.
18
+ * Available in all entity callbacks (beforeSave, afterSave, afterRead,
19
+ * beforeDelete, afterDelete) and in CollectionActionsProps via context.
20
+ * Use it to call backend functions, access data, storage, etc.
21
+ *
22
+ * @example
23
+ * // In a beforeSave callback:
24
+ * const result = await context.client.functions.invoke('my-function', { ... });
25
+ *
26
+ * @example
27
+ * // In a CollectionAction component:
28
+ * const { client } = props.context;
29
+ * const result = await client.functions.invoke('extract-job', { url });
30
+ */
31
+ client: RebaseClient<any>;
15
32
  /**
16
33
  * Unified data access — `context.data.products.create(...)`.
17
34
  * Access any collection as a dynamic property.
@@ -9,6 +9,7 @@ import type { RebaseContext } from "../rebase_context";
9
9
  import type { Relation } from "./relations";
10
10
  import type { EntityCustomView } from "./entity_views";
11
11
  import type { EntityAction } from "./entity_actions";
12
+ import type { ComponentRef } from "./component_ref";
12
13
  /**
13
14
  * Base interface containing all driver-agnostic collection properties.
14
15
  * Use {@link PostgresCollection} or {@link FirebaseCollection} for
@@ -86,6 +87,9 @@ export interface BaseEntityCollection<M extends Record<string, unknown> = Record
86
87
  icon?: string | React.ReactNode;
87
88
  /**
88
89
  * Navigation group for this collection.
90
+ * Collections sharing the same group name will be visually grouped
91
+ * together in the drawer and home page. If not set, the collection
92
+ * falls into the default "Views" group.
89
93
  */
90
94
  group?: string;
91
95
  /**
@@ -301,7 +305,7 @@ export interface BaseEntityCollection<M extends Record<string, unknown> = Record
301
305
  /**
302
306
  * Builder for the collection actions rendered in the toolbar
303
307
  */
304
- Actions?: React.ComponentType<any>[];
308
+ Actions?: ComponentRef<CollectionActionsProps>[];
305
309
  }
306
310
  /**
307
311
  * A collection backed by PostgreSQL (or any SQL database).
@@ -482,6 +486,21 @@ export interface CollectionActionsProps<M extends Record<string, unknown> = Reco
482
486
  * undefined means the count is still loading.
483
487
  */
484
488
  collectionEntitiesCount?: number;
489
+ /**
490
+ * Programmatically open the new-document form for this collection,
491
+ * optionally pre-populating it with initial field values.
492
+ * The form opens in the same mode configured for the collection
493
+ * (side panel, full screen, or split).
494
+ *
495
+ * This is the primary hook for workflows that need to create a document
496
+ * from external data — e.g. fetching content from a URL, importing from
497
+ * a third-party API, or duplicating from another system.
498
+ *
499
+ * @example
500
+ * // Inside a custom CollectionAction component:
501
+ * openNewDocument({ title: "Fetched title", body: "..." });
502
+ */
503
+ openNewDocument: (defaultValues?: Record<string, unknown>) => void;
485
504
  }
486
505
  /**
487
506
  * Use this controller to retrieve the selected entities or modify them in
@@ -0,0 +1,47 @@
1
+ import type React from "react";
2
+ /**
3
+ * Internal marker for a lazily-loaded component reference.
4
+ * Created by the Vite transform plugin when converting string paths
5
+ * to deferred `import()` calls. Users should NOT create these manually.
6
+ *
7
+ * @internal
8
+ */
9
+ export interface LazyComponentRef<P = unknown> {
10
+ readonly __rebaseLazy: true;
11
+ readonly load: () => Promise<{
12
+ default: React.ComponentType<P>;
13
+ }>;
14
+ }
15
+ /**
16
+ * A reference to a React component that can be provided in three forms:
17
+ *
18
+ * 1. **String path** (recommended for collection configs):
19
+ * ```ts
20
+ * Field: "../../frontend/src/components/MyField"
21
+ * ```
22
+ * The Vite plugin transforms this into a `LazyComponentRef` at build time.
23
+ * On the backend, the string stays inert and is never evaluated.
24
+ *
25
+ * 2. **Lazy import function**:
26
+ * ```ts
27
+ * Field: () => import("../../frontend/src/components/MyField")
28
+ * ```
29
+ * Standard ES dynamic import. Backend never calls the function.
30
+ *
31
+ * 3. **Direct component reference** (use only in frontend-only code):
32
+ * ```ts
33
+ * Field: MyFieldComponent
34
+ * ```
35
+ * Importing a component at the top level will pull React into the
36
+ * backend runtime — only safe in code that the backend never imports.
37
+ *
38
+ * @group Types
39
+ */
40
+ export type ComponentRef<P = unknown> = React.ComponentType<P> | LazyComponentRef<P> | (() => Promise<{
41
+ default: React.ComponentType<P>;
42
+ }>) | string;
43
+ /**
44
+ * Type guard: checks if a value is a `LazyComponentRef` produced by the
45
+ * Vite transform plugin.
46
+ */
47
+ export declare function isLazyComponentRef<P = unknown>(ref: unknown): ref is LazyComponentRef<P>;
@@ -2,6 +2,7 @@ import React from "react";
2
2
  import type { Entity, EntityValues } from "./entities";
3
3
  import type { EntityCollection } from "./collections";
4
4
  import type { FormexController } from "./formex";
5
+ import type { ComponentRef } from "./component_ref";
5
6
  /**
6
7
  * Context passed to custom fields and entity views.
7
8
  * @group Form custom fields
@@ -46,7 +47,7 @@ export type EntityCustomView<M extends Record<string, unknown> = Record<string,
46
47
  name: string;
47
48
  tabComponent?: React.ReactNode;
48
49
  includeActions?: boolean | "bottom";
49
- Builder?: React.ComponentType<EntityCustomViewParams<M>>;
50
+ Builder?: ComponentRef<EntityCustomViewParams<M>>;
50
51
  position?: "start" | "end";
51
52
  };
52
53
  export interface EntityCustomViewParams<M extends Record<string, unknown> = Record<string, unknown>> {
@@ -23,3 +23,4 @@ export * from "./entity_views";
23
23
  export * from "./data_source";
24
24
  export * from "./cron";
25
25
  export * from "./backend_hooks";
26
+ export * from "./component_ref";
@@ -1,4 +1,4 @@
1
- import React from "react";
1
+ import type { ComponentRef } from "./component_ref";
2
2
  import type { EntityReference, EntityRelation, EntityValues, GeoPoint, Entity } from "./entities";
3
3
  import type { Relation, JoinStep, OnAction } from "./relations";
4
4
  import type { EntityCollection, FilterValues } from "./collections";
@@ -104,8 +104,8 @@ export interface BaseUIConfig<CustomProps = unknown> {
104
104
  disabled?: boolean | PropertyDisabledConfig;
105
105
  widthPercentage?: number;
106
106
  customProps?: CustomProps;
107
- Field?: React.ComponentType<any>;
108
- Preview?: React.ComponentType<any>;
107
+ Field?: ComponentRef<any>;
108
+ Preview?: ComponentRef<any>;
109
109
  }
110
110
  export interface BaseProperty<CustomProps = unknown> {
111
111
  ui?: BaseUIConfig<CustomProps>;
@@ -124,6 +124,18 @@ export interface BaseProperty<CustomProps = unknown> {
124
124
  * overwritten by the current property config.
125
125
  */
126
126
  propertyConfig?: string;
127
+ /**
128
+ * Explicit database column name. When set, this value is used as-is
129
+ * for the SQL column name, bypassing any snake_case conversion of
130
+ * the property key.
131
+ *
132
+ * This is automatically populated by `rebase schema introspect`
133
+ * to guarantee an exact match with the live database schema.
134
+ *
135
+ * For manually-authored collections you can omit this — the framework
136
+ * will derive the column name from the property key via `toSnakeCase()`.
137
+ */
138
+ columnName?: string;
127
139
  /**
128
140
  * Rules for validating this property
129
141
  */
@@ -51,6 +51,8 @@ export interface RebaseTranslations {
51
51
  all_entries_loaded: string;
52
52
  create_your_first_entry: string;
53
53
  no_results_filter_sort: string;
54
+ /** Shown when a text search yields no results. Supports `{{search}}` interpolation. */
55
+ no_results_search?: string;
54
56
  add: string;
55
57
  remove: string;
56
58
  copy_id: string;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@rebasepro/server-core",
3
3
  "type": "module",
4
- "version": "0.0.1-canary.f81da60",
4
+ "version": "0.1.2",
5
5
  "description": "Database-Agnostic Backend Core for Rebase",
6
6
  "funding": {
7
7
  "url": "https://github.com/sponsors/rebaseco"
@@ -52,10 +52,10 @@
52
52
  "ts-morph": "27.0.2",
53
53
  "ws": "^8.16.0",
54
54
  "zod": "^3.22.4",
55
- "@rebasepro/client": "0.0.1-canary.f81da60",
56
- "@rebasepro/common": "0.0.1-canary.f81da60",
57
- "@rebasepro/types": "0.0.1-canary.f81da60",
58
- "@rebasepro/utils": "0.0.1-canary.f81da60"
55
+ "@rebasepro/client": "0.1.2",
56
+ "@rebasepro/common": "0.1.2",
57
+ "@rebasepro/utils": "0.1.2",
58
+ "@rebasepro/types": "0.1.2"
59
59
  },
60
60
  "devDependencies": {
61
61
  "@types/jest": "^29.5.14",
@@ -69,8 +69,8 @@
69
69
  "ts-jest": "29.4.1",
70
70
  "typescript": "^5.0.0",
71
71
  "vite": "^5.0.0",
72
- "@rebasepro/common": "0.0.1-canary.f81da60",
73
- "@rebasepro/types": "0.0.1-canary.f81da60"
72
+ "@rebasepro/common": "0.1.2",
73
+ "@rebasepro/types": "0.1.2"
74
74
  },
75
75
  "gitHead": "d935eefa5aa8d1009a2398cfac2c1e4ee9aeb6b6",
76
76
  "publishConfig": {
package/src/api/errors.ts CHANGED
@@ -120,10 +120,11 @@ export const errorHandler: ErrorHandler = (err, c) => {
120
120
  `❌ [API] ${c.req.method} ${c.req.path} → ${statusCode} ${code}: ${logMessage}`
121
121
  );
122
122
 
123
- // Suppress the huge stack trace for known missing schema errors (it's noisy and not a code bug)
123
+ // Suppress the huge stack trace for known DB errors (it's noisy and leaks SQL)
124
124
  const causePg = (error.cause && typeof error.cause === "object") ? (error.cause as PgLikeError) : undefined;
125
125
  const pgErrorCode = causePg?.code || error.code;
126
- if (pgErrorCode !== "42703" && pgErrorCode !== "42P01") {
126
+ const suppressStack = pgErrorCode === "42703" || pgErrorCode === "42P01" || (statusCode < 500 && code === "BAD_REQUEST");
127
+ if (!suppressStack) {
127
128
  console.error(error.stack || error);
128
129
  }
129
130
 
package/src/api/server.ts CHANGED
@@ -69,8 +69,11 @@ export class RebaseApiServer {
69
69
  * Setup Hono middleware
70
70
  */
71
71
  private setupMiddleware(): void {
72
- // Security headers
73
- this.router.use("/*", secureHeaders());
72
+ // Security headers — use same-origin-allow-popups for COOP so that
73
+ // OAuth popup flows (Google, etc.) can postMessage back to the opener.
74
+ this.router.use("/*", secureHeaders({
75
+ crossOriginOpenerPolicy: "same-origin-allow-popups"
76
+ }));
74
77
 
75
78
  // CORS — only applied if explicitly configured via `cors` option.
76
79
  // If omitted, the user is expected to configure CORS on their own
@@ -10,26 +10,69 @@ export interface GoogleUserInfo {
10
10
  emailVerified: boolean;
11
11
  }
12
12
 
13
+ export interface GoogleProviderConfig {
14
+ clientId: string;
15
+ /**
16
+ * The OAuth 2.0 client secret from Google Cloud Console.
17
+ *
18
+ * Required for the **authorization code flow** (Path 3), where the
19
+ * frontend sends an authorization `code` and the backend exchanges it
20
+ * server-side for tokens. This is the most secure flow because tokens
21
+ * never touch the browser.
22
+ *
23
+ * When omitted, only ID-token and access-token verification are available
24
+ * (Paths 1 & 2), which rely on the frontend obtaining tokens directly.
25
+ */
26
+ clientSecret?: string;
27
+ }
28
+
13
29
  /**
14
30
  * Creates a Google OAuth Provider integration.
15
- * Supports both ID-token verification (One Tap / renderButton) and
16
- * access-token verification (popup via initTokenClient).
31
+ *
32
+ * Supports three verification paths:
33
+ *
34
+ * **Path 1 – ID Token** (One Tap / Sign In With Google button):
35
+ * Frontend sends `idToken`. Backend verifies cryptographically using
36
+ * Google's public keys. No secret required.
37
+ *
38
+ * **Path 2 – Access Token** (popup via `initTokenClient`):
39
+ * Frontend sends `accessToken`. Backend validates by calling Google's
40
+ * userinfo endpoint. No secret required.
41
+ *
42
+ * **Path 3 – Authorization Code** (most secure, requires `clientSecret`):
43
+ * Frontend sends `code` + `redirectUri`. Backend exchanges the code
44
+ * server-side for an ID token using `clientId` + `clientSecret`, then
45
+ * verifies the ID token. Tokens never touch the browser.
17
46
  */
18
- export function createGoogleProvider(clientId: string): OAuthProvider<{ idToken?: string; accessToken?: string }> {
19
- const googleClient = new OAuth2Client(clientId);
47
+ export function createGoogleProvider(config: GoogleProviderConfig | string): OAuthProvider<{
48
+ idToken?: string;
49
+ accessToken?: string;
50
+ code?: string;
51
+ redirectUri?: string;
52
+ }> {
53
+ const clientId = typeof config === "string" ? config : config.clientId;
54
+ const clientSecret = typeof config === "string" ? undefined : config.clientSecret;
55
+ const googleClient = new OAuth2Client(clientId, clientSecret);
20
56
 
21
57
  return {
22
58
  id: "google",
23
59
  schema: z.object({
24
60
  idToken: z.string().min(1).optional(),
25
- accessToken: z.string().min(1).optional()
61
+ accessToken: z.string().min(1).optional(),
62
+ code: z.string().min(1).optional(),
63
+ redirectUri: z.string().min(1).optional()
26
64
  }).refine(
27
- (data) => data.idToken || data.accessToken,
28
- { message: "Either idToken or accessToken is required" }
65
+ (data) => data.idToken || data.accessToken || (data.code && data.redirectUri),
66
+ { message: "One of idToken, accessToken, or code+redirectUri is required" }
29
67
  ),
30
- verify: async (payload: { idToken?: string; accessToken?: string }): Promise<OAuthProviderProfile | null> => {
68
+ verify: async (payload: {
69
+ idToken?: string;
70
+ accessToken?: string;
71
+ code?: string;
72
+ redirectUri?: string;
73
+ }): Promise<OAuthProviderProfile | null> => {
31
74
  try {
32
- // Path 1: verify an ID token (legacy / One Tap)
75
+ // Path 1: verify an ID token (One Tap / renderButton)
33
76
  if (payload.idToken) {
34
77
  const ticket = await googleClient.verifyIdToken({
35
78
  idToken: payload.idToken,
@@ -38,7 +81,7 @@ export function createGoogleProvider(clientId: string): OAuthProvider<{ idToken?
38
81
 
39
82
  const content = ticket.getPayload();
40
83
  if (!content) {
41
- return null;
84
+ throw new Error("Google ID token payload was empty");
42
85
  }
43
86
 
44
87
  return {
@@ -56,8 +99,7 @@ export function createGoogleProvider(clientId: string): OAuthProvider<{ idToken?
56
99
  { headers: { Authorization: `Bearer ${payload.accessToken}` } }
57
100
  );
58
101
  if (!res.ok) {
59
- console.error("Google userinfo request failed:", res.status);
60
- return null;
102
+ throw new Error(`Google userinfo request failed with status ${res.status}`);
61
103
  }
62
104
  const info = await res.json() as {
63
105
  sub: string;
@@ -66,7 +108,7 @@ export function createGoogleProvider(clientId: string): OAuthProvider<{ idToken?
66
108
  picture?: string;
67
109
  };
68
110
  if (!info.sub || !info.email) {
69
- return null;
111
+ throw new Error("Google userinfo response missing sub or email");
70
112
  }
71
113
  return {
72
114
  providerId: info.sub,
@@ -76,12 +118,101 @@ export function createGoogleProvider(clientId: string): OAuthProvider<{ idToken?
76
118
  };
77
119
  }
78
120
 
79
- return null;
121
+ // Path 3: authorization code exchange (most secure)
122
+ // The frontend obtained a one-time authorization code via the
123
+ // Google OAuth consent screen. We exchange it server-side for
124
+ // tokens, so the access/id tokens never touch the browser.
125
+ if (payload.code && payload.redirectUri) {
126
+ if (!clientSecret) {
127
+ throw new Error(
128
+ "Google authorization code flow requires clientSecret. " +
129
+ "Configure GOOGLE_CLIENT_SECRET in your environment."
130
+ );
131
+ }
132
+
133
+ // Exchange the authorization code for tokens
134
+ const tokenResponse = await fetch("https://oauth2.googleapis.com/token", {
135
+ method: "POST",
136
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
137
+ body: new URLSearchParams({
138
+ code: payload.code,
139
+ client_id: clientId,
140
+ client_secret: clientSecret,
141
+ redirect_uri: payload.redirectUri,
142
+ grant_type: "authorization_code"
143
+ })
144
+ });
145
+
146
+ if (!tokenResponse.ok) {
147
+ const errorBody = await tokenResponse.text();
148
+ throw new Error(`Google token exchange failed (${tokenResponse.status}): ${errorBody}`);
149
+ }
150
+
151
+ const tokenData = await tokenResponse.json() as {
152
+ id_token?: string;
153
+ access_token?: string;
154
+ error?: string;
155
+ error_description?: string;
156
+ };
157
+
158
+ if (tokenData.error) {
159
+ throw new Error(`Google token exchange error: ${tokenData.error} – ${tokenData.error_description || "no details"}`);
160
+ }
161
+
162
+ // Prefer verifying the ID token (cryptographic verification)
163
+ if (tokenData.id_token) {
164
+ const ticket = await googleClient.verifyIdToken({
165
+ idToken: tokenData.id_token,
166
+ audience: clientId
167
+ });
168
+
169
+ const content = ticket.getPayload();
170
+ if (!content) {
171
+ throw new Error("Google ID token payload was empty after code exchange");
172
+ }
173
+
174
+ return {
175
+ providerId: content.sub,
176
+ email: content.email || "",
177
+ displayName: content.name || null,
178
+ photoUrl: content.picture || null
179
+ };
180
+ }
181
+
182
+ // Fallback: use the access token to fetch userinfo
183
+ if (tokenData.access_token) {
184
+ const userInfoRes = await fetch(
185
+ "https://www.googleapis.com/oauth2/v3/userinfo",
186
+ { headers: { Authorization: `Bearer ${tokenData.access_token}` } }
187
+ );
188
+ if (!userInfoRes.ok) {
189
+ throw new Error(`Google userinfo request failed after code exchange (${userInfoRes.status})`);
190
+ }
191
+ const info = await userInfoRes.json() as {
192
+ sub: string;
193
+ email?: string;
194
+ name?: string;
195
+ picture?: string;
196
+ };
197
+ if (!info.sub || !info.email) {
198
+ return null;
199
+ }
200
+ return {
201
+ providerId: info.sub,
202
+ email: info.email,
203
+ displayName: info.name || null,
204
+ photoUrl: info.picture || null
205
+ };
206
+ }
207
+
208
+ throw new Error("Google token exchange returned neither id_token nor access_token");
209
+ }
210
+
211
+ throw new Error("No valid Google credential provided (expected idToken, accessToken, or code+redirectUri)");
80
212
  } catch (error) {
81
- console.error("Failed to verify Google token:", error);
82
- return null;
213
+ console.error("Google OAuth verification failed:", error);
214
+ throw error;
83
215
  }
84
216
  }
85
217
  };
86
218
  }
87
-