-
Notifications
You must be signed in to change notification settings - Fork 234
feat: add NIP-43 invite code foundation #650
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Anshumancanrock
wants to merge
1
commit into
main
Choose a base branch
from
feat/nip43-invite-codes
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "nostream": minor | ||
| --- | ||
|
|
||
| Add NIP-43 invite code foundation: InviteCodeRepository with atomic claimCode, invite_codes migration, and event kind/tag constants. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
28 changes: 28 additions & 0 deletions
28
migrations/20260624_120000_create_nip43_invite_codes_table.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| exports.up = async function (knex) { | ||
| await knex.schema.createTable('invite_codes', (table) => { | ||
| table.string('code', 64).primary() | ||
| table.binary('created_by').nullable() | ||
| table.binary('claimed_by').nullable() | ||
| table.timestamp('expires_at', { useTz: true }).nullable() | ||
| table.integer('max_uses').notNullable().defaultTo(1) | ||
| table.integer('use_count').notNullable().defaultTo(0) | ||
| table.timestamp('created_at', { useTz: true }).notNullable().defaultTo(knex.fn.now()) | ||
| table.timestamp('updated_at', { useTz: true }).notNullable().defaultTo(knex.fn.now()) | ||
| }) | ||
|
|
||
| await knex.raw( | ||
| 'ALTER TABLE invite_codes ADD CONSTRAINT chk_use_count_non_negative CHECK (use_count >= 0)' | ||
| ) | ||
| await knex.raw( | ||
| 'ALTER TABLE invite_codes ADD CONSTRAINT chk_max_uses_non_negative CHECK (max_uses >= 0)' | ||
| ) | ||
|
|
||
| // partial index: only rows with an expiry set | ||
| await knex.raw( | ||
| 'CREATE INDEX idx_invite_codes_expires_at ON invite_codes(expires_at) WHERE expires_at IS NOT NULL' | ||
| ) | ||
| } | ||
|
|
||
| exports.down = async function (knex) { | ||
| await knex.schema.dropTableIfExists('invite_codes') | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| export interface InviteCode { | ||
| code: string | ||
| createdBy: string | null | ||
| claimedBy: string | null | ||
| expiresAt: Date | null | ||
| maxUses: number | ||
| useCount: number | ||
| createdAt: Date | ||
| updatedAt: Date | ||
| } | ||
|
|
||
| export interface DBInviteCode { | ||
| code: string | ||
| created_by: Buffer | null | ||
| claimed_by: Buffer | null | ||
| expires_at: Date | null | ||
| max_uses: number | ||
| use_count: number | ||
| created_at: Date | ||
| updated_at: Date | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,149 @@ | ||
| import { randomBytes } from 'crypto' | ||
|
|
||
| import { DatabaseClient, Pubkey } from '../@types/base' | ||
| import { DBInviteCode, InviteCode } from '../@types/invite-code' | ||
| import { IInviteCodeRepository } from '../@types/repositories' | ||
| import { createLogger } from '../factories/logger-factory' | ||
| import { toBuffer } from '../utils/transform' | ||
|
|
||
| const logger = createLogger('invite-code-repository') | ||
|
|
||
| export function generateInviteCode(): string { | ||
| return randomBytes(16).toString('hex') | ||
| } | ||
|
|
||
| function fromDBInviteCode(row: DBInviteCode): InviteCode { | ||
| return { | ||
| code: row.code, | ||
| createdBy: row.created_by ? row.created_by.toString('hex') : null, | ||
| claimedBy: row.claimed_by ? row.claimed_by.toString('hex') : null, | ||
| expiresAt: row.expires_at, | ||
| maxUses: row.max_uses, | ||
| useCount: row.use_count, | ||
| createdAt: row.created_at, | ||
| updatedAt: row.updated_at, | ||
| } | ||
| } | ||
|
|
||
| function affectedRows(result: unknown): number { | ||
| if (typeof result === 'number') { return result } | ||
| if (result && typeof (result as any).rowCount === 'number') { return (result as any).rowCount } | ||
| return 0 | ||
| } | ||
|
|
||
| export class InviteCodeRepository implements IInviteCodeRepository { | ||
| public constructor(private readonly dbClient: DatabaseClient) {} | ||
|
|
||
| public async create( | ||
| code: string, | ||
| expiresAt?: Date, | ||
| maxUses: number = 1, | ||
| client: DatabaseClient = this.dbClient, | ||
| ): Promise<InviteCode> { | ||
| logger('create invite code: %s (expires: %s, maxUses: %d)', code, expiresAt ?? 'never', maxUses) | ||
|
|
||
|
|
||
| const now = new Date() | ||
| const row: DBInviteCode = { | ||
| code, | ||
| created_by: null, | ||
| claimed_by: null, | ||
| expires_at: expiresAt ?? null, | ||
| max_uses: maxUses, | ||
| use_count: 0, | ||
| created_at: now, | ||
| updated_at: now, | ||
| } | ||
|
|
||
| await client<DBInviteCode>('invite_codes').insert(row) | ||
|
|
||
| return fromDBInviteCode(row) | ||
| } | ||
|
|
||
| public async findByCode( | ||
| code: string, | ||
| client: DatabaseClient = this.dbClient, | ||
| ): Promise<InviteCode | undefined> { | ||
| logger('find invite code: %s', code) | ||
|
|
||
|
|
||
| const [row] = await client<DBInviteCode>('invite_codes') | ||
| .where('code', code) | ||
| .select() | ||
|
|
||
| if (!row) { | ||
| return | ||
| } | ||
|
|
||
| return fromDBInviteCode(row) | ||
| } | ||
|
|
||
| // Atomic claim: single UPDATE ensures only one caller wins on a single-use code | ||
| public async claimCode( | ||
| code: string, | ||
| pubkey: Pubkey, | ||
| client: DatabaseClient = this.dbClient, | ||
| ): Promise<boolean> { | ||
| logger('claim invite code %s for %s', code, pubkey) | ||
|
|
||
|
|
||
| const now = new Date() | ||
|
|
||
| const result = await client<DBInviteCode>('invite_codes') | ||
| .where('code', code) | ||
| .where(function () { | ||
| this.where('max_uses', 0) // 0 = unlimited uses | ||
| .orWhereRaw('use_count < max_uses') | ||
| }) | ||
| .where(function () { | ||
| this.whereNull('expires_at') | ||
| .orWhere('expires_at', '>', now) | ||
| }) | ||
| .update({ | ||
| use_count: client.raw('use_count + 1'), | ||
| claimed_by: toBuffer(pubkey), | ||
|
|
||
| updated_at: now, | ||
| } as any) | ||
|
|
||
| return affectedRows(result) > 0 | ||
| } | ||
|
|
||
| public async findActiveCodes( | ||
| limit: number = 100, | ||
| client: DatabaseClient = this.dbClient, | ||
| ): Promise<InviteCode[]> { | ||
| logger('find active invite codes (limit %d)', limit) | ||
|
|
||
| const now = new Date() | ||
|
|
||
| const rows = await client<DBInviteCode>('invite_codes') | ||
| .where(function () { | ||
| this.whereNull('expires_at') | ||
| .orWhere('expires_at', '>', now) | ||
| }) | ||
| .where(function () { | ||
| this.where('max_uses', 0) | ||
| .orWhereRaw('use_count < max_uses') | ||
| }) | ||
| .orderBy('created_at', 'desc') | ||
| .limit(limit) | ||
| .select() | ||
|
|
||
| return rows.map(fromDBInviteCode) | ||
| } | ||
|
|
||
| public async deleteExpiredCodes( | ||
| client: DatabaseClient = this.dbClient, | ||
| ): Promise<number> { | ||
| logger('delete expired invite codes') | ||
|
|
||
| const now = new Date() | ||
|
|
||
| const result = await client<DBInviteCode>('invite_codes') | ||
| .whereNotNull('expires_at') | ||
| .where('expires_at', '<=', now) | ||
| .delete() | ||
|
|
||
| const count = affectedRows(result) | ||
| logger('deleted %d expired invite codes', count) | ||
|
|
||
| return count | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think these two fields could just be one called
remaining_uses, once it gets to <= 0 the invite can no longer be used.