Skip to content

Class: Accounts ​

Defined in: server/accounts.ts:278

A small player backend on D1: accounts with a name and a password, sessions, guests who can sign up without losing what they earned, per-player data, stats and leaderboards, public profiles, and a player's right to download or delete everything about them.

Make one per request; it holds no state of its own beyond its options.

const accounts = new Accounts(env.DB, { secret: env.JOIN_SECRET });
return (await accounts.route(request)) ?? new Response("Not found", { status: 404 });

Constructors ​

Constructor ​

ts
new Accounts(db, options): Accounts;

Defined in: server/accounts.ts:296

Parameters ​

ParameterType
dbD1Database
optionsAccountsOptions

Returns ​

Accounts

Methods ​

migrate() ​

ts
migrate(): Promise<void>;

Defined in: server/accounts.ts:328

Creates the tables if they are not there yet. Called for you before the first query.

Returns ​

Promise<void>


identify() ​

ts
identify(request, scope?): Promise<Identity | null>;

Defined in: server/accounts.ts:346

Who is making this request: the account its session cookie or bearer session token belongs to, else the player a join token (?token= or bearer) speaks for, else nobody. scope is checked against scoped join tokens, as tokenAuth does.

Parameters ​

ParameterType
requestRequest
scope?string

Returns ​

Promise<Identity | null>


authenticate() ​

ts
readonly authenticate(request, scope): Promise<Response | Identity>;

Defined in: server/accounts.ts:372

For routeToRoom and routeToMatchmaker: lets in signed-in players and holders of a join token, guests included, and answers 401 otherwise. The room learns the player's name too.

Parameters ​

ParameterType
requestRequest
scopestring

Returns ​

Promise<Response | Identity>


requireAccount() ​

ts
readonly requireAccount(request, scope): Promise<Response | Identity>;

Defined in: server/accounts.ts:378

Like authenticate, for places that need an account: guests get 401 too.

Parameters ​

ParameterType
requestRequest
scopestring

Returns ​

Promise<Response | Identity>


route() ​

ts
route(request, ctx?): Promise<Response | null>;

Defined in: server/accounts.ts:413

Answers requests to the accounts API, under prefix; null for any other URL so your Worker can try its other routes.

POST   /guest            a guest player and a join token for them
POST   /register         { name, password, email?, guestToken? }
POST   /login            { name, password }
POST   /logout
GET    /me               your account, data and stats
DELETE /me               { password }: delete your account and everything in it
POST   /password         { current, next }: change it and sign out everywhere else
POST   /recovery-code    { password }: a code that sets a new password once, shown this one time
POST   /recover          { name, code, password }: set a new password with that code, and sign in
POST   /forgot           { name } or { email }: send a reset link, if `sendPasswordReset` is set
POST   /reset            { token, password }: set a new password with the link's token, and sign in
POST   /name             { name }: take another name
POST   /email            { password, email }: set or (with null) remove the email address
GET    /export           everything stored about you, as a JSON download
POST   /token            { scope? }: a short-lived join token for a room or queue
GET    /data/:key        PUT /data/:key { value }   DELETE /data/:key
GET    /players/:id      a public profile
GET    /leaderboards/:stat?limit=&offset=

Pass the Worker's ctx as well if you reset passwords by email: the email is then sent after the answer, which takes as long whether or not there was an account to write to.

Parameters ​

ParameterType
requestRequest
ctx?Pick<ExecutionContext<unknown>, "waitUntil">

Returns ​

Promise<Response | null>


register() ​

ts
register(input): Promise<Identity>;

Defined in: server/accounts.ts:639

Creates an account. id lets a guest keep theirs; it is made up otherwise.

Parameters ​

ParameterType
input{ name: string; password: string; email?: string | null; id?: string; }
input.namestring
input.passwordstring
input.email?string | null
input.id?string

Returns ​

Promise<Identity>


importAccount() ​

ts
importAccount(account): Promise<void>;

Defined in: server/accounts.ts:665

Brings in an account from another service. Its password works through verifyImportedPassword.

Parameters ​

ParameterType
accountImportedAccount

Returns ​

Promise<void>


signIn() ​

ts
signIn(
   name, 
   password, 
   from?
): Promise<Identity>;

Defined in: server/accounts.ts:678

Checks a name and password. Repeated failures for one name or one address are refused for a while.

Parameters ​

ParameterTypeDefault value
namestringundefined
passwordstringundefined
from?string"unknown"

Returns ​

Promise<Identity>


rename() ​

ts
rename(accountId, name): Promise<Identity>;

Defined in: server/accounts.ts:696

Gives an account another name, if nobody has it. Sessions and join tokens issued later carry the new one.

Parameters ​

ParameterType
accountIdstring
namestring

Returns ​

Promise<Identity>


setEmail() ​

ts
setEmail(accountId, email): Promise<void>;

Defined in: server/accounts.ts:713

Sets the email address, or removes it with null.

Parameters ​

ParameterType
accountIdstring
emailstring | null

Returns ​

Promise<void>


setPassword() ​

ts
setPassword(accountId, password): Promise<void>;

Defined in: server/accounts.ts:725

Sets a new password, ends every session of the account, and makes any password reset token it was sent useless. Its recovery code stays.

Parameters ​

ParameterType
accountIdstring
passwordstring

Returns ​

Promise<void>


createRecoveryCode() ​

ts
createRecoveryCode(accountId): Promise<string>;

Defined in: server/accounts.ts:746

Makes a recovery code for an account and returns it: twenty letters and digits the player keeps somewhere safe, which set a new password once, with no email involved. It replaces the code the account had, if any. Only its hash is stored, so this is the one time it can be shown.

Parameters ​

ParameterType
accountIdstring

Returns ​

Promise<string>


recoverWithCode() ​

ts
recoverWithCode(
   name, 
   code, 
   password, 
   from?
): Promise<Identity>;

Defined in: server/accounts.ts:764

Sets a new password for the account called name, given its recovery code, and ends its sessions. The code is used up: make another once signed in. Wrong guesses are counted as wrong passwords are.

Parameters ​

ParameterTypeDefault value
namestringundefined
codestringundefined
passwordstringundefined
from?string"unknown"

Returns ​

Promise<Identity>


startPasswordReset() ​

ts
startPasswordReset(who): Promise<PasswordReset[]>;

Defined in: server/accounts.ts:796

Makes a password reset token for the account with this name, or for each account with this email address, and returns what to send to whom. Empty if there is no such account or it has no email address. A token replaces the one the account was sent before. POST /forgot calls this and hands each result to sendPasswordReset.

Parameters ​

ParameterType
who{ name?: string; email?: string; }
who.name?string
who.email?string

Returns ​

Promise<PasswordReset[]>


resetPassword() ​

ts
resetPassword(token, password): Promise<Identity>;

Defined in: server/accounts.ts:828

Sets a new password with a token from startPasswordReset, once, and ends the account's sessions.

Parameters ​

ParameterType
tokenstring
passwordstring

Returns ​

Promise<Identity>


createSession() ​

ts
createSession(accountId): Promise<string>;

Defined in: server/accounts.ts:850

Starts a session for an account and returns its token. Usually done for you by /login.

Parameters ​

ParameterType
accountIdstring

Returns ​

Promise<string>


deleteAccount() ​

ts
deleteAccount(accountId): Promise<void>;

Defined in: server/accounts.ts:862

Deletes an account, its sessions, data and stats. Match records keep the id, but it no longer resolves to a name.

Parameters ​

ParameterType
accountIdstring

Returns ​

Promise<void>


exportAccount() ​

ts
exportAccount(accountId): Promise<Record<string, unknown>>;

Defined in: server/accounts.ts:874

Everything stored about a player, for them to download.

Parameters ​

ParameterType
accountIdstring

Returns ​

Promise<Record<string, unknown>>


ownAccount() ​

ts
ownAccount(accountId): Promise<OwnAccount>;

Defined in: server/accounts.ts:923

The account as its owner sees it.

Parameters ​

ParameterType
accountIdstring

Returns ​

Promise<OwnAccount>


profile() ​

ts
profile(playerId): Promise<PublicProfile | null>;

Defined in: server/accounts.ts:950

A player's public profile, or null if there is no account with that id.

Parameters ​

ParameterType
playerIdstring

Returns ​

Promise<PublicProfile | null>


names() ​

ts
names(playerIds): Promise<Map<string, string>>;

Defined in: server/accounts.ts:964

Account names by player id. Guests and deleted accounts are left out.

Parameters ​

ParameterType
playerIdsreadonly string[]

Returns ​

Promise<Map<string, string>>


getData() ​

ts
getData(playerId, key): Promise<unknown>;

Defined in: server/accounts.ts:982

The value a player has under key, or undefined. Server code reads every key, whatever its policy.

Parameters ​

ParameterType
playerIdstring
keystring

Returns ​

Promise<unknown>


setData() ​

ts
setData(
   playerId, 
   key, 
   value
): Promise<void>;

Defined in: server/accounts.ts:993

Stores a JSON value for a player. Server code may set any key; clients only those with write: "owner".

Parameters ​

ParameterType
playerIdstring
keystring
valueunknown

Returns ​

Promise<void>


deleteData() ​

ts
deleteData(playerId, key): Promise<void>;

Defined in: server/accounts.ts:1019

Removes a player's value under key. Does nothing if there is none.

Parameters ​

ParameterType
playerIdstring
keystring

Returns ​

Promise<void>


addStats() ​

ts
addStats(playerId, increments): Promise<void>;

Defined in: server/accounts.ts:1036

Adds to a player's stats: { wins: 1, kills: 7 }. Server only: clients cannot write stats.

Parameters ​

ParameterType
playerIdstring
incrementsRecord<string, number>

Returns ​

Promise<void>


setStats() ​

ts
setStats(playerId, values): Promise<void>;

Defined in: server/accounts.ts:1041

Sets stats to these values.

Parameters ​

ParameterType
playerIdstring
valuesRecord<string, number>

Returns ​

Promise<void>


maxStats() ​

ts
maxStats(playerId, values): Promise<void>;

Defined in: server/accounts.ts:1046

Keeps the higher of the stored and the given value: best scores, longest streaks.

Parameters ​

ParameterType
playerIdstring
valuesRecord<string, number>

Returns ​

Promise<void>


awardStats() ​

ts
awardStats(key, awards): Promise<boolean>;

Defined in: server/accounts.ts:1056

Writes several players' stats in one go, once per key: a match id, say. Calling it again with the same key changes nothing and returns false, so code that retries after a failure cannot count a result twice. Either all of it is written or none of it.

Parameters ​

ParameterType
keystring
awardsreadonly { player: string; add?: Record<string, number>; set?: Record<string, number>; max?: Record<string, number>; }[]

Returns ​

Promise<boolean>


stats() ​

ts
stats(playerId): Promise<Record<string, number>>;

Defined in: server/accounts.ts:1083

Every stat a player has.

Parameters ​

ParameterType
playerIdstring

Returns ​

Promise<Record<string, number>>


statsOf() ​

ts
statsOf(playerIds, stats?): Promise<Map<string, Record<string, number>>>;

Defined in: server/accounts.ts:1093

Several players' stats at once, by player id. stats limits it to those stats. Players without any are left out.

Parameters ​

ParameterType
playerIdsreadonly string[]
stats?readonly string[]

Returns ​

Promise<Map<string, Record<string, number>>>


leaderboard() ​

ts
leaderboard(stat, page?): Promise<LeaderboardPage>;

Defined in: server/accounts.ts:1117

The players with the highest value of a stat. Players without an account are not listed.

Parameters ​

ParameterType
statstring
page?{ limit?: number; offset?: number; }
page.limit?number
page.offset?number

Returns ​

Promise<LeaderboardPage>


rank() ​

ts
rank(stat, playerId): Promise<
  | Pick<LeaderboardEntry, "value" | "rank">
| null>;

Defined in: server/accounts.ts:1144

A player's place on a leaderboard, or null if they have no value for that stat.

Parameters ​

ParameterType
statstring
playerIdstring

Returns ​

Promise< | Pick<LeaderboardEntry, "value" | "rank"> | null>

MIT licence. Tickflare is an independent project and is not affiliated with Cloudflare.