Skip to content
Classplugin-oauthv0.1.0

OAuth

Logs people in with Discord and calls the API as them. Attach what with returns.

It serves oauth/login and oauth/callback under your bot's server.url. Add the callback's address under Redirects on your application's OAuth2 page. The plugin logs the exact address at startup when it isn't there yet.

It reads the client secret from DISCORD_CLIENT_SECRET. It saves each user's tokens in your bot's kv, so kv needs a driver that saves to a file or a database.

abstract class OAuth<
    TScopes extends OAuthScope = never,
    TExtra extends OAuthScope = never
> extends Plugin
new Seedcord(config).attach(
    'oauth',
    OAuth.with({
        scopes: ['guilds'],
        onLogin: ({ user, returnTo }) =>
            new Response(null, {
                status: 302,
                headers: {
                    location: returnTo ?? '/dashboard',
                    'set-cookie': sessions.create(user.id)
                }
            })
    })
);

// in a handler or your own routes
const guilds = await this.core.oauth.as(userId).guilds();

Member visibility

Filter class members by access level.

constructor

Constructs a new instance of the Plugin class

Plugin(
    host: CoreBase,
    [spec],
    input: PluginSpecArgs<Opts, Fixed>
)

Inherited from:Plugin

TScopes

The scopes from the options. Leave it out.

TScopes extends OAuthScope = never

TExtra

The extraScopes from the options. Leave it out.

TExtra extends OAuthScope = never

core

The host, typed to the transport whose Plugin base this class extends.

protected core: TCore

Inherited from:Plugin

dispatchMembers

Adds values that every handler can read. Each key becomes a member, like this.tag, and its function returns the value. Gates and Notice.render read the same values on ctx.

Seedcord calls each function once per interaction, and once per event that has a handler.

attach() throws if seedcord already uses one of these keys, like reply, if another plugin on the bot uses it, or if the bot attaches this plugin twice.

readonly dispatchMembers?: DispatchMemberFunctions
public override readonly dispatchMembers = {
    tag: (origin: DispatchOrigin) => `${origin.guildId}:${origin.userId}`
};

Inherited from:Plugin

kv

This plugin's records in the bot's config.kv, stored under its attach key. Two attachments of one plugin class each get their own records. Renaming the attach key leaves the records under the old key behind.

protected kv: Kv
// works in a field initializer, the constructor, and every method
private readonly jobs = this.kv.collection<Job>('job');

Inherited from:Plugin

Throws:

  • A SeedcordTypeError when something built the plugin with new outside attach().

logger

Logs under the plugin's class name, on the channel its attach key sets.

protected readonly logger: Logger

Inherited from:Plugin

options

protected abstract readonly options: OAuthOptions<TScopes, TExtra>

codegen()

Returns data that seedcord codegen writes into the bot's seedcord-gen.ts as a type. Read it back with Generated<typeof YourPlugin>. Return plain data, or classes and objects that a project file or your plugin's package exports. The class needs a static readonly id.

seedcord codegen calls this without running init(). Read only what the constructor stored and the bot's files.

async codegen?(): Promise<unknown>

Inherited from:Plugin

dispose()

Runs during teardown, in ShutdownPhase.Disconnect by default. seedcord skips it when init() has thrown.

When init() outlasts its timeout, seedcord calls this once that init() resolves, outside any shutdown phase. The process must still be alive for that call to happen.

dispose?(): Promisable<void>

Inherited from:Plugin

forget()

Deletes a user's saved tokens. It doesn't call Discord, and the user's grant there keeps working.

When several processes or Workers isolates share one kv, a refresh that's running in another one can save the tokens back. Call revoke when the login has to end for certain.

public async forget(userId: string): Promise<void>

init()

public init(): void

Throws:

A SeedcordError when server.url or DISCORD_CLIENT_SECRET isn't set.

Throws:

A SeedcordTypeError when the bot's kv keeps everything in memory.

loginUrl()

The address of the login route. Send a browser there, or put it in a message.

public loginUrl(link?: LoginLink<TScopes, TExtra>): string
// requests one more scope, and ends on the page that needed it
this.core.oauth.loginUrl({ scopes: ['connections'], returnTo: '/dashboard/accounts' });

prepareCommands()

Changes commands before seedcord sends them to Discord. Write your changes onto these objects, like setting name_localizations. Each command appears once, even when it deploys to several guilds.

If it throws, the deploy stops, and so do seedcord codegen, a Workers build, seedcord commands deploy, and seedcord commands list.

The CLI calls this without running init(). Read only what the constructor stored and the bot's files.

prepareCommands?(
    commands: readonly RESTPostAPIApplicationCommandsJSONBody[]
): Promisable<void>

Inherited from:Plugin

registerCommandFiles()

Tells seedcord dev which files your prepareCommands reads. Saving one of them in seedcord dev shows the command refresh prompt.

protected registerCommandFiles(patterns: string[]): void
Parameter: patterns

Glob patterns. A relative one resolves against root from seedcord.config.ts. A pattern that starts with ! excludes the files it matches.

Inherited from:Plugin

registerCriticalFiles()

Registers critical file patterns that should trigger a full restart when changed in Dev HMR.

protected registerCriticalFiles(
    patterns: string[]
): void
Parameter: patterns

Glob patterns. A relative one resolves against root from seedcord.config.ts. A pattern that starts with ! excludes the files it matches from the other patterns in this call.

Inherited from:Plugin

rejectOptions()

Rejects the options this plugin got.

protected rejectOptions(reason: string): never
Parameter: reason

Why the options are invalid.

Throws:

A SeedcordTypeError every time, with the plugin class name and reason in its message.

Inherited from:Plugin

revoke()

Revokes a user's grant on Discord and deletes their saved tokens.

Discord ends every grant that the user gave your application, so tokens that another OAuthClient saved for them stop working too. Use forget to log someone out of one place.

public async revoke(userId: string): Promise<void>

scopesOf()

The scopes that a user granted, or undefined for a user without saved tokens. It doesn't call Discord.

public async scopesOf(
    userId: string
): Promise<OAuthScope[] | undefined>

with()

Returns the plugin class to attach, with your options in it. Attaching OAuth directly doesn't compile, because it's abstract.

public static with<TScopes, TExtra>(options?: OAuthOptions<TScopes, TExtra>): new (host: CoreBase) => OAuth<TScopes, TExtra>
seedcord.attach('oauth', OAuth.with({ scopes: ['guilds'], extraScopes: ['connections'] }));