mirror of
https://github.com/nestriness/nestri.git
synced 2026-11-22 15:09:54 +02:00
Release: Steam linking requires Steam's sign-in; installer 0.2.2 (#359)
- A Steam account is linked only through Steam's own OpenID sign-in (POST /steam/link/start, GET /steam/link/callback). POST /steam/link, which linked any Steam id on trust, is removed. Migration 0020, additive. - The installer installs host agent 0.2.2 (virtiofsd preflight, install wording), released from nescore prod.
This commit is contained in:
@@ -45,6 +45,7 @@ const routes = app
|
||||
.route('/', IndexApi.route)
|
||||
.route('/', InstallApi.route)
|
||||
.route('/user', UserApi.route)
|
||||
.route('/steam', SteamApi.publicRoute)
|
||||
.route('/steam', SteamApi.route)
|
||||
.route('/library', LibraryApi.route)
|
||||
.route('/games', GameApi.route)
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { Actor } from '@nestri/core/actor';
|
||||
import { Env } from '@nestri/core/env';
|
||||
import { ErrorCodes, VisibleError } from '@nestri/core/error';
|
||||
import { Examples } from '@nestri/core/examples';
|
||||
import { Steam } from '@nestri/core/steam/index';
|
||||
import { SteamLinkRequest } from '@nestri/core/steam/link-request';
|
||||
import { LinkedAccount } from '@nestri/core/user/linked-account';
|
||||
import { Hono } from 'hono';
|
||||
import { describeRoute } from 'hono-openapi';
|
||||
@@ -10,6 +12,54 @@ import { z } from 'zod';
|
||||
import { ErrorResponses, notPublic, Result, validator } from '../utils';
|
||||
|
||||
export namespace SteamApi {
|
||||
/**
|
||||
* Where Steam sends the browser back to, for one link request.
|
||||
*
|
||||
* This API's own public address: `API_URL` when set, otherwise the host the
|
||||
* request arrived on — over https, because a proxy in front of the API
|
||||
* forwards plain http and Steam must be sent somewhere a browser can reach.
|
||||
*/
|
||||
function callbackUrl(requestUrl: string, nonce: string): string {
|
||||
const here = new URL(requestUrl);
|
||||
const local = here.hostname === 'localhost' || here.hostname === '127.0.0.1';
|
||||
const base = Env.get().API_URL ?? `${local ? here.protocol : 'https:'}//${here.host}`;
|
||||
return `${base.replace(/\/$/, '')}/steam/link/callback?state=${encodeURIComponent(nonce)}`;
|
||||
}
|
||||
|
||||
function page(title: string, body: string, status: 200 | 400) {
|
||||
return new Response(
|
||||
`<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>${title}</title><body style="font:16px system-ui;background:#111;color:#eee;display:grid;place-items:center;min-height:90vh;margin:0"><p>${body}</p>`,
|
||||
{ status, headers: { 'content-type': 'text/html; charset=utf-8' } }
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Steam's way back. Public, because a browser returning from Steam carries
|
||||
* no bearer token: the one-time request is what says who this is for.
|
||||
*/
|
||||
export const publicRoute = new Hono().get('/link/callback', async (c) => {
|
||||
const params = Object.fromEntries(new URL(c.req.url).searchParams.entries());
|
||||
const nonce = params.state ?? '';
|
||||
const steamId = await SteamLinkRequest.verify(params, callbackUrl(c.req.url, nonce));
|
||||
if (!steamId) {
|
||||
return page(
|
||||
'Not linked',
|
||||
'Steam did not confirm that sign-in. Start again from Nestri.',
|
||||
400
|
||||
);
|
||||
}
|
||||
const userId = await SteamLinkRequest.consume(nonce);
|
||||
if (!userId) {
|
||||
return page(
|
||||
'Not linked',
|
||||
'That link has expired or was already used. Start again from Nestri.',
|
||||
400
|
||||
);
|
||||
}
|
||||
await Steam.link({ steamId, userId });
|
||||
return page('Steam linked', 'Your Steam account is linked. You can close this tab.', 200);
|
||||
});
|
||||
|
||||
export const route = new Hono()
|
||||
.use(notPublic)
|
||||
.get(
|
||||
@@ -75,67 +125,31 @@ export namespace SteamApi {
|
||||
}
|
||||
)
|
||||
.post(
|
||||
'/link',
|
||||
'/link/start',
|
||||
describeRoute({
|
||||
tags: ['Steam'],
|
||||
summary: 'Link a Steam account',
|
||||
description: 'Link a Steam account to the calling user.',
|
||||
summary: 'Start linking a Steam account',
|
||||
description:
|
||||
'Returns a Steam sign-in URL. Open it in a browser: signing in to Steam there is what proves the account is yours, and the account is linked when Steam sends the browser back. The URL is good for ten minutes and one sign-in. A Steam id on its own is public, so no route links one on trust.',
|
||||
responses: {
|
||||
200: {
|
||||
content: {
|
||||
'application/json': {
|
||||
schema: Result(
|
||||
z.object({
|
||||
linkedAccountId: z.string().meta({
|
||||
description: 'The ID of the linked account',
|
||||
example: Examples.LinkedAccount.id
|
||||
}),
|
||||
steamId: z.string().meta({
|
||||
description: 'The Steam ID that was linked',
|
||||
example: '76561197960287930'
|
||||
})
|
||||
url: z.string().meta({ description: 'Open this to sign in to Steam' })
|
||||
})
|
||||
)
|
||||
}
|
||||
},
|
||||
description: 'Steam account linked'
|
||||
description: 'Where to sign in'
|
||||
},
|
||||
400: ErrorResponses[400],
|
||||
401: ErrorResponses[401],
|
||||
403: ErrorResponses[403],
|
||||
429: ErrorResponses[429]
|
||||
401: ErrorResponses[401]
|
||||
}
|
||||
}),
|
||||
validator(
|
||||
'json',
|
||||
z.object({
|
||||
steamId: z.string().min(1).meta({
|
||||
description: 'Steam ID to link',
|
||||
example: '76561197960287930'
|
||||
}),
|
||||
profile: z
|
||||
.record(z.string(), z.unknown())
|
||||
.optional()
|
||||
.meta({
|
||||
description: 'Steam profile data',
|
||||
example: { personaname: 'Player', avatarfull: 'https://...' }
|
||||
})
|
||||
})
|
||||
),
|
||||
async (c) => {
|
||||
const body = c.req.valid('json');
|
||||
|
||||
// Linking is always for the caller. It once accepted a `userId`,
|
||||
// which meant one credential could attach a Steam account to any
|
||||
// user \u2014 and a linked account is how a library is reached.
|
||||
const linkedAccountID = await Steam.link({
|
||||
steamId: body.steamId,
|
||||
profile: body.profile,
|
||||
userId: Actor.userID
|
||||
});
|
||||
return c.json({
|
||||
data: { linkedAccountId: linkedAccountID, steamId: body.steamId }
|
||||
});
|
||||
const nonce = await SteamLinkRequest.create(Actor.userID);
|
||||
return c.json({ data: { url: SteamLinkRequest.signInUrl(callbackUrl(c.req.url, nonce)) } });
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ set -eu
|
||||
API="${NESTRI_API:-https://api.nestri.io}"
|
||||
# Pinned, not "latest", so the script and the binary it installs are a pair
|
||||
# somebody chose. Bump when cutting a release; NESTRI_HOST_VERSION overrides it.
|
||||
DEFAULT_VERSION="0.2.1"
|
||||
DEFAULT_VERSION="0.2.2"
|
||||
VERSION="${NESTRI_HOST_VERSION:-$DEFAULT_VERSION}"
|
||||
BIN_DIR="${NESTRI_BIN_DIR:-$HOME/.local/bin}"
|
||||
|
||||
|
||||
@@ -212,7 +212,8 @@ describe('OpenAPI doc', () => {
|
||||
expect(paths).toContain('/games/download-state');
|
||||
expect(paths).toContain('/library');
|
||||
expect(paths).toContain('/library/sync');
|
||||
expect(paths).toContain('/steam/link');
|
||||
expect(paths).toContain('/steam/link/start');
|
||||
expect(paths).not.toContain('/steam/link');
|
||||
expect(paths).toContain('/steam/linked');
|
||||
expect(paths).toContain('/steam/unlink');
|
||||
expect(paths).toContain('/user');
|
||||
@@ -469,21 +470,37 @@ describe('Machine registration', () => {
|
||||
});
|
||||
|
||||
describe('Steam routes', () => {
|
||||
test('POST /steam/link requires auth', async () => {
|
||||
const res = await app.request('/steam/link', { method: 'POST' });
|
||||
test('POST /steam/link/start requires auth', async () => {
|
||||
const res = await app.request('/steam/link/start', { method: 'POST' });
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
test('POST /steam/link validates steamId', async () => {
|
||||
test('POST /steam/link/start hands back a Steam sign-in that returns here', async () => {
|
||||
const res = await app.request('http://api.example.test/steam/link/start', {
|
||||
method: 'POST',
|
||||
headers: await userHeaders()
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
const url = new URL(((await res.json()) as any).data.url);
|
||||
expect(url.host).toBe('steamcommunity.com');
|
||||
const back = new URL(url.searchParams.get('openid.return_to')!);
|
||||
expect(back.origin + back.pathname).toBe('https://api.example.test/steam/link/callback');
|
||||
expect(back.searchParams.get('state')).toBeTruthy();
|
||||
});
|
||||
|
||||
test('a Steam id can no longer be linked on trust', async () => {
|
||||
const res = await app.request('/steam/link', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...(await userHeaders()),
|
||||
'content-type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({})
|
||||
headers: { ...(await userHeaders()), 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ steamId: '76561197960287930' })
|
||||
});
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
|
||||
test('the callback needs no session, and refuses what Steam did not assert', async () => {
|
||||
const res = await app.request('/steam/link/callback?state=nope&openid.mode=cancel');
|
||||
expect(res.status).toBe(400);
|
||||
expect(await res.text()).toContain('Steam did not confirm');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
CREATE TABLE "steam_link_request" (
|
||||
"id" char(30) PRIMARY KEY NOT NULL,
|
||||
"time_created" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"time_updated" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"time_deleted" timestamp with time zone,
|
||||
"user_id" char(30) NOT NULL,
|
||||
"nonce_hash" text NOT NULL,
|
||||
"expires_at" timestamp with time zone NOT NULL,
|
||||
"used_at" timestamp with time zone
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "steam_link_request" ADD CONSTRAINT "steam_link_request_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "steam_link_request_nonce_unique" ON "steam_link_request" USING btree ("nonce_hash");--> statement-breakpoint
|
||||
CREATE INDEX "steam_link_request_user_idx" ON "steam_link_request" USING btree ("user_id");
|
||||
File diff suppressed because it is too large
Load Diff
@@ -141,6 +141,13 @@
|
||||
"when": 1791355334692,
|
||||
"tag": "0019_install_token_for_a_fleet",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 20,
|
||||
"version": "7",
|
||||
"when": 1791359465283,
|
||||
"tag": "0020_steam_link_request",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -69,7 +69,12 @@ export namespace Env {
|
||||
* Unset, nothing is placed on rented hardware. Configured per deploy,
|
||||
* never written into the repository.
|
||||
*/
|
||||
FLEET_ORGANISATION_ID: z.string().optional()
|
||||
FLEET_ORGANISATION_ID: z.string().optional(),
|
||||
/**
|
||||
* This API's public address, for URLs handed to a browser that must come
|
||||
* back here (Steam's sign-in). Unset, the request's own host over https.
|
||||
*/
|
||||
API_URL: z.string().optional()
|
||||
});
|
||||
|
||||
export type Info = z.infer<typeof Info>;
|
||||
|
||||
@@ -15,6 +15,7 @@ export namespace Identifier {
|
||||
machine: 'mch',
|
||||
installToken: 'mit',
|
||||
trialClaim: 'trc',
|
||||
steamLinkRequest: 'slr',
|
||||
box: 'box',
|
||||
session: 'ses',
|
||||
accessToken: 'pat',
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { index, pgTable, text, uniqueIndex } from 'drizzle-orm/pg-core';
|
||||
|
||||
import { id, timestamps, ulid, utc } from '../db/types.js';
|
||||
import { UserTable } from '../user/user.sql.js';
|
||||
|
||||
/**
|
||||
* A person partway through proving a Steam account is theirs.
|
||||
*
|
||||
* Linking goes through Steam's own sign-in, which leaves this site and comes
|
||||
* back to a callback that carries no session — so the request is how the
|
||||
* callback knows who it is for. One use, minutes long, and stored only as a
|
||||
* digest, because the nonce travels in a URL.
|
||||
*/
|
||||
export const SteamLinkRequestTable = pgTable(
|
||||
'steam_link_request',
|
||||
{
|
||||
...id,
|
||||
...timestamps,
|
||||
userId: ulid('user_id')
|
||||
.notNull()
|
||||
.references(() => UserTable.id, { onDelete: 'cascade' }),
|
||||
nonceHash: text('nonce_hash').notNull(),
|
||||
expiresAt: utc('expires_at').notNull(),
|
||||
usedAt: utc('used_at')
|
||||
},
|
||||
(t) => [
|
||||
uniqueIndex('steam_link_request_nonce_unique').on(t.nonceHash),
|
||||
index('steam_link_request_user_idx').on(t.userId)
|
||||
]
|
||||
);
|
||||
@@ -0,0 +1,106 @@
|
||||
import { afterAll, describe, expect, test } from 'bun:test';
|
||||
|
||||
import { Fixtures } from '../db/fixtures.js';
|
||||
import { testDb } from '../db/test.js';
|
||||
import { SteamLinkRequest } from './link-request.js';
|
||||
|
||||
const sql = testDb();
|
||||
const createdUserIds: string[] = [];
|
||||
|
||||
afterAll(async () => {
|
||||
if (createdUserIds.length > 0) {
|
||||
await sql`delete from "user" where id in ${sql(createdUserIds)}`;
|
||||
}
|
||||
});
|
||||
|
||||
const RETURN_TO = 'https://api.example.test/steam/link/callback?state=abc';
|
||||
const ID = '76561198000000001';
|
||||
|
||||
/** An assertion as Steam sends it back, for `ID`, to `RETURN_TO`. */
|
||||
function assertion(overrides: Record<string, string> = {}) {
|
||||
return {
|
||||
'openid.ns': 'http://specs.openid.net/auth/2.0',
|
||||
'openid.mode': 'id_res',
|
||||
'openid.op_endpoint': SteamLinkRequest.OPENID,
|
||||
'openid.claimed_id': `https://steamcommunity.com/openid/id/${ID}`,
|
||||
'openid.identity': `https://steamcommunity.com/openid/id/${ID}`,
|
||||
'openid.return_to': RETURN_TO,
|
||||
'openid.response_nonce': '2026-10-07T08:00:00Zabc',
|
||||
'openid.assoc_handle': '1234567890',
|
||||
'openid.signed': 'signed,op_endpoint,claimed_id,identity,return_to,response_nonce,assoc_handle',
|
||||
'openid.sig': 'c2lnbmF0dXJl',
|
||||
...overrides
|
||||
};
|
||||
}
|
||||
|
||||
function steamSays(valid: boolean) {
|
||||
const calls: string[] = [];
|
||||
const check = (async (_url: string, init: RequestInit) => {
|
||||
calls.push(String(init.body));
|
||||
return new Response(`ns:http://specs.openid.net/auth/2.0\nis_valid:${valid}\n`);
|
||||
}) as unknown as typeof fetch;
|
||||
return { check, calls };
|
||||
}
|
||||
|
||||
describe('Verifying a Steam sign-in', () => {
|
||||
test('an assertion Steam confirms proves the id in its claimed identity', async () => {
|
||||
const steam = steamSays(true);
|
||||
expect(await SteamLinkRequest.verify(assertion(), RETURN_TO, steam.check)).toBe(ID);
|
||||
expect(steam.calls[0]).toContain('openid.mode=check_authentication');
|
||||
});
|
||||
|
||||
test('one Steam does not confirm proves nothing', async () => {
|
||||
expect(
|
||||
await SteamLinkRequest.verify(assertion(), RETURN_TO, steamSays(false).check)
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
test('one issued for somewhere else is refused before Steam is asked', async () => {
|
||||
const steam = steamSays(true);
|
||||
const other = assertion({ 'openid.return_to': 'https://evil.example/cb' });
|
||||
expect(await SteamLinkRequest.verify(other, RETURN_TO, steam.check)).toBeNull();
|
||||
expect(steam.calls).toEqual([]);
|
||||
});
|
||||
|
||||
test('a claimed id not in Steam’s shape is refused', async () => {
|
||||
const steam = steamSays(true);
|
||||
for (const claimed of [
|
||||
`https://steamcommunity.com.evil/openid/id/${ID}`,
|
||||
`http://steamcommunity.com/openid/id/${ID}`,
|
||||
'https://steamcommunity.com/openid/id/123'
|
||||
]) {
|
||||
const forged = assertion({ 'openid.claimed_id': claimed, 'openid.identity': claimed });
|
||||
expect(await SteamLinkRequest.verify(forged, RETURN_TO, steam.check)).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
test('another provider’s endpoint is refused', async () => {
|
||||
const forged = assertion({ 'openid.op_endpoint': 'https://openid.evil/login' });
|
||||
expect(await SteamLinkRequest.verify(forged, RETURN_TO, steamSays(true).check)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('A link request', () => {
|
||||
test('works once', async () => {
|
||||
const owner = await Fixtures.owner('steam-link');
|
||||
createdUserIds.push(owner.userId);
|
||||
const nonce = await SteamLinkRequest.create(owner.userId);
|
||||
expect(await SteamLinkRequest.consume(nonce)).toBe(owner.userId);
|
||||
expect(await SteamLinkRequest.consume(nonce)).toBeNull();
|
||||
});
|
||||
|
||||
test('expires', async () => {
|
||||
const owner = await Fixtures.owner('steam-link-old');
|
||||
createdUserIds.push(owner.userId);
|
||||
const nonce = await SteamLinkRequest.create(owner.userId);
|
||||
await sql`update steam_link_request set expires_at = now() - interval '1 minute' where user_id = ${owner.userId}`;
|
||||
expect(await SteamLinkRequest.consume(nonce)).toBeNull();
|
||||
});
|
||||
|
||||
test('the sign-in URL sends Steam back to exactly the callback', () => {
|
||||
const url = new URL(SteamLinkRequest.signInUrl(RETURN_TO));
|
||||
expect(url.origin + url.pathname).toBe(SteamLinkRequest.OPENID);
|
||||
expect(url.searchParams.get('openid.return_to')).toBe(RETURN_TO);
|
||||
expect(url.searchParams.get('openid.realm')).toBe('https://api.example.test');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
import { randomBytes } from 'node:crypto';
|
||||
|
||||
import { and, eq, gt, isNull, sql } from 'drizzle-orm';
|
||||
import z from 'zod';
|
||||
|
||||
import { Database } from '../db/index.js';
|
||||
import { fn } from '../fn.js';
|
||||
import { Identifier } from '../id.js';
|
||||
import { SteamLinkRequestTable } from './link-request.sql.js';
|
||||
|
||||
/**
|
||||
* Proving a Steam account is yours, by signing in to Steam.
|
||||
*
|
||||
* A Steam id is public — anyone can read one off a profile page — so a link
|
||||
* that took an id on trust would let anybody claim any account, and with it
|
||||
* that account's library and its one free weekend. The only proof accepted is
|
||||
* Steam's own: an OpenID assertion that Steam itself confirms, for a sign-in
|
||||
* that this site started.
|
||||
*/
|
||||
export namespace SteamLinkRequest {
|
||||
export const OPENID = 'https://steamcommunity.com/openid/login';
|
||||
const TTL_MINUTES = 10;
|
||||
const CLAIMED_ID = /^https:\/\/steamcommunity\.com\/openid\/id\/(\d{17})$/;
|
||||
|
||||
async function digest(value: string): Promise<string> {
|
||||
const d = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value));
|
||||
return Array.from(new Uint8Array(d))
|
||||
.map((b) => b.toString(16).padStart(2, '0'))
|
||||
.join('');
|
||||
}
|
||||
|
||||
/** Start a link for `userId`. The nonce goes in the callback URL and nowhere else. */
|
||||
export const create = fn(z.string(), async (userId) => {
|
||||
const nonce = randomBytes(24).toString('base64url');
|
||||
const nonceHash = await digest(nonce);
|
||||
await Database.use((tx) =>
|
||||
tx.insert(SteamLinkRequestTable).values({
|
||||
id: Identifier.ascending('steamLinkRequest'),
|
||||
userId,
|
||||
nonceHash,
|
||||
expiresAt: sql`now() + interval '${sql.raw(String(TTL_MINUTES))} minutes'`
|
||||
})
|
||||
);
|
||||
return nonce;
|
||||
});
|
||||
|
||||
/** The URL that sends a person to Steam, coming back to `returnTo`. */
|
||||
export function signInUrl(returnTo: string): string {
|
||||
const realm = new URL(returnTo).origin;
|
||||
const params = new URLSearchParams({
|
||||
'openid.ns': 'http://specs.openid.net/auth/2.0',
|
||||
'openid.mode': 'checkid_setup',
|
||||
'openid.return_to': returnTo,
|
||||
'openid.realm': realm,
|
||||
'openid.identity': 'http://specs.openid.net/auth/2.0/identifier_select',
|
||||
'openid.claimed_id': 'http://specs.openid.net/auth/2.0/identifier_select'
|
||||
});
|
||||
return `${OPENID}?${params}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Steam id an assertion proves, or null.
|
||||
*
|
||||
* Three checks, each closing a different hole: Steam confirms the
|
||||
* signature (`check_authentication`), so the parameters were not made up;
|
||||
* the assertion was issued for exactly this callback, so one minted for
|
||||
* another site cannot be replayed here; and the id is read only from the
|
||||
* claimed identity URL, in the one shape Steam issues.
|
||||
*/
|
||||
export async function verify(
|
||||
params: Record<string, string>,
|
||||
expectedReturnTo: string,
|
||||
check: typeof fetch = fetch
|
||||
): Promise<string | null> {
|
||||
if (params['openid.mode'] !== 'id_res') return null;
|
||||
if (params['openid.op_endpoint'] !== OPENID) return null;
|
||||
if (params['openid.return_to'] !== expectedReturnTo) return null;
|
||||
const claimed = CLAIMED_ID.exec(params['openid.claimed_id'] ?? '');
|
||||
if (!claimed || params['openid.identity'] !== params['openid.claimed_id']) return null;
|
||||
|
||||
const res = await check(OPENID, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({ ...params, 'openid.mode': 'check_authentication' })
|
||||
});
|
||||
const text = await res.text();
|
||||
return /^is_valid:true$/m.test(text) ? claimed[1]! : null;
|
||||
}
|
||||
|
||||
/** Spend a nonce: the user it was for, once, while it is fresh. */
|
||||
export const consume = fn(z.string(), async (nonce) => {
|
||||
const nonceHash = await digest(nonce);
|
||||
return Database.use((tx) =>
|
||||
tx
|
||||
.update(SteamLinkRequestTable)
|
||||
.set({ usedAt: sql`now()` })
|
||||
.where(
|
||||
and(
|
||||
eq(SteamLinkRequestTable.nonceHash, nonceHash),
|
||||
isNull(SteamLinkRequestTable.usedAt),
|
||||
gt(SteamLinkRequestTable.expiresAt, sql`now()`)
|
||||
)
|
||||
)
|
||||
.returning({ userId: SteamLinkRequestTable.userId })
|
||||
.then((rows) => rows.at(0)?.userId ?? null)
|
||||
);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user