The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Harness backend says who holds a Harness sign-in, for Grid (GET /api/grid/profile) (#930)
Kelvinb9bbc76fc487
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex f08b7c6f7..6e82a09ae 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -113,6 +113,16 @@ model User {// `lastAttribution` is the latest tagged sign-in.signUpAttribution SignInAttribution?lastAttribution SignInAttribution?+ // The account's Google subject as this backend last read it LIVE from the Autonomous profile+ // (lib/googleSubject.ts, ADR 0046), so `GET /api/grid/profile` can answer for a computer signed in+ // by QR, whose token Autonomous cannot read. `googleSubCheckedAt` unset means never checked — and on+ // MongoDB that is ABSENT on every row written before today as well as null, so a filter on+ // `googleSubCheckedAt: null` alone misses the legacy rows (the trap `Machine.deletedAt` and+ // routes/grid.ts document); `UserService.recordGoogleSubject` adds `isSet: false`. Once checked, a+ // null `googleSub` means "this account has no Google identity".+ // Both are internal: `UserService.toPublic` leaves them out of every user-describing response.+ googleSub String?+ googleSubCheckedAt DateTime?createdAt DateTime @default(now())updatedAt DateTime @updatedAtdiff --git a/backend/src/lib/googleSubject.ts b/backend/src/lib/googleSubject.tsnew file mode 100644index 000000000..f7b429dc4--- /dev/null+++ b/backend/src/lib/googleSubject.ts@@ -0,0 +1,242 @@+import { env } from '../config/env.js'+import { normalizeUserEmail, userService } from '../services/UserService.js'+import { logger } from '../utils/logger.js'+import { autonomousEnvironmentConfig, type AutonomousEnvironment } from './autonomousEnvironment.js'++/**+ * The account's **Google subject**, as this backend last read it live from the Autonomous profile.+ *+ * Why it is kept at all (ADR 0046, in the autonomous-grid repository): the Grid control plane keys a+ * person's Grid account by their Google subject when they have one, and learns it by asking who holds+ * a Harness sign-in token. For an Autonomous token the profile can be read live. A computer signed in+ * by QR holds a token Harness issued itself, which Autonomous cannot read — so the only way to answer+ * for it is from what was read the last time one of the account's Autonomous tokens was seen.+ *+ * Three rules make that stored value safe to key a permanent account on:+ * - **Every successful live read overwrites it**, including to "none" — a fill below, or the profile+ * route. A stored value is never kept over a fresher answer.+ * - **Never checked is not "none".** An account this backend has never read is answered 409 by the+ * profile route, not keyed by its customer id: an account key is permanent, and guessing for a+ * Google-linked account would split it from its website sign-in for good.+ * - **The stored-versus-live check**: when a live read disagrees with what was stored, one log line+ * names the fields that differ — never a value. It is what gates the Grid cut-over.+ *+ * ⚠️ The profile body is a credential: `customer_socials[].token` is the person's live Google OAuth+ * token. [readLiveProfile] copies four fields out of it and drops the rest; nothing here logs, stores+ * or returns any other part of it.+ */++/** How long a check stands before an Autonomous-token request reads the profile again. */+export const GOOGLE_SUBJECT_RECHECK_MS = 7 * 24 * 60 * 60 * 1000++const GOOGLE_SOURCE = 'google'++/** All a live read keeps of an Autonomous profile. `googleSub` null = the account has no Google identity. */+export interface LiveProfile {+ customerId: string+ email: string+ fullName: string+ googleSub: string | null+}++/** The stored half of the comparison: what a user row says, absent fields included. */+export interface StoredGoogleSubject {+ id: string+ email: string+ externalId: string+ googleSub?: string | null+ googleSubCheckedAt?: Date | null+}++export class LiveProfileError extends Error {+ constructor(message: string, readonly code: 'REJECTED' | 'UNAVAILABLE') {+ super(message)+ this.name = 'LiveProfileError'+ }+}++/**+ * Read the full Autonomous profile for this token, live — never the authentication cache, never the+ * identity endpoint (it answers from the token alone and carries no socials). Production plane only:+ * a Google subject is only ever learned from production.+ *+ * REJECTED = Autonomous said the token is not good (401/403, or its envelope saying so).+ * UNAVAILABLE = no answer we can read (unreachable, 5xx, a malformed body).+ */+export async function readLiveProfile(token: string, fetchImpl: typeof fetch = fetch): Promise<LiveProfile> {+ const { ssoProfileUrl } = autonomousEnvironmentConfig('prod')+ let res: Response+ try {+ res = await fetchImpl(ssoProfileUrl, {+ method: 'GET',+ headers: {+ Accept: 'application/json',+ // The account API refuses every /api/v1 request without a locale here (see ssoAuth.ts).+ Location: 'en-US',+ Authorization: `Bearer ${token}`,+ },+ signal: AbortSignal.timeout(env.SSO_PROFILE_TIMEOUT_MS),+ })+ } catch {+ throw new LiveProfileError('Autonomous profile service unreachable', 'UNAVAILABLE')+ }+ if (res.status === 401 || res.status === 403) {+ throw new LiveProfileError('Autonomous rejected the token', 'REJECTED')+ }+ if (!res.ok) throw new LiveProfileError(`Autonomous profile service returned ${res.status}`, 'UNAVAILABLE')++ let raw: unknown+ try { raw = await res.json() } catch {+ throw new LiveProfileError('Autonomous profile service returned invalid JSON', 'UNAVAILABLE')+ }+ return profileFrom(raw)+}++/** The four fields, out of Autonomous' own envelope. Defensive before every index. */+function profileFrom(raw: unknown): LiveProfile {+ const unreadable = (what: string) => new LiveProfileError(`Autonomous profile unreadable (${what})`, 'UNAVAILABLE')+ if (!raw || typeof raw !== 'object') throw unreadable('body')+ const body = raw as { status?: unknown; message?: unknown; data?: unknown }+ if (body.status !== 1) {+ // Its own envelope saying no under an HTTP 200; the same reading ssoAuth.ts gives it.+ if (typeof body.message === 'string' && /invalid|expired|unauthorized/i.test(body.message)) {+ throw new LiveProfileError('Autonomous rejected the token', 'REJECTED')+ }+ throw unreadable('status')+ }+ if (!body.data || typeof body.data !== 'object') throw unreadable('data')+ const data = body.data as Record<string, unknown>+ const customerId = text(data.id)+ const email = normalizeUserEmail(text(data.email))+ if (!customerId) throw unreadable('id')+ if (!email) throw unreadable('email')++ // Absent or null is an account with no social sign-in (an email-registered account has no key).+ const socials = data.customer_socials ?? []+ if (!Array.isArray(socials)) throw unreadable('customer_socials')+ const google = socials.find((s): s is Record<string, unknown> =>+ !!s && typeof s === 'object' && text((s as Record<string, unknown>).source).toLowerCase() === GOOGLE_SOURCE)+ let googleSub: string | null = null+ if (google) {+ googleSub = text(google.uid)+ // A Google identity we cannot read is not "no Google": recording none would key a Google-linked+ // account by its customer id, a second key for one person.+ if (!googleSub) throw unreadable('google uid')+ }+ const fullName = text(data.full_name) || (google ? text(google.full_name) : '')+ return { customerId, email, fullName, googleSub }+}++/**+ * One trimmed string, or ''. `uid` is a string in every sample but a number in the API's schema — and+ * a 21-digit Google subject parsed as a JSON number has already lost its last digits (JS doubles hold+ * 15–16). So a number counts only when it is exact; anything else reads as missing, which for a+ * Google social is "unreadable", never a rounded subject keyed on for good.+ */+function text(value: unknown): string {+ if (typeof value === 'string') return value.trim()+ if (typeof value === 'number' && Number.isSafeInteger(value)) return String(value)+ return ''+}++/** Never checked, or checked longer ago than the recheck interval. Absent and null are both "never". */+export function needsGoogleSubjectCheck(user: Pick<StoredGoogleSubject, 'googleSubCheckedAt'>, now = Date.now()): boolean {+ const checkedAt = user.googleSubCheckedAt+ if (!(checkedAt instanceof Date) || Number.isNaN(checkedAt.getTime())) return true+ return now - checkedAt.getTime() > GOOGLE_SUBJECT_RECHECK_MS+}++/**+ * Overwrite the stored Google subject with what a live read said, and run the stored-versus-live check+ * against what was there. `readAt` is when the read BEGAN: a slower read never replaces a fresher one.+ *+ * Two guards, one log line each, field names only — never a value from either side:+ * - **The read must be of THIS row's customer.** A live profile naming another customer id or email+ * than the row (two Autonomous accounts reaching one email) is not recorded at all: its Google+ * subject would then be answered for a computer of the row's account. Together with the upsert+ * forgetting the Google subject whenever a row's production subject changes+ * (`UserService.upsertFromSso`), a stored Google subject is always the row's own customer's.+ * - **The stored-versus-live check** runs only on an account checked before — a first fill has+ * nothing stored to disagree with — and by the guard above it can only ever name `google_sub`.+ */+export async function recordLiveProfile(stored: StoredGoogleSubject, live: LiveProfile, readAt = new Date()): Promise<void> {+ const otherCustomer = [+ ...(stored.externalId !== live.customerId ? ['customer_id'] : []),+ ...(normalizeUserEmail(stored.email ?? '') !== live.email ? ['email'] : []),+ ]+ if (otherCustomer.length > 0) {+ logger.warn('google subject: live read is of another customer than the row; not recorded', { userId: stored.id, fields: otherCustomer })+ return+ }+ if (stored.googleSubCheckedAt && (stored.googleSub ?? null) !== live.googleSub) {+ logger.warn('google subject: stored and live disagree', { userId: stored.id, fields: ['google_sub'] })+ }+ await userService.recordGoogleSubject(stored.id, live.googleSub, readAt)+}++// One fill per account per process at a time. Across processes (a pm2 cluster) two workers can each+// read an account's profile once in the window before the first write lands; that is the whole cost,+// once per account per recheck interval, and it is what keeps a fill free of any shared lock.+const filling = new Set<string>()++/** How many fills one process runs at once. Past it a fill is DROPPED, not queued: the account stays+ * unchecked and a later request picks it up. Bounds the burst after a deploy reconnects every daemon. */+export const MAX_CONCURRENT_FILLS = 16++/** After a failed read, how long this process leaves the account alone. A read that keeps failing+ * (Autonomous degraded, a profile it cannot serve) must not become one storefront read per request. */+export const FILL_RETRY_AFTER_MS = 60_000+const FILL_RETRY_ENTRIES_MAX = 10_000+const retryAfter = new Map<string, number>()++function backOff(userId: string): void {+ if (retryAfter.size >= FILL_RETRY_ENTRIES_MAX) {+ const oldest = retryAfter.keys().next().value+ if (oldest !== undefined) retryAfter.delete(oldest)+ }+ retryAfter.set(userId, Date.now() + FILL_RETRY_AFTER_MS)+}++/** Forget this process' in-flight and back-off state. Tests only. */+export function resetGoogleSubjectFill(): void {+ filling.clear()+ retryAfter.clear()+}++/**+ * After an Autonomous token authenticates: if the account is unchecked or its check is older than+ * [GOOGLE_SUBJECT_RECHECK_MS], read the profile once and record the answer. Fire-and-forget — the+ * request never waits for it, and nothing it does can fail the request. A failed read records+ * nothing, so the account stays unchecked and is retried by a request after [FILL_RETRY_AFTER_MS].+ */+export function scheduleGoogleSubjectFill(+ token: string,+ user: StoredGoogleSubject,+ autonomousEnv: AutonomousEnvironment,+): void {+ try {+ if (autonomousEnv !== 'prod') return+ if (!needsGoogleSubjectCheck(user) || filling.has(user.id)) return+ if ((retryAfter.get(user.id) ?? 0) > Date.now()) return+ if (filling.size >= MAX_CONCURRENT_FILLS) return+ filling.add(user.id)+ const readAt = new Date()+ void (async () => {+ try {+ await recordLiveProfile(user, await readLiveProfile(token), readAt)+ retryAfter.delete(user.id)+ } catch (err) {+ backOff(user.id)+ // A status or a field name, never a value from the body.+ logger.warn('google subject fill failed', {+ userId: user.id,+ reason: err instanceof LiveProfileError ? err.code : 'RECORD_FAILED',+ })+ } finally {+ filling.delete(user.id)+ }+ })()+ } catch {+ // Deciding whether to fill must never cost the caller its sign-in either.+ }+}diff --git a/backend/src/lib/gridProfile.ts b/backend/src/lib/gridProfile.tsnew file mode 100644index 000000000..a152fa870--- /dev/null+++ b/backend/src/lib/gridProfile.ts@@ -0,0 +1,145 @@+import { isProvisionalUserEmail, userService } from '../services/UserService.js'+import { logger } from '../utils/logger.js'+import { storedAutonomousEnvironment } from './autonomousEnvironment.js'+import { LiveProfileError, readLiveProfile, recordLiveProfile, type LiveProfile } from './googleSubject.js'+import type { AuthUser } from './ssoAuth.js'++/**+ * What `GET /api/grid/profile` answers: who holds this Harness sign-in token, for the Grid control+ * plane (grid-apis `/v1/grid/auth/harness`). ADR 0046 in the autonomous-grid repository is the record.+ *+ * ⚠️ **The success body is Autonomous-shaped on purpose — a contract, not an accident.** It is the+ * subset of the Autonomous account API's `/me/profile` answer that the control plane's+ * `account_api.identity_from_profile` already parses: an INTEGER `status: 1` (not this backend's+ * usual `{success, data}`), and `data.{id, email, full_name, customer_socials[{source, uid}]}`. The+ * account key rules stay in the control plane, which is why the shape is theirs. Do not "tidy" it+ * into `sendSuccess`; `routes/fixtures/gridProfile.contract.json` pins it, and grid-apis holds a+ * hand-duplicated copy that its own tests parse.+ *+ * ⚠️ **409 means exactly one thing here: the account's Google subject is not yet known.** The+ * control plane branches on that status alone, without reading a code, so no other condition on this+ * route may ever produce a 409.+ */++export const GRID_PROFILE_PATH = '/api/grid/profile'++export interface GridProfileBody {+ status: 1+ data: { id: string; email: string; full_name: string; customer_socials: Array<{ source: 'google'; uid: string }> }+}++export type GridProfileAnswer =+ | { status: 200; body: GridProfileBody }+ | { status: 401 | 403 | 409 | 429 | 503; code: string; message: string }++/**+ * Live reads one account may cause through this route per minute, in this process. The control plane+ * asks once per Grid sign-in; anything past this is somebody looping the route with their own+ * Autonomous token to make this backend hammer the storefront from its own address — which every+ * user's token validation shares. A computer sign-in reads nothing upstream and is not counted.+ */+export const GRID_PROFILE_LIVE_READS_PER_MINUTE = 10+const LIVE_READ_WINDOW_MS = 60_000+const LIVE_READ_ENTRIES_MAX = 10_000+const liveReads = new Map<string, number[]>()++/** Count one live read for this account; false when it is over the limit. */+function admitLiveRead(userId: string, now = Date.now()): boolean {+ const recent = (liveReads.get(userId) ?? []).filter((at) => now - at < LIVE_READ_WINDOW_MS)+ if (recent.length >= GRID_PROFILE_LIVE_READS_PER_MINUTE) return false+ if (!liveReads.has(userId) && liveReads.size >= LIVE_READ_ENTRIES_MAX) {+ const oldest = liveReads.keys().next().value+ if (oldest !== undefined) liveReads.delete(oldest)+ }+ liveReads.set(userId, [...recent, now])+ return true+}++/** Forget the per-account live read counts. Tests only. */+export function resetGridProfileLimits(): void {+ liveReads.clear()+}++/** Only these fields, and never a social's `token`, whatever the source held. */+export function gridProfileBody(profile: LiveProfile): GridProfileBody {+ return {+ status: 1,+ data: {+ id: profile.customerId,+ email: profile.email,+ full_name: profile.fullName,+ customer_socials: profile.googleSub ? [{ source: 'google', uid: profile.googleSub }] : [],+ },+ }+}++const refuse = (status: 401 | 403 | 409 | 429 | 503, code: string, message: string): GridProfileAnswer => ({ status, code, message })++const UNAUTHORIZED = refuse(401, 'UNAUTHORIZED', 'Unauthorized')+const STAGING_PLANE = refuse(403, 'STAGING_PLANE', 'This account signs in through the staging Autonomous plane, which Grid does not accept')+const PROVISIONAL = refuse(403, 'PROVISIONAL_ACCOUNT', "This account's Autonomous identity is not known yet; sign in to Harness with Google, Apple or your email first")++/** A customer id this backend minted itself (staging-created or local accounts), or a device's placeholder row. */+function isProvisional(user: { email: string; externalId: string }): boolean {+ return isProvisionalUserEmail(user.email) || user.externalId.startsWith('local-')+}++/** The answer for this caller. `token` is the bearer the authentication middleware already accepted. */+export async function answerGridProfile(caller: AuthUser, token: string): Promise<GridProfileAnswer> {+ if (caller.harnessSessionId) return answerHarnessSession(caller)++ // An Autonomous token: read it live. The middleware's acceptance may have come from the+ // authentication cache, and a token Autonomous revoked a moment ago must not reach Grid from there.+ if (caller.autonomousEnv !== 'prod') return STAGING_PLANE+ const user = await userService.get(caller.sub)+ if (!user) return UNAUTHORIZED+ if (storedAutonomousEnvironment(user.autonomousEnv) !== 'prod') return STAGING_PLANE++ if (!admitLiveRead(user.id)) {+ return refuse(429, 'TOO_MANY_REQUESTS', 'Too many Grid profile reads for this account; try again in a minute')+ }++ let live: LiveProfile+ const readAt = new Date()+ try {+ live = await readLiveProfile(token)+ } catch (err) {+ if (err instanceof LiveProfileError && err.code === 'REJECTED') {+ return refuse(401, 'UNAUTHORIZED', 'Autonomous rejected this sign-in')+ }+ return refuse(503, 'AUTH_SERVICE_UNAVAILABLE', 'The Autonomous account service could not be reached; try again in a moment')+ }+ try {+ await recordLiveProfile(user, live, readAt)+ } catch {+ // The answer is the live read's either way; a failed write only leaves the stored value older.+ logger.warn('grid profile: could not record the live read', { userId: user.id })+ }+ return { status: 200, body: gridProfileBody(live) }+}++/** A sign-in Harness issued itself: only a computer's, answered from what was last read live. */+async function answerHarnessSession(caller: AuthUser): Promise<GridProfileAnswer> {+ // A phone never calls Grid, and a lost phone must not become a long-lived Grid session.+ if (caller.harnessSessionKind !== 'computer') {+ return refuse(403, 'PHONE_SIGN_IN', 'A phone sign-in cannot be used for Grid; sign in on a computer')+ }+ const user = await userService.get(caller.sub)+ if (!user) return UNAUTHORIZED+ if (storedAutonomousEnvironment(user.autonomousEnv) !== 'prod') return STAGING_PLANE+ if (isProvisional(user)) return PROVISIONAL+ const checkedAt = user.googleSubCheckedAt+ if (!(checkedAt instanceof Date) || Number.isNaN(checkedAt.getTime())) {+ return refuse(409, 'GOOGLE_SUBJECT_UNKNOWN',+ "Harness hasn't confirmed this account's Google identity yet; sign in to Harness once with Google, Apple or your email on any device, then try again")+ }+ return {+ status: 200,+ body: gridProfileBody({+ customerId: user.externalId,+ email: user.email,+ fullName: user.name ?? '',+ googleSub: user.googleSub ?? null,+ }),+ }+}diff --git a/backend/src/lib/ssoAuth.test.ts b/backend/src/lib/ssoAuth.test.tsindex 30ccb3501..7bc042eb9 100644--- a/backend/src/lib/ssoAuth.test.ts+++ b/backend/src/lib/ssoAuth.test.ts@@ -250,7 +250,9 @@ describe('authenticated user resolution', () => {it('asks the profile service once for a token used on back-to-back requests', async () => {profileFetch('prod-sub-1', '[email protected]')- const existing = { id: 'u1', email: '[email protected]', externalId: 'prod-sub-1', role: 'user', autonomousEnv: 'prod' }+ // Google subject checked today, so the fill (lib/googleSubject.ts) has nothing to read and every+ // `fetch` counted here is a validation.+ const existing = { id: 'u1', email: '[email protected]', externalId: 'prod-sub-1', role: 'user', autonomousEnv: 'prod', googleSubCheckedAt: new Date() }findByEmail.mockResolvedValue(existing)upsertFromSso.mockResolvedValue(existing)diff --git a/backend/src/lib/ssoAuth.ts b/backend/src/lib/ssoAuth.tsindex 1f13399ac..eac21d15a 100644--- a/backend/src/lib/ssoAuth.ts+++ b/backend/src/lib/ssoAuth.ts@@ -11,6 +11,7 @@ import {} from './autonomousEnvironment.js'import { createSsoProfileCache, type SharedProfileStore } from './ssoProfileCache.js'import { isHarnessAccessToken } from './harnessTokenFormat.js'+import { scheduleGoogleSubjectFill } from './googleSubject.js'import type { SignInAttribution } from './signInAttribution.js'/** Internal identity attached to authenticated backend requests and user WebSockets. */@@ -193,11 +194,15 @@ export async function authenticateAccessToken(enforceEnv = true,allowHarnessSession = true,signUpAttribution,+ learnGoogleSubject = true,}: {enforceEnv?: booleanallowHarnessSession?: boolean | 'computer'/** The sign-in's tags (lib/signInAttribution.ts), kept on the account only if this creates it. */signUpAttribution?: SignInAttribution+ /** FALSE where the caller reads the profile live itself (`GET /api/grid/profile`), so one request+ * is one read and one stored-versus-live line, not two. */+ learnGoogleSubject?: boolean} = {},): Promise<AuthUser> {// A sign-in Harness issued itself — a phone signed in by scanning a computer's QR. It names its@@ -242,5 +247,9 @@ export async function authenticateAccessToken(...metadata,...(signUpAttribution ? { signUpAttribution } : {}),})+ // Learn the account's Google subject while an Autonomous token is in hand, so a computer of the same+ // account signed in by QR can be answered later (lib/googleSubject.ts). Not awaited, never throws.+ // Here and not in the REST hook, because a daemon that only holds a socket authenticates here too.+ if (learnGoogleSubject) scheduleGoogleSubjectFill(token, user, autonomousEnv)return { sub: user.id, email: user.email, role: user.role, autonomousEnv }}diff --git a/backend/src/middlewares/authMiddleware.ts b/backend/src/middlewares/authMiddleware.tsindex f128a9e23..abaaf3d76 100644--- a/backend/src/middlewares/authMiddleware.ts+++ b/backend/src/middlewares/authMiddleware.ts@@ -5,6 +5,11 @@ import { ForbiddenError } from '../errors/index.js'import { parseAutonomousEnvironment, type AutonomousEnvironment } from '../lib/autonomousEnvironment.js'import { countryCodeFromHeaders, stampUserCountry } from '../lib/clientGeo.js'import { isPublicCommunityRead } from '../lib/communityAccess.js'+import { GRID_PROFILE_PATH } from '../lib/gridProfile.js'++/** By the matched route, not the raw URL, so an encoded spelling of the path is the same route. */+const isGridProfileRequest = (request: FastifyRequest): boolean =>+ (request.routeOptions?.url ?? request.url.split('?')[0]) === GRID_PROFILE_PATH/*** Public local routes (no user access token). Data-plane requests never reach Fastify — they're@@ -85,14 +90,19 @@ export function registerAuthMiddleware(} catch {return reply.code(400).send({ success: false, error: { code: 'INVALID_AUTONOMOUS_ENV', message: 'Invalid Autonomous environment' } })}- const auth = await resolveSsoAuth(token, authenticate, autonomousEnv)+ // The Grid profile route reads the profile live and records it itself; a fill on top of that would+ // be a second storefront read and a second stored-versus-live line for one request.+ const auth = await resolveSsoAuth(token, authenticate, autonomousEnv, isGridProfileRequest(request))if ('user' in auth) {request.user = auth.user// Where the person is, per Cloudflare (`CF-IPCountry`, absent off-Cloudflare). Every control-plane// call comes from their own computer, which is what makes this — and not the daemon's socket —// the "user country" signal. Fire-and-forget and rate-floored inside; never on the request path.+ //+ // Except the Grid profile route: its caller is the Grid control plane asking on the person's+ // behalf, from a datacenter, and stamping that would relabel them (routes/grid.ts).const countryCode = countryCodeFromHeaders(request.headers)- if (countryCode) void stampUserCountry(auth.user.sub, countryCode)+ if (countryCode && !isGridProfileRequest(request)) void stampUserCountry(auth.user.sub, countryCode)return}return reply.code(auth.status).send({@@ -110,6 +120,7 @@ export async function resolveSsoAuth(token: string,authenticate: typeof authenticateAccessToken = authenticateAccessToken,autonomousEnv: AutonomousEnvironment = 'prod',+ readsProfileItself = false,): Promise<| { user: AuthUser }| {@@ -120,7 +131,11 @@ export async function resolveSsoAuth(}> {try {- return { user: await authenticate(token, autonomousEnv) }+ return {+ user: await (readsProfileItself+ ? authenticate(token, autonomousEnv, { learnGoogleSubject: false })+ : authenticate(token, autonomousEnv)),+ }} catch (err) {if (err instanceof SsoAuthError && err.code === 'AUTH_SERVICE_UNAVAILABLE') {return { status: 503, code: 'AUTH_SERVICE_UNAVAILABLE', message: 'Authentication service unavailable' }diff --git a/backend/src/routes/fixtures/README.md b/backend/src/routes/fixtures/README.mdnew file mode 100644index 000000000..cb3af9542--- /dev/null+++ b/backend/src/routes/fixtures/README.md@@ -0,0 +1,11 @@+# Contract fixtures++`gridProfile.contract.json` is what `GET /api/grid/profile` answers for one known account (a+Google-linked one), in the Autonomous profile shape the Grid control plane parses — ADR 0046 in the+autonomous-grid repository.++**It is hand-duplicated in grid-apis** (`tests/fixtures/harness_grid_profile.contract.json`), the+cross-repo lockstep convention: there is no code dependency between the repositories, so each side+pins its own copy. `routes/gridProfile.test.ts` asserts this route produces it; grid-apis asserts it+parses to the expected identity and account key. Change both copies together — changing one alone+fails a test on that side, which is the point.diff --git a/backend/src/routes/fixtures/gridProfile.contract.json b/backend/src/routes/fixtures/gridProfile.contract.jsonnew file mode 100644index 000000000..851e47e01--- /dev/null+++ b/backend/src/routes/fixtures/gridProfile.contract.json@@ -0,0 +1,11 @@+{+ "status": 1,+ "data": {+ "id": "65f1a2b3c4d5e6f708192a3b",+ "email": "[email protected]",+ "full_name": "Grid Contract",+ "customer_socials": [+ { "source": "google", "uid": "104857600000000000042" }+ ]+ }+}diff --git a/backend/src/routes/grid.ts b/backend/src/routes/grid.tsindex 610e279c1..ed556cf76 100644--- a/backend/src/routes/grid.ts+++ b/backend/src/routes/grid.ts@@ -1,7 +1,9 @@import type { FastifyInstance } from 'fastify'import { prisma } from '../lib/prisma.js'-import { sendSuccess } from '../utils/response.js'+import { sendError, sendSuccess } from '../utils/response.js'import { harnessGridName } from '../lib/gridName.js'+import { answerGridProfile, GRID_PROFILE_PATH } from '../lib/gridProfile.js'+import { bearerToken } from '../lib/ssoAuth.js'/*** `POST /api/grid/name` — read the account's grid name, minting it on the first ask.@@ -37,4 +39,30 @@ export async function gridRoutes(app: FastifyInstance): Promise<void> {const existing = await prisma.user.findUnique({ where: { id: userId }, select: { gridName: true } })return sendSuccess(reply, { gridName: existing?.gridName ?? minted })})++ /**+ * `GET /api/grid/profile` — GRID-ONLY. Who holds this Harness sign-in token, asked by the Grid+ * control plane (grid-apis `POST /v1/grid/auth/harness`) with the person's token as the bearer.+ *+ * ⚠️ **Autonomous-shaped, not Harness-shaped, and that is the contract** (ADR 0046 in the+ * autonomous-grid repository; `lib/gridProfile.ts`): the success body is `{status: 1, data: {id,+ * email, full_name, customer_socials}}`, written directly — never through `sendSuccess`. Do not tidy+ * it. `fixtures/gridProfile.contract.json` pins it, and grid-apis parses a copy of that file.+ *+ * No parameter names an account — path, query and body are all ignored; the account is the token's.+ * The authentication middleware does not stamp the user's country for this path: the caller is a+ * server acting for the person, not their device.+ *+ * Autonomous token → a live profile read (Autonomous 401 → 401, unreachable or 5xx → 503)+ * computer sign-in → the stored values; never checked → 409 (and 409 means only that here)+ * phone sign-in, staging-plane account, provisional customer id → 403+ * more than GRID_PROFILE_LIVE_READS_PER_MINUTE live reads for one account → 429+ */+ app.get(GRID_PROFILE_PATH, async (req, reply) => {+ const answer = await answerGridProfile(req.user!, bearerToken(req.headers['authorization'])!)+ // A person's email, name and Google subject: nothing between here and the caller may keep it.+ reply.header('Cache-Control', 'no-store')+ if (answer.status === 200) return reply.code(200).send(answer.body)+ return sendError(reply, answer.message, answer.code, answer.status)+ })}diff --git a/backend/src/routes/gridProfile.test.ts b/backend/src/routes/gridProfile.test.tsnew file mode 100644index 000000000..1fb5cde46--- /dev/null+++ b/backend/src/routes/gridProfile.test.ts@@ -0,0 +1,646 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import Fastify, { type FastifyInstance } from 'fastify'+import { readFileSync } from 'node:fs'+import { join } from 'node:path'++// The contract the control plane (grid-apis) parses, hand-duplicated there — see the fixture's README+// and ADR 0046. Changing either copy alone fails a test on that side.+const contract = JSON.parse(readFileSync(join(import.meta.dirname, 'fixtures', 'gridProfile.contract.json'), 'utf-8')) as {+ status: number+ data: { id: string; email: string; full_name: string; customer_socials: Array<{ source: string; uid: string }> }+}++// In-memory Redis, Prisma and Harness sessions, so the real authentication middleware, the real user+// mirror, the real Harness sessions and the real Google subject fill all run. Only Autonomous is+// stubbed, at `fetch`.+const fakes = vi.hoisted(() => {+ const redis = new Map<string, string>()+ const sessions: Array<Record<string, unknown> & { id: string }> = []+ const users = new Map<string, Record<string, unknown> & { id: string }>()+ const match = <T extends Record<string, unknown>>(rows: Iterable<T>, where: Record<string, unknown>) =>+ [...rows].find((r) => Object.entries(where).every(([k, v]) => r[k] === v)) ?? null+ const set = (key: string, value: string, ...opts: unknown[]) => {+ if (opts.includes('NX') && redis.has(key)) return null+ if (opts.includes('XX') && !redis.has(key)) return null+ redis.set(key, value)+ return 'OK'+ }+ const pub = {+ set: async (key: string, value: string, ...opts: unknown[]) => set(key, value, ...opts),+ get: async (key: string) => redis.get(key) ?? null,+ del: async (key: string) => (redis.delete(key) ? 1 : 0),+ multi: () => {+ const ops: Array<() => unknown> = []+ const chain = {+ get: (key: string) => { ops.push(() => redis.get(key) ?? null); return chain },+ del: (key: string) => { ops.push(() => (redis.delete(key) ? 1 : 0)); return chain },+ set: (key: string, value: string, ...opts: unknown[]) => { ops.push(() => set(key, value, ...opts)); return chain },+ expire: (key: string) => { ops.push(() => (redis.has(key) ? 1 : 0)); return chain },+ exec: async () => ops.map((op) => [null, op()]),+ }+ return chain+ },+ }+ let nextUser = 1+ const user = {+ findUnique: vi.fn(async ({ where }: { where: Record<string, unknown> }) => {+ const row = match(users.values(), where)+ return row ? { ...row } : null+ }),+ findMany: vi.fn(async () => [...users.values()].map((r) => ({ ...r }))),+ create: vi.fn(async ({ data }: { data: Record<string, unknown> }) => {+ if (match(users.values(), { email: data.email }) || match(users.values(), { externalId: data.externalId })) {+ throw new Error('unique constraint')+ }+ const row = { id: `u${nextUser++}`, role: 'user', autonomousEnv: 'prod', ...data }+ users.set(row.id, row)+ return { ...row }+ }),+ update: vi.fn(async ({ where, data }: { where: { id: string }; data: Record<string, unknown> }) => {+ const row = users.get(where.id)+ if (!row) throw new Error('record to update not found')+ Object.assign(row, data)+ return { ...row }+ }),+ // MongoDB's reading of the one filter the Google subject write uses: `field: null` matches a null+ // and NOT an absent field; `{ isSet: false }` matches only an absent one; `{ lt }` a smaller date.+ updateMany: vi.fn(async ({ where, data }: { where: { id: string; OR: Array<Record<string, unknown>> }; data: Record<string, unknown> }) => {+ const row = users.get(where.id)+ const holds = (cond: Record<string, unknown>) => Object.entries(cond).every(([key, want]) => {+ const has = key in row! && row![key] !== undefined+ if (want === null) return has && row![key] === null+ const op = want as { isSet?: boolean; lt?: Date }+ if (op.isSet === false) return !has+ if (op.lt) return row![key] instanceof Date && (row![key] as Date) < op.lt+ return row![key] === want+ })+ if (!row || !where.OR.some(holds)) return { count: 0 }+ Object.assign(row, data)+ return { count: 1 }+ }),+ }+ const harnessSession = {+ create: vi.fn(async ({ data }: { data: Record<string, unknown> }) => {+ const row = { id: `s${sessions.length + 1}`, revokedAt: null, ...data }+ sessions.push(row); return row+ }),+ findUnique: vi.fn(async ({ where }: { where: Record<string, unknown> }) => match(sessions, where)),+ update: vi.fn(async ({ where, data }: { where: { id: string }; data: Record<string, unknown> }) => {+ const row = match(sessions, where)!; Object.assign(row, data); return row+ }),+ updateMany: vi.fn(async () => ({ count: 0 })),+ }+ const stampUserCountry = vi.fn(async () => undefined)+ return { redis, sessions, users, pub, user, harnessSession, stampUserCountry }+})++vi.mock('../lib/bus.js', () => ({ pub: fakes.pub }))+vi.mock('../lib/prisma.js', () => ({ prisma: { user: fakes.user, harnessSession: fakes.harnessSession } }))+vi.mock('../lib/clientGeo.js', async (importOriginal) => ({+ ...(await importOriginal<typeof import('../lib/clientGeo.js')>()),+ stampUserCountry: fakes.stampUserCountry,+}))++import { clearSsoProfileCache } from '../lib/ssoAuth.js'+import { answerQrSignIn, claimQrSignIn, redeemHandoff, startHandoff, startQrSignIn } from '../lib/harnessSession.js'+import {+ FILL_RETRY_AFTER_MS, GOOGLE_SUBJECT_RECHECK_MS, recordLiveProfile, resetGoogleSubjectFill,+} from '../lib/googleSubject.js'+import { GRID_PROFILE_LIVE_READS_PER_MINUTE, resetGridProfileLimits } from '../lib/gridProfile.js'+import { userService } from '../services/UserService.js'+import { registerAuthMiddleware } from '../middlewares/authMiddleware.js'+import { errorHandler } from '../middlewares/errorHandler.js'+import { gridRoutes } from './grid.js'++const IDENTITY_URL = 'https://apiv2.autonomous.ai/api/v1/me/identity'+const PROFILE_URL = 'https://apiv2.autonomous.ai/api/v1/me/profile'++// The contract's known account, and the person's live Google OAuth token, which Autonomous puts in+// the profile body and which must never leave it.+const CUSTOMER_ID = contract.data.id+const EMAIL = contract.data.email+const FULL_NAME = contract.data.full_name+const GOOGLE_SUB = contract.data.customer_socials[0].uid+const GOOGLE_OAUTH_TOKEN = 'ya29.live-google-oauth-token-never-copied'++/** An Autonomous access token: a JWT-shaped string whose payload names the person. */+function autonomousToken(name = FULL_NAME, nonce = 'n1'): string {+ const payload = Buffer.from(JSON.stringify({ name, nonce })).toString('base64url')+ return `eyJhbGciOiJSUzI1NiJ9.${payload}.signature`+}++function json(status: number, body: unknown): Response {+ return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } })+}++type ProfileAnswer = () => Response | Promise<Response>++const googleProfile = (sub: string | null = GOOGLE_SUB): ProfileAnswer => () => json(200, {+ status: 1,+ message: 'ok',+ data: {+ id: CUSTOMER_ID,+ email: EMAIL,+ full_name: FULL_NAME,+ phone: '+84 000 000 000',+ address: '1 Private Street',+ customer_socials: sub+ ? [+ { source: 'apple', uid: 'apple-uid-1', token: 'apple-token-never-copied' },+ { source: 'google', uid: sub, full_name: FULL_NAME, token: GOOGLE_OAUTH_TOKEN },+ ]+ : [{ source: 'apple', uid: 'apple-uid-1', token: 'apple-token-never-copied' }],+ },+})++/** Autonomous, stubbed per URL. The identity URL proves a token; the profile URL is the full read. */+function stubAutonomous(profile: ProfileAnswer, identity: ProfileAnswer = () => json(200, { status: 1, data: { id: CUSTOMER_ID, email: EMAIL } })) {+ const fetchMock = vi.fn<typeof fetch>(async (url) => {+ const u = String(url)+ if (u === IDENTITY_URL) return identity()+ if (u === PROFILE_URL) return profile()+ throw new Error(`unexpected fetch ${u}`)+ })+ vi.stubGlobal('fetch', fetchMock)+ return {+ fetchMock,+ profileReads: () => fetchMock.mock.calls.filter(([url]) => String(url) === PROFILE_URL).length,+ }+}++function seedUser(fields: Record<string, unknown> = {}): string {+ const row = { id: 'known', email: EMAIL, externalId: CUSTOMER_ID, name: FULL_NAME, role: 'user', autonomousEnv: 'prod', ...fields }+ fakes.users.set(row.id, row as never)+ return row.id+}++async function computerToken(userId: string): Promise<string> {+ const { code, pollToken } = await startQrSignIn({ label: 'MacBook Pro', kind: 'computer' }, {})+ const user = fakes.users.get(userId)!+ await answerQrSignIn(code, { approve: true, userId, email: String(user.email) })+ return (await claimQrSignIn(pollToken))!.token+}++async function phoneToken(userId: string): Promise<string> {+ const { code } = await startHandoff(userId)+ return (await redeemHandoff(code, 'phone'))!.token+}++/** Wait for the fire-and-forget fill to land (or to give up) without sleeping a fixed time. */+const settle = () => new Promise((resolve) => setTimeout(resolve, 20))++describe('GET /api/grid/profile — who holds a Harness sign-in token, in the Autonomous profile shape', () => {+ let app: FastifyInstance+ let logs: string[]++ beforeEach(async () => {+ fakes.redis.clear()+ fakes.sessions.length = 0+ fakes.users.clear()+ fakes.stampUserCountry.mockClear()+ clearSsoProfileCache()+ resetGoogleSubjectFill()+ resetGridProfileLimits()+ logs = []+ for (const level of ['log', 'warn', 'error', 'debug', 'info'] as const) {+ vi.spyOn(console, level).mockImplementation((...args: unknown[]) => { logs.push(args.map(String).join(' ')) })+ }+ app = Fastify()+ app.setErrorHandler(errorHandler)+ registerAuthMiddleware(app)+ await app.register(gridRoutes)+ // "Any route": the fill rides on authentication, not on a particular handler.+ app.get('/api/anything', async () => ({ ok: true }))+ await app.ready()+ })++ afterEach(async () => {+ await app.close()+ vi.useRealTimers()+ vi.unstubAllGlobals()+ vi.restoreAllMocks()+ })++ const get = (url: string, token: string, headers: Record<string, string> = {}) =>+ app.inject({ method: 'GET', url, headers: { authorization: `Bearer ${token}`, ...headers } })++ const leaked = (text: string) =>+ [GOOGLE_OAUTH_TOKEN, 'apple-token-never-copied', '1 Private Street', '+84 000 000 000'].filter((secret) => text.includes(secret))++ describe('the fill, observed across two requests', () => {+ it('learns the Google subject from an Autonomous request, then answers a computer sign-in from it', async () => {+ seedUser()+ stubAutonomous(googleProfile())++ expect((await get('/api/anything', autonomousToken())).statusCode).toBe(200)+ await settle()++ const res = await get('/api/grid/profile', await computerToken('known'))+ expect(res.statusCode).toBe(200)+ expect(res.json()).toEqual(contract)+ })++ it('answers the same contract for an Autonomous token, read live', async () => {+ seedUser()+ stubAutonomous(googleProfile())++ const res = await get('/api/grid/profile', autonomousToken())++ expect(res.statusCode).toBe(200)+ expect(res.json()).toEqual(contract)+ })++ it('records "none" for an account with no Google identity, and answers an empty list', async () => {+ seedUser()+ stubAutonomous(googleProfile(null))++ await get('/api/anything', autonomousToken())+ await settle()++ const res = await get('/api/grid/profile', await computerToken('known'))+ expect(res.statusCode).toBe(200)+ expect(res.json().data.customer_socials).toEqual([])+ })++ it('fills a user row written before the new fields existed (absent, not null)', async () => {+ seedUser() // no googleSub, no googleSubCheckedAt at all+ const autonomous = stubAutonomous(googleProfile())++ await get('/api/anything', autonomousToken())+ await settle()++ expect(autonomous.profileReads()).toBe(1)+ expect(fakes.users.get('known')).toMatchObject({ googleSub: GOOGLE_SUB })+ expect(fakes.users.get('known')!.googleSubCheckedAt).toBeInstanceOf(Date)+ })++ it('fills a row whose fields are null', async () => {+ seedUser({ googleSub: null, googleSubCheckedAt: null })+ const autonomous = stubAutonomous(googleProfile())++ await get('/api/anything', autonomousToken())+ await settle()++ expect(autonomous.profileReads()).toBe(1)+ })++ it('reads once for concurrent requests of one account', async () => {+ seedUser()+ const autonomous = stubAutonomous(googleProfile())++ await Promise.all(['n1', 'n2', 'n3', 'n4', 'n5'].map((n) => get('/api/anything', autonomousToken('x', n))))+ await settle()++ expect(autonomous.profileReads()).toBe(1)+ })++ it('reads the profile at most once in 7 days outside the profile route', async () => {+ seedUser()+ const autonomous = stubAutonomous(googleProfile())++ await get('/api/anything', autonomousToken('x', 'n1'))+ await settle()+ await get('/api/anything', autonomousToken('x', 'n2'))+ await get('/api/anything', autonomousToken('x', 'n3'))+ await settle()++ expect(autonomous.profileReads()).toBe(1)+ })++ it('rechecks once the last check is older than 7 days, and overwrites to "none"', async () => {+ seedUser({ googleSub: GOOGLE_SUB, googleSubCheckedAt: new Date(Date.now() - GOOGLE_SUBJECT_RECHECK_MS - 60_000) })+ const autonomous = stubAutonomous(googleProfile(null))++ await get('/api/anything', autonomousToken())+ await settle()++ expect(autonomous.profileReads()).toBe(1)+ expect(fakes.users.get('known')!.googleSub).toBeNull()+ expect((fakes.users.get('known')!.googleSubCheckedAt as Date).getTime()).toBeGreaterThan(Date.now() - 60_000)+ })++ it('does not recheck a row checked less than 7 days ago', async () => {+ seedUser({ googleSub: GOOGLE_SUB, googleSubCheckedAt: new Date(Date.now() - GOOGLE_SUBJECT_RECHECK_MS + 60_000) })+ const autonomous = stubAutonomous(googleProfile())++ await get('/api/anything', autonomousToken())+ await settle()++ expect(autonomous.profileReads()).toBe(0)+ })++ it('never makes the request wait for the fill', async () => {+ // Its own account: the hung read stays in flight past this test (in production the read's own+ // timeout ends it), and an account with a fill in flight is not filled twice.+ seedUser({ id: 'hung', email: '[email protected]', externalId: 'hung-customer' })+ stubAutonomous(+ () => new Promise<Response>(() => { /* Autonomous never answers the full read */ }),+ () => json(200, { status: 1, data: { id: 'hung-customer', email: '[email protected]' } }),+ )++ const res = await get('/api/anything', autonomousToken())++ expect(res.statusCode).toBe(200)+ })++ it('never fails the request, and leaves the account unchecked so a later request retries', async () => {+ vi.useFakeTimers({ toFake: ['Date'] })+ seedUser()+ const autonomous = stubAutonomous(() => json(502, { message: 'bad gateway' }))++ expect((await get('/api/anything', autonomousToken('x', 'n1'))).statusCode).toBe(200)+ await settle()+ expect(fakes.users.get('known')!.googleSubCheckedAt).toBeUndefined()++ // Not on every request: a read that keeps failing would be a storefront read per request.+ expect((await get('/api/anything', autonomousToken('x', 'n2'))).statusCode).toBe(200)+ await settle()+ expect(autonomous.profileReads()).toBe(1)++ vi.setSystemTime(Date.now() + FILL_RETRY_AFTER_MS + 1)+ expect((await get('/api/anything', autonomousToken('x', 'n3'))).statusCode).toBe(200)+ await settle()+ expect(autonomous.profileReads()).toBe(2)+ })++ it('counts only production-plane reads', async () => {+ seedUser({ autonomousEnv: 'stag', stagExternalId: 'stag-1' })+ const fetchMock = vi.fn<typeof fetch>(async (url) =>+ String(url).includes('staging')+ ? json(200, { status: 1, data: { id: 'stag-1', email: EMAIL, customer_socials: [{ source: 'google', uid: 'stag-google' }] } })+ : json(500, {}))+ vi.stubGlobal('fetch', fetchMock)++ expect((await get('/api/anything', autonomousToken(), { 'x-autonomous-env': 'stag' })).statusCode).toBe(200)+ await settle()++ expect(fetchMock.mock.calls.map(([u]) => String(u)).filter((u) => u.endsWith('/me/profile'))).toEqual([])+ expect(fakes.users.get('known')!.googleSubCheckedAt).toBeUndefined()+ })+ })++ describe('an Autonomous token', () => {+ it('is read live — a token Autonomous now rejects is refused even while the auth cache accepts it', async () => {+ seedUser({ googleSub: GOOGLE_SUB, googleSubCheckedAt: new Date() })+ // The identity endpoint (what authentication asks, and caches) still says yes; the live profile+ // read says the token is gone.+ stubAutonomous(() => json(401, { message: 'Invalid or expired JWT' }))++ const token = autonomousToken()+ expect((await get('/api/anything', token)).statusCode).toBe(200) // primes the auth cache+ const res = await get('/api/grid/profile', token)++ expect(res.statusCode).toBe(401)+ })++ it('answers 503 when Autonomous fails or cannot be reached', async () => {+ seedUser({ googleSub: GOOGLE_SUB, googleSubCheckedAt: new Date() })+ stubAutonomous(() => json(503, {}))+ expect((await get('/api/grid/profile', autonomousToken('x', 'n1'))).statusCode).toBe(503)++ stubAutonomous(() => { throw new TypeError('fetch failed') })+ expect((await get('/api/grid/profile', autonomousToken('x', 'n2'))).statusCode).toBe(503)++ stubAutonomous(() => json(200, { status: 1, data: { id: CUSTOMER_ID, email: EMAIL, customer_socials: [{ source: 'google', uid: '' }] } }))+ expect((await get('/api/grid/profile', autonomousToken('x', 'n3'))).statusCode).toBe(503)+ })++ it('records what it read', async () => {+ seedUser({ googleSub: null, googleSubCheckedAt: null })+ stubAutonomous(googleProfile())++ const res = await get('/api/grid/profile', autonomousToken())++ expect(res.json().data.id).toBe(CUSTOMER_ID)+ expect(fakes.users.get('known')).toMatchObject({ googleSub: GOOGLE_SUB })+ })++ it('takes the customer id from the live profile, not from the row', async () => {+ seedUser({ googleSub: GOOGLE_SUB, googleSubCheckedAt: new Date() })+ // Authentication (the identity endpoint) mirrors one id onto the row; the live profile says another.+ stubAutonomous(googleProfile(), () => json(200, { status: 1, data: { id: 'identity-id', email: EMAIL } }))++ const res = await get('/api/grid/profile', autonomousToken())++ expect(fakes.users.get('known')!.externalId).toBe('identity-id')+ expect(res.json().data.id).toBe(CUSTOMER_ID)+ })++ it('is one read and no fill: the route records its own live read', async () => {+ seedUser({ googleSub: 'stale-sub', googleSubCheckedAt: new Date(Date.now() - GOOGLE_SUBJECT_RECHECK_MS - 60_000) })+ const autonomous = stubAutonomous(googleProfile())++ await get('/api/grid/profile', autonomousToken())+ await settle()++ expect(autonomous.profileReads()).toBe(1)+ expect(logs.filter((l) => l.includes('stored and live'))).toHaveLength(1)+ })++ it('refuses a 21-digit Google subject that arrived as a JSON number rather than store it rounded', async () => {+ seedUser({ googleSub: null, googleSubCheckedAt: null })+ stubAutonomous(() => new Response(+ `{"status":1,"data":{"id":"${CUSTOMER_ID}","email":"${EMAIL}","customer_socials":[{"source":"google","uid":104857600000000000042}]}}`,+ { status: 200, headers: { 'Content-Type': 'application/json' } },+ ))++ expect((await get('/api/grid/profile', autonomousToken())).statusCode).toBe(503)+ expect(fakes.users.get('known')!.googleSubCheckedAt).toBeNull()+ })++ it('refuses a staging-plane sign-in with 403', async () => {+ seedUser({ autonomousEnv: 'stag', stagExternalId: 'stag-1' })+ vi.stubGlobal('fetch', vi.fn<typeof fetch>(async () => json(200, { status: 1, data: { id: 'stag-1', email: EMAIL } })))++ const res = await get('/api/grid/profile', autonomousToken(), { 'x-autonomous-env': 'stag' })++ expect(res.statusCode).toBe(403)+ })+ })++ describe('a computer sign-in', () => {+ it('is refused with 409 when the account was never checked — and nothing else on this route is a 409', async () => {+ seedUser()+ vi.stubGlobal('fetch', vi.fn<typeof fetch>(async () => { throw new Error('a computer sign-in asks nobody') }))++ const res = await get('/api/grid/profile', await computerToken('known'))++ expect(res.statusCode).toBe(409)+ expect(JSON.stringify(res.json())).not.toContain(EMAIL)+ })++ it('answers the stored values for an account checked and found to have no Google identity', async () => {+ seedUser({ googleSub: null, googleSubCheckedAt: new Date() })++ const res = await get('/api/grid/profile', await computerToken('known'))++ expect(res.statusCode).toBe(200)+ expect(res.json()).toEqual({ status: 1, data: { id: CUSTOMER_ID, email: EMAIL, full_name: FULL_NAME, customer_socials: [] } })+ })++ it('refuses an account on the staging plane with 403', async () => {+ seedUser({ autonomousEnv: 'stag', googleSub: GOOGLE_SUB, googleSubCheckedAt: new Date() })+ expect((await get('/api/grid/profile', await computerToken('known'))).statusCode).toBe(403)+ })++ it('refuses a provisional customer id with 403', async () => {+ seedUser({ externalId: 'local-prod-0b5c', googleSub: null, googleSubCheckedAt: new Date() })+ expect((await get('/api/grid/profile', await computerToken('known'))).statusCode).toBe(403)++ fakes.users.clear()+ seedUser({ email: `device-${CUSTOMER_ID}@pending.harness.invalid`, googleSub: null, googleSubCheckedAt: new Date() })+ expect((await get('/api/grid/profile', await computerToken('known'))).statusCode).toBe(403)+ })++ it('takes no parameter naming an account', async () => {+ seedUser({ googleSub: GOOGLE_SUB, googleSubCheckedAt: new Date() })+ fakes.users.set('other', { id: 'other', email: '[email protected]', externalId: 'other-customer', role: 'user', autonomousEnv: 'prod', googleSub: '999', googleSubCheckedAt: new Date() })++ const res = await get('/api/grid/[email protected]&id=other&userId=other', await computerToken('known'))++ expect(res.json()).toEqual(contract)+ })+ })++ it('refuses a phone sign-in with 403', async () => {+ seedUser({ googleSub: GOOGLE_SUB, googleSubCheckedAt: new Date() })+ expect((await get('/api/grid/profile', await phoneToken('known'))).statusCode).toBe(403)+ })++ it('does not stamp the user country — the caller is the control plane, not the person', async () => {+ seedUser({ googleSub: GOOGLE_SUB, googleSubCheckedAt: new Date() })+ stubAutonomous(googleProfile())++ await get('/api/grid/profile', autonomousToken('x', 'n1'), { 'cf-ipcountry': 'US' })+ await get('/api/grid/profile', await computerToken('known'), { 'cf-ipcountry': 'US' })+ expect(fakes.stampUserCountry).not.toHaveBeenCalled()++ await get('/api/anything', autonomousToken('x', 'n2'), { 'cf-ipcountry': 'VN' })+ expect(fakes.stampUserCountry).toHaveBeenCalledWith('known', 'VN')+ })++ it('never copies a social token, nor logs any part of the profile body', async () => {+ seedUser({ googleSub: 'stale-sub', googleSubCheckedAt: new Date(Date.now() - GOOGLE_SUBJECT_RECHECK_MS - 1) })+ stubAutonomous(googleProfile())++ const live = await get('/api/grid/profile', autonomousToken('x', 'n1'))+ await get('/api/anything', autonomousToken('x', 'n2'))+ await settle()+ const stored = await get('/api/grid/profile', await computerToken('known'))++ expect(leaked(live.body)).toEqual([])+ expect(leaked(stored.body)).toEqual([])+ const all = logs.join('\n')+ expect(leaked(all)).toEqual([])+ for (const value of [GOOGLE_SUB, 'stale-sub', EMAIL, CUSTOMER_ID, FULL_NAME]) expect(all).not.toContain(value)+ })++ describe('a stored Google subject is always the row\'s own customer\'s', () => {+ it('forgets it when the row takes a new production subject, so a computer sign-in is "not yet known"', async () => {+ seedUser({ googleSub: GOOGLE_SUB, googleSubCheckedAt: new Date() })+ // Another Autonomous customer reaching the same email; its own profile read fails, so nothing+ // fresher replaces what is forgotten.+ stubAutonomous(() => json(502, {}), () => json(200, { status: 1, data: { id: 'another-customer', email: EMAIL } }))++ await get('/api/anything', autonomousToken())+ await settle()++ expect(fakes.users.get('known')).toMatchObject({ externalId: 'another-customer', googleSub: null, googleSubCheckedAt: null })+ expect((await get('/api/grid/profile', await computerToken('known'))).statusCode).toBe(409)+ })++ it('does not record a live read of another customer than the row, and says so by field name', async () => {+ seedUser({ googleSub: GOOGLE_SUB, googleSubCheckedAt: new Date(Date.now() - GOOGLE_SUBJECT_RECHECK_MS - 1) })+ stubAutonomous(() => json(200, { status: 1, data: { id: 'another-customer', email: EMAIL, customer_socials: [{ source: 'google', uid: '7' }] } }))++ await get('/api/anything', autonomousToken())+ await settle()++ expect(fakes.users.get('known')!.googleSub).toBe(GOOGLE_SUB)+ const lines = logs.filter((l) => l.includes('another customer'))+ expect(lines).toHaveLength(1)+ expect(lines[0]).toContain('customer_id')+ expect(lines[0]).not.toContain('another-customer')+ })++ it('never lets a slower read replace a fresher one', async () => {+ const fresh = new Date()+ seedUser({ googleSub: GOOGLE_SUB, googleSubCheckedAt: fresh })+ const stored = { ...fakes.users.get('known')! } as never++ await recordLiveProfile(stored, { customerId: CUSTOMER_ID, email: EMAIL, fullName: FULL_NAME, googleSub: null }, new Date(fresh.getTime() - 1000))++ expect(fakes.users.get('known')).toMatchObject({ googleSub: GOOGLE_SUB, googleSubCheckedAt: fresh })+ })+ })++ it(`allows ${GRID_PROFILE_LIVE_READS_PER_MINUTE} live reads a minute per account, then 429 — never 409`, async () => {+ seedUser({ googleSub: GOOGLE_SUB, googleSubCheckedAt: new Date() })+ const autonomous = stubAutonomous(googleProfile())+ const token = autonomousToken()++ for (let i = 0; i < GRID_PROFILE_LIVE_READS_PER_MINUTE; i++) expect((await get('/api/grid/profile', token)).statusCode).toBe(200)+ expect((await get('/api/grid/profile', token)).statusCode).toBe(429)+ expect(autonomous.profileReads()).toBe(GRID_PROFILE_LIVE_READS_PER_MINUTE)+ // A computer sign-in reads nothing upstream and is not counted.+ expect((await get('/api/grid/profile', await computerToken('known'))).statusCode).toBe(200)+ })++ it('tells every cache in between not to keep the answer', async () => {+ seedUser({ googleSub: GOOGLE_SUB, googleSubCheckedAt: new Date() })+ const res = await get('/api/grid/profile', await computerToken('known'))+ expect(res.headers['cache-control']).toBe('no-store')+ expect((await get('/api/grid/profile', await phoneToken('known'))).headers['cache-control']).toBe('no-store')+ })++ describe('the stored-versus-live check', () => {+ it('logs one line naming the fields that disagree, never a value', async () => {+ seedUser({ googleSub: 'stale-sub', googleSubCheckedAt: new Date(Date.now() - 60_000) })+ stubAutonomous(googleProfile())++ await get('/api/grid/profile', autonomousToken())++ const lines = logs.filter((l) => l.includes('stored and live'))+ expect(lines).toHaveLength(1)+ expect(lines[0]).toContain('google_sub')+ expect(lines[0]).not.toContain('stale-sub')+ expect(lines[0]).not.toContain(GOOGLE_SUB)+ expect(fakes.users.get('known')!.googleSub).toBe(GOOGLE_SUB)+ })++ it('logs one line from the fill as well, and overwrites to "none"', async () => {+ seedUser({ googleSub: GOOGLE_SUB, googleSubCheckedAt: new Date(Date.now() - GOOGLE_SUBJECT_RECHECK_MS - 1) })+ stubAutonomous(googleProfile(null))++ await get('/api/anything', autonomousToken())+ await settle()++ expect(logs.filter((l) => l.includes('stored and live'))).toHaveLength(1)+ expect(fakes.users.get('known')!.googleSub).toBeNull()+ })++ it('logs nothing when they agree, nor on the first check', async () => {+ seedUser()+ stubAutonomous(googleProfile())++ await get('/api/anything', autonomousToken('x', 'n1'))+ await settle()+ await get('/api/grid/profile', autonomousToken('x', 'n2'))++ expect(logs.filter((l) => l.includes('stored and live'))).toEqual([])+ })+ })+})++describe('the user shape every user-describing response is built from', () => {+ it('leaves out the Google subject and when it was checked', () => {+ const row = {+ id: 'u1', email: EMAIL, externalId: CUSTOMER_ID, passwordHash: 'h', googleSub: GOOGLE_SUB, googleSubCheckedAt: new Date(),+ } as unknown as Parameters<typeof userService.toPublic>[0]+ const shown = userService.toPublic(row) as Record<string, unknown>+ expect(shown).not.toHaveProperty('googleSub')+ expect(shown).not.toHaveProperty('googleSubCheckedAt')+ expect(shown).not.toHaveProperty('passwordHash')+ expect(shown).toMatchObject({ id: 'u1', email: EMAIL })+ })+})diff --git a/backend/src/services/UserService.test.ts b/backend/src/services/UserService.test.tsindex dd91e8144..beb151b4a 100644--- a/backend/src/services/UserService.test.ts+++ b/backend/src/services/UserService.test.ts@@ -114,7 +114,8 @@ describe('SSO user identity', () => {expect(remove).toHaveBeenCalledWith({ where: { id: 'pending' } })expect(update).toHaveBeenCalledWith(expect.objectContaining({where: { id: 'real' },- data: { externalId: 'prod-sub-1' },+ // A new production subject forgets the Google subject learned under the old one (lib/googleSubject.ts).+ data: { externalId: 'prod-sub-1', googleSub: null, googleSubCheckedAt: null },}))})diff --git a/backend/src/services/UserService.ts b/backend/src/services/UserService.tsindex 4bc6175f5..a149c8389 100644--- a/backend/src/services/UserService.ts+++ b/backend/src/services/UserService.ts@@ -7,10 +7,12 @@ import { ConflictError, NotFoundError } from '../errors/index.js'import type { AutonomousEnvironment } from '../lib/autonomousEnvironment.js'import type { SignInAttribution } from '../lib/signInAttribution.js'-export type PublicUser = Omit<User, 'passwordHash'>+// The Google subject and its check time (lib/googleSubject.ts) are internal: they exist to answer the+// control plane's `GET /api/grid/profile`, and must not reach every client a user is described to.+export type PublicUser = Omit<User, 'passwordHash' | 'googleSub' | 'googleSubCheckedAt'>function toPublic(u: User): PublicUser {- const { passwordHash: _omit, ...rest } = u+ const { passwordHash: _hash, googleSub: _sub, googleSubCheckedAt: _checked, ...rest } = ureturn rest}@@ -104,7 +106,12 @@ export const userService = {...(existing.email !== em ? { email: em } : {}),...(input.name && existing.name !== input.name ? { name: input.name } : {}),...(existing.role !== role ? { role } : {}),- ...(input.autonomousEnv === 'prod' && existing.externalId !== externalId ? { externalId } : {}),+ // A new production subject on this row makes its stored Google subject (lib/googleSubject.ts)+ // somebody else's answer: forget it, so the account is unchecked until a live read of THIS+ // customer's profile — never answered for a QR-signed computer from the previous customer's.+ ...(input.autonomousEnv === 'prod' && existing.externalId !== externalId+ ? { externalId, googleSub: null, googleSubCheckedAt: null }+ : {}),...(input.autonomousEnv === 'stag' && existing.stagExternalId !== externalId? { stagExternalId: externalId }: {}),@@ -192,6 +199,30 @@ export const userService = {})},+ /**+ * Record what a live read of the Autonomous profile said about the account's Google subject — a+ * subject, or null for "none". Every successful live read overwrites, including to none — unless a+ * read that STARTED later has already been recorded: `readAt` is when this one began, so a slow read+ * never replaces a fresher answer. False when it was not recorded.+ *+ * ⚠️ `googleSubCheckedAt: null` alone does NOT match a row written before the field existed — on+ * MongoDB absent is not null (the trap `routes/grid.ts` documents). `isSet: false` covers those.+ */+ async recordGoogleSubject(userId: string, googleSub: string | null, readAt: Date): Promise<boolean> {+ const { count } = await prisma.user.updateMany({+ where: {+ id: userId,+ OR: [+ { googleSubCheckedAt: null },+ { googleSubCheckedAt: { isSet: false } },+ { googleSubCheckedAt: { lt: readAt } },+ ],+ },+ data: { googleSub, googleSubCheckedAt: readAt },+ })+ return count === 1+ },+get(id: string): Promise<User | null> {return prisma.user.findUnique({ where: { id } })},