Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# emulate


This repository is forked from Vercel Labs' `emulate` project. Useful Software
Co maintains this fork to support deployable emulator surfaces and product
testing flows for our own development and agent-driven use cases.
Expand Down Expand Up @@ -819,6 +820,8 @@ Because the full schema is real, this surface is well suited to testing GraphQL

## Google OAuth + Gmail, Calendar, and Drive APIs

Google ID tokens use RS256 and the instance publishes its public signing keys at `/oauth2/v3/certs`. Verify the signature, instance issuer, client audience, expiry and nonce through OIDC discovery. Signing keys are retained with instance state across hosted eviction; resetting the instance replaces them.

OAuth 2.0, OpenID Connect, and mutable Google Workspace-style surfaces for local inbox, calendar, and drive flows.

- `GET /o/oauth2/v2/auth` - authorization endpoint
Expand Down
3 changes: 3 additions & 0 deletions apps/web/app/docs/google/page.mdx
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# Google API


Google ID tokens use RS256 and the instance publishes its public signing keys at `/oauth2/v3/certs`. Verify the signature, instance issuer, client audience, expiry and nonce through OIDC discovery. Signing keys are retained with instance state across hosted eviction; resetting the instance replaces them.

OAuth 2.0, OpenID Connect, and mutable Google Workspace-style surfaces for local inbox, calendar, and drive flows.

## OAuth & OpenID Connect
Expand Down
3 changes: 3 additions & 0 deletions packages/@emulators/google/README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# @emulators/google


Google ID tokens use RS256 and the instance publishes its public signing keys at `/oauth2/v3/certs`. Verify the signature, instance issuer, client audience, expiry and nonce through OIDC discovery. Signing keys are retained with instance state across hosted eviction; resetting the instance replaces them.

Google OAuth 2.0, OpenID Connect, and mutable Google Workspace-style surfaces for local Gmail, Calendar, and Drive flows.

Part of [emulate](https://github.com/vercel-labs/emulate) — local drop-in replacement services for CI and no-network sandboxes.
Expand Down
2 changes: 1 addition & 1 deletion packages/@emulators/google/src/manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export const manifest: ServiceManifest = {
path: "/.well-known/openid-configuration",
status: "hand-authored",
},
{ operationId: "jwks", method: "GET", path: "/oauth2/v3/certs", status: "partial" },
{ operationId: "jwks", method: "GET", path: "/oauth2/v3/certs", status: "hand-authored" },
{ operationId: "authorize", method: "GET", path: "/o/oauth2/v2/auth", status: "hand-authored" },
{ operationId: "token", method: "POST", path: "/oauth2/token", status: "hand-authored" },
{ operationId: "userinfo", method: "GET", path: "/oauth2/v2/userinfo", status: "hand-authored" },
Expand Down
51 changes: 24 additions & 27 deletions packages/@emulators/google/src/routes/oauth.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { createHash, randomBytes } from "crypto";
import { SignJWT } from "jose";
import type { RouteContext } from "@emulators/core";
import {
escapeHtml,
escapeAttr,

Check warning on line 5 in packages/@emulators/google/src/routes/oauth.ts

View workflow job for this annotation

GitHub Actions / build-and-test

'escapeAttr' is defined but never used. Allowed unused vars must match /^_/u
renderCardPage,
renderErrorPage,
renderUserButton,
Expand All @@ -15,8 +14,7 @@
} from "@emulators/core";
import { getGoogleStore } from "../store.js";
import type { GoogleUser } from "../entities.js";

const JWT_SECRET = new TextEncoder().encode("emulate-google-jwt-secret");
import { googleSigning } from "../signing.js";

type PendingCode = {
email: string;
Expand Down Expand Up @@ -66,30 +64,29 @@
clientId: string,
nonce: string | null,
baseUrl: string,
signing: ReturnType<typeof googleSigning>,
): Promise<string> {
const builder = new SignJWT({
sub: user.uid,
email: user.email,
email_verified: user.email_verified,
name: user.name,
given_name: user.given_name,
family_name: user.family_name,
picture: user.picture,
locale: user.locale,
...(user.hd ? { hd: user.hd } : {}),
...(nonce ? { nonce } : {}),
})
.setProtectedHeader({ alg: "HS256", typ: "JWT" })
.setIssuer(baseUrl)
.setAudience(clientId)
.setIssuedAt()
.setExpirationTime("1h");

return builder.sign(JWT_SECRET);
return signing.sign(
{
sub: user.uid,
email: user.email,
email_verified: user.email_verified,
name: user.name,
given_name: user.given_name,
family_name: user.family_name,
picture: user.picture,
locale: user.locale,
...(user.hd ? { hd: user.hd } : {}),
...(nonce ? { nonce } : {}),
},
baseUrl,
clientId,
);
}

export function oauthRoutes({ app, store, baseUrl, tokenMap }: RouteContext): void {
const gs = getGoogleStore(store);
const signing = googleSigning(store);

// ---------- OIDC Discovery ----------

Expand All @@ -103,7 +100,7 @@
jwks_uri: `${baseUrl}/oauth2/v3/certs`,
response_types_supported: ["code"],
subject_types_supported: ["public"],
id_token_signing_alg_values_supported: ["HS256"],
id_token_signing_alg_values_supported: ["RS256"],
scopes_supported: ["openid", "email", "profile"],
token_endpoint_auth_methods_supported: ["client_secret_post", "client_secret_basic"],
claims_supported: [
Expand All @@ -121,10 +118,10 @@
});
});

// ---------- JWKS (stub) ----------
// ---------- Public signing keys ----------

app.get("/oauth2/v3/certs", (c) => {
return c.json({ keys: [] });
app.get("/oauth2/v3/certs", async (c) => {
return c.json(await signing.jwks());
});

// Google API Discovery document, pointed at this instance.
Expand Down Expand Up @@ -281,7 +278,7 @@
}

const code = typeof body.code === "string" ? body.code : "";
const redirect_uri = typeof body.redirect_uri === "string" ? body.redirect_uri : "";

Check warning on line 281 in packages/@emulators/google/src/routes/oauth.ts

View workflow job for this annotation

GitHub Actions / build-and-test

'redirect_uri' is assigned a value but never used. Allowed unused vars must match /^_/u
const grant_type = typeof body.grant_type === "string" ? body.grant_type : "";
const code_verifier = typeof body.code_verifier === "string" ? body.code_verifier : undefined;
const bodyClientId = typeof body.client_id === "string" ? body.client_id : "";
Expand Down Expand Up @@ -387,7 +384,7 @@
clientId: pending.clientId,
});

const idToken = await createIdToken(user, pending.clientId, pending.nonce, baseUrl);
const idToken = await createIdToken(user, pending.clientId, pending.nonce, baseUrl, signing);

debug("google.oauth", `[Google token] issued token for ${user.email}`);

Expand Down
48 changes: 48 additions & 0 deletions packages/@emulators/google/src/signing.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { exportJWK, generateKeyPair, importJWK, SignJWT, type JWK, type JWTPayload } from "jose";
import type { Store } from "@emulators/core";
import { randomBytes } from "node:crypto";

interface SigningKeys {
kid: string;
publicKey: JWK;
privateKey: JWK;
}

/** Persist each instance's signing material so published keys survive hosted eviction. */
export function googleSigning(store: Store) {
let pending: Promise<SigningKeys> | undefined;
const keys = (): Promise<SigningKeys> => {
const saved = store.getData<SigningKeys>("google.oauth.signingKeys");
if (saved) return Promise.resolve(saved);
if (pending) return pending;
pending = (async () => {
const pair = await generateKeyPair("RS256", { extractable: true });
const value = {
kid: randomBytes(16).toString("hex"),
publicKey: await exportJWK(pair.publicKey),
privateKey: await exportJWK(pair.privateKey),
};
store.setData("google.oauth.signingKeys", value);
return value;
})().finally(() => {
pending = undefined;
});
return pending;
};
return {
async jwks() {
const value = await keys();
return { keys: [{ ...value.publicKey, kid: value.kid, alg: "RS256", use: "sig" }] };
},
async sign(payload: JWTPayload, issuer: string, audience: string) {
const value = await keys();
return new SignJWT(payload)
.setProtectedHeader({ alg: "RS256", typ: "JWT", kid: value.kid })
.setIssuer(issuer)
.setAudience(audience)
.setIssuedAt()
.setExpirationTime("1h")
.sign(await importJWK(value.privateKey, "RS256"));
},
};
}
3 changes: 3 additions & 0 deletions packages/emulate/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,9 @@ Global catalog:
/_emulate/seed to load fixtures, /_emulate/faults to arm one-shot failures,
and /_emulate/ledger to validate API calls.

Google OIDC signs ID tokens with RS256 and publishes verification keys at
/oauth2/v3/certs. Its discovery issuer is the instance URL.

Hosted services:
Available services include vercel, github, gitlab, google, slack, apple,
microsoft, okta, aws, resend, stripe, mongoatlas, clerk, spotify, x, workos,
Expand Down
2 changes: 2 additions & 0 deletions skills/google/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ description: Emulated Google OAuth 2.0, OpenID Connect, Gmail, Calendar, and Dri
allowed-tools: Bash(npx emulate:*), Bash(emulate:*), Bash(curl:*)
---

Google ID tokens use RS256 and the instance publishes its public signing keys at `/oauth2/v3/certs`. Verify the signature, instance issuer, client audience, expiry and nonce through OIDC discovery. Signing keys are retained with instance state across hosted eviction; resetting the instance replaces them.

# Google OAuth 2.0 / OIDC + Gmail, Calendar & Drive Emulator

OAuth 2.0 and OpenID Connect emulation with authorization code flow, PKCE support, ID tokens, OIDC discovery, refresh tokens, plus Gmail, Google Calendar, and Google Drive REST API surfaces.
Expand Down
Loading