session-keys 3.0.11

Gum Session Protocol (GPL Session)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
#![allow(unexpected_cfgs)]

use anchor_lang::prelude::*;
use anchor_lang::system_program;

const LAMPORTS_PER_SOL: u64 = 1_000_000_000;

#[cfg(feature = "no-entrypoint")]
pub use session_keys_macros::*;

declare_id!("KeyspM2ssCJbqUhQ4k7sveSiY4WjnYsrXkC8oDbwde5");

#[cfg(not(feature = "no-entrypoint"))]
solana_security_txt::security_txt! {
    name: "session_keys",
    project_url: "https://magicblock.gg",
    contacts: "email:dev@magicblock.gg,twitter:@magicblock",
    policy: "",
    preferred_languages: "en",
    source_code: "https://github.com/magicblock-labs"
}

#[program]
pub mod gpl_session {
    use super::*;

    // create a session token
    pub fn create_session(
        ctx: Context<CreateSessionToken>,
        top_up: Option<bool>,
        valid_until: Option<i64>,
        lamports: Option<u64>,
    ) -> Result<()> {
        let (top_up, valid_until) = process_session_params(top_up, valid_until)?;
        create_session_token_handler(ctx, top_up, valid_until, lamports)
    }

    pub fn create_session_with_payer(
        ctx: Context<CreateSessionTokenWithPayer>,
        top_up: Option<bool>,
        valid_until: Option<i64>,
        lamports: Option<u64>,
    ) -> Result<()> {
        let (top_up, valid_until) = process_session_params(top_up, valid_until)?;
        create_session_token_with_payer_handler(ctx, top_up, valid_until, lamports)
    }
    // revoke a session token
    pub fn revoke_session(ctx: Context<RevokeSessionToken>) -> Result<()> {
        revoke_session_token_handler(ctx)
    }

    // V2 instructions
    //
    // Added the V2 instructions to support the new session token format.
    // The new format allows session to be created with a payer which on revoking
    // would send the lamports back to the payer.
    pub fn create_session_v2(
        ctx: Context<CreateSessionTokenV2>,
        top_up: Option<bool>,
        valid_until: Option<i64>,
        lamports: Option<u64>,
    ) -> Result<()> {
        let (top_up, valid_until) = process_session_params(top_up, valid_until)?;
        create_session_token_handler_v2(ctx, top_up, valid_until, lamports)
    }

    pub fn revoke_session_v2(ctx: Context<RevokeSessionTokenV2>) -> Result<()> {
        revoke_session_token_handler_v2(ctx)
    }
}

fn process_session_params(top_up: Option<bool>, valid_until: Option<i64>) -> Result<(bool, i64)> {
    let top_up = top_up.unwrap_or(false);
    let valid_until = valid_until.unwrap_or(Clock::get()?.unix_timestamp + 60 * 60);
    Ok((top_up, valid_until))
}

// Create a SessionToken account
#[derive(Accounts)]
pub struct CreateSessionToken<'info> {
    #[account(
        init,
        seeds = [
            SessionToken::SEED_PREFIX.as_bytes(),
            target_program.key().as_ref(),
            session_signer.key().as_ref(),
            authority.key().as_ref()
        ],
        bump,
        payer = authority,
        space = SessionToken::LEN
    )]
    pub session_token: Account<'info, SessionToken>,

    #[account(mut)]
    pub session_signer: Signer<'info>,
    #[account(mut)]
    pub authority: Signer<'info>,

    /// CHECK the target program is actually a program.
    #[account(executable)]
    pub target_program: AccountInfo<'info>,

    pub system_program: Program<'info, System>,
}

struct CreateSessionTokenParams {
    authority: Pubkey,
    target_program: Pubkey,
    session_signer: Pubkey,
    top_up: bool,
    valid_until: i64,
    lamports: Option<u64>,
}

fn create_session_token_internal<'info>(
    session_token: &mut Account<'info, SessionToken>,
    params: CreateSessionTokenParams,
    system_program: AccountInfo<'info>,
    payer: AccountInfo<'info>,
    session_signer_account: AccountInfo<'info>,
) -> Result<()> {
    let authority = params.authority;
    let target_program = params.target_program;
    let session_signer = params.session_signer;
    let top_up = params.top_up;
    let valid_until = params.valid_until;
    let lamports = params.lamports;
    // Valid until can't be greater than a week
    require!(
        valid_until <= Clock::get()?.unix_timestamp + (60 * 60 * 24 * 7),
        SessionError::ValidityTooLong
    );

    session_token.set_inner(SessionToken {
        authority,
        target_program,
        session_signer,
        valid_until,
    });

    // Top up the session signer account with some lamports to pay for the transaction fees
    if top_up {
        system_program::transfer(
            CpiContext::new(
                system_program,
                system_program::Transfer {
                    from: payer,
                    to: session_signer_account,
                },
            ),
            lamports.unwrap_or(LAMPORTS_PER_SOL / 100),
        )?;
    }

    Ok(())
}

// Handler to create a session token account
pub fn create_session_token_handler(
    ctx: Context<CreateSessionToken>,
    top_up: bool,
    valid_until: i64,
    lamports: Option<u64>,
) -> Result<()> {
    create_session_token_internal(
        &mut ctx.accounts.session_token,
        CreateSessionTokenParams {
            authority: ctx.accounts.authority.key(),
            target_program: ctx.accounts.target_program.key(),
            session_signer: ctx.accounts.session_signer.key(),
            top_up,
            valid_until,
            lamports,
        },
        ctx.accounts.system_program.to_account_info(),
        ctx.accounts.authority.to_account_info(),
        ctx.accounts.session_signer.to_account_info(),
    )
}

// Create a SessionToken account
#[derive(Accounts)]
pub struct CreateSessionTokenWithPayer<'info> {
    #[account(
        init,
        seeds = [
            SessionToken::SEED_PREFIX.as_bytes(),
            target_program.key().as_ref(),
            session_signer.key().as_ref(),
            authority.key().as_ref()
        ],
        bump,
        payer = payer,
        space = SessionToken::LEN
    )]
    pub session_token: Account<'info, SessionToken>,

    #[account(mut)]
    pub session_signer: Signer<'info>,
    #[account(mut)]
    pub payer: Signer<'info>,
    pub authority: Signer<'info>,

    /// CHECK the target program is actually a program.
    #[account(executable)]
    pub target_program: AccountInfo<'info>,

    pub system_program: Program<'info, System>,
}

// Handler to create a session token account
pub fn create_session_token_with_payer_handler(
    ctx: Context<CreateSessionTokenWithPayer>,
    top_up: bool,
    valid_until: i64,
    lamports: Option<u64>,
) -> Result<()> {
    create_session_token_internal(
        &mut ctx.accounts.session_token,
        CreateSessionTokenParams {
            authority: ctx.accounts.authority.key(),
            target_program: ctx.accounts.target_program.key(),
            session_signer: ctx.accounts.session_signer.key(),
            top_up,
            valid_until,
            lamports,
        },
        ctx.accounts.system_program.to_account_info(),
        ctx.accounts.payer.to_account_info(),
        ctx.accounts.session_signer.to_account_info(),
    )
}

// Revoke a session token
// We allow *anyone* to revoke a session token. This is because the session token is designed to
// expire on it's own after a certain amount of time. However, if the session token is compromised
// anyone can revoke it immediately.
//
// One attack vector here to consider, however is that a malicious actor could enumerate all the tokens
// created using the program and revoke them all or keep revoking them as they are created. It is a
// nuisance but not a security risk. We can easily address this by whitelisting a revoker.
#[derive(Accounts)]
pub struct RevokeSessionToken<'info> {
    #[account(
        mut,
        seeds = [
            SessionToken::SEED_PREFIX.as_bytes(),
            session_token.target_program.key().as_ref(),
            session_token.session_signer.key().as_ref(),
            session_token.authority.key().as_ref()
        ],
        bump,
        has_one = authority,
        close = authority,
    )]
    pub session_token: Account<'info, SessionToken>,

    #[account(mut)]
    // Only the token authority can reclaim the rent
    pub authority: SystemAccount<'info>,

    pub system_program: Program<'info, System>,
}

// Handler to revoke a session token
pub fn revoke_session_token_handler(_: Context<RevokeSessionToken>) -> Result<()> {
    Ok(())
}

// V2 Accounts and Handlers

// Create a SessionTokenV2 account
#[derive(Accounts)]
pub struct CreateSessionTokenV2<'info> {
    #[account(
        init,
        seeds = [
            SessionTokenV2::SEED_PREFIX.as_bytes(),
            target_program.key().as_ref(),
            session_signer.key().as_ref(),
            authority.key().as_ref()
        ],
        bump,
        payer = fee_payer,
        space = SessionTokenV2::LEN
    )]
    pub session_token: Account<'info, SessionTokenV2>,

    #[account(mut)]
    pub session_signer: Signer<'info>,
    #[account(mut)]
    pub fee_payer: Signer<'info>,
    pub authority: Signer<'info>,

    /// CHECK the target program is actually a program.
    #[account(executable)]
    pub target_program: AccountInfo<'info>,

    pub system_program: Program<'info, System>,
}

struct CreateSessionTokenV2Params {
    authority: Pubkey,
    target_program: Pubkey,
    session_signer: Pubkey,
    fee_payer: Pubkey,
    top_up: bool,
    valid_until: i64,
    lamports: Option<u64>,
}

fn create_session_token_v2_internal<'info>(
    session_token: &mut Account<'info, SessionTokenV2>,
    params: CreateSessionTokenV2Params,
    system_program: AccountInfo<'info>,
    payer: AccountInfo<'info>,
    session_signer_account: AccountInfo<'info>,
) -> Result<()> {
    let authority = params.authority;
    let target_program = params.target_program;
    let session_signer = params.session_signer;
    let fee_payer = params.fee_payer;
    let top_up = params.top_up;
    let valid_until = params.valid_until;
    let lamports = params.lamports;
    // Valid until can't be greater than a week
    require!(
        valid_until <= Clock::get()?.unix_timestamp + (60 * 60 * 24 * 7),
        SessionError::ValidityTooLong
    );

    session_token.set_inner(SessionTokenV2 {
        authority,
        target_program,
        session_signer,
        fee_payer,
        valid_until,
    });

    // Top up the session signer account with some lamports to pay for the transaction fees
    if top_up {
        system_program::transfer(
            CpiContext::new(
                system_program,
                system_program::Transfer {
                    from: payer,
                    to: session_signer_account,
                },
            ),
            lamports.unwrap_or(LAMPORTS_PER_SOL / 100),
        )?;
    }

    Ok(())
}

// Handler to create a session token v2 account
pub fn create_session_token_handler_v2(
    ctx: Context<CreateSessionTokenV2>,
    top_up: bool,
    valid_until: i64,
    lamports: Option<u64>,
) -> Result<()> {
    create_session_token_v2_internal(
        &mut ctx.accounts.session_token,
        CreateSessionTokenV2Params {
            authority: ctx.accounts.authority.key(),
            target_program: ctx.accounts.target_program.key(),
            session_signer: ctx.accounts.session_signer.key(),
            fee_payer: ctx.accounts.fee_payer.key(),
            top_up,
            valid_until,
            lamports,
        },
        ctx.accounts.system_program.to_account_info(),
        ctx.accounts.fee_payer.to_account_info(),
        ctx.accounts.session_signer.to_account_info(),
    )
}

// Revoke a session token V2
//
// Anybody can revoke session but only the fee payer will receive the lamports back.
#[derive(Accounts)]
pub struct RevokeSessionTokenV2<'info> {
    #[account(
        mut,
        seeds = [
            SessionTokenV2::SEED_PREFIX.as_bytes(),
            session_token.target_program.key().as_ref(),
            session_token.session_signer.key().as_ref(),
            session_token.authority.key().as_ref()
        ],
        bump,
        has_one = fee_payer,
        has_one = authority,
        close = fee_payer,
    )]
    pub session_token: Account<'info, SessionTokenV2>,

    #[account(mut)]
    // Lamports are sent back to the fee payer
    pub fee_payer: SystemAccount<'info>,

    // Requires to be a signer if session is still active
    pub authority: SystemAccount<'info>,

    pub system_program: Program<'info, System>,
}

// Handler to revoke a session token V2
pub fn revoke_session_token_handler_v2(ctx: Context<RevokeSessionTokenV2>) -> Result<()> {
    // If the session is still active, the authority must be a signer
    if !ctx.accounts.session_token.is_expired()? {
        require!(
            ctx.accounts.authority.is_signer,
            SessionError::InvalidAuthority
        );
    }
    Ok(())
}

pub struct ValidityChecker<'info> {
    pub session_token: Account<'info, SessionToken>,
    pub session_signer: Signer<'info>,
    pub authority: Pubkey,
    pub target_program: Pubkey,
}

pub struct ValidityCheckerV2<'info> {
    pub session_token: Account<'info, SessionTokenV2>,
    pub session_signer: Signer<'info>,
    pub authority: Pubkey,
    pub target_program: Pubkey,
}

// SessionToken Account
#[account]
#[derive(Copy)]
pub struct SessionToken {
    pub authority: Pubkey,
    pub target_program: Pubkey,
    pub session_signer: Pubkey,
    pub valid_until: i64,
}

#[account]
#[derive(Copy)]
pub struct SessionTokenV2 {
    pub authority: Pubkey,
    pub target_program: Pubkey,
    pub session_signer: Pubkey,
    // account that paid for initialization and receives lamports back on revoking
    pub fee_payer: Pubkey,
    pub valid_until: i64,
}

impl SessionToken {
    pub const LEN: usize = 8 + std::mem::size_of::<Self>();
    pub const SEED_PREFIX: &'static str = "session_token";

    fn is_expired(&self) -> Result<bool> {
        let now = Clock::get()?.unix_timestamp;
        Ok(now < self.valid_until)
    }

    // validate the token
    pub fn validate(&self, ctx: ValidityChecker) -> Result<bool> {
        let target_program = ctx.target_program;
        let session_signer = ctx.session_signer.key();
        let authority = ctx.authority.key();

        // Check the PDA seeds
        let seeds = &[
            SessionToken::SEED_PREFIX.as_bytes(),
            target_program.as_ref(),
            session_signer.as_ref(),
            authority.as_ref(),
        ];

        let (pda, _) = Pubkey::find_program_address(seeds, &crate::id());

        require_eq!(pda, ctx.session_token.key(), SessionError::InvalidToken);

        // Check if the token has expired
        self.is_expired()
    }
}

impl SessionTokenV2 {
    pub const LEN: usize = 8 + std::mem::size_of::<Self>();
    pub const SEED_PREFIX: &'static str = "session_token_v2";
}

impl SessionTokenV2 {
    /// Returns `true` when the token has expired (`now >= valid_until`).
    pub fn is_expired(&self) -> Result<bool> {
        let now = Clock::get()?.unix_timestamp;
        Ok(now >= self.valid_until)
    }

    // validate the token
    pub fn validate(&self, ctx: ValidityCheckerV2) -> Result<bool> {
        let target_program = ctx.target_program;
        let session_signer = ctx.session_signer.key();
        let authority = ctx.authority.key();

        // Check the PDA seeds
        let seeds = &[
            SessionTokenV2::SEED_PREFIX.as_bytes(),
            target_program.as_ref(),
            session_signer.as_ref(),
            authority.as_ref(),
        ];

        let (pda, _) = Pubkey::find_program_address(seeds, &crate::id());

        require_eq!(pda, ctx.session_token.key(), SessionError::InvalidToken);

        // Check if the token is still valid (not expired)
        let expired = self.is_expired()?;
        Ok(!expired)
    }
}

pub trait Session<'info> {
    fn session_token(&self) -> Option<Account<'info, SessionToken>>;
    fn session_signer(&self) -> Signer<'info>;
    fn session_authority(&self) -> Pubkey;
    fn target_program(&self) -> Pubkey;

    fn is_valid(&self) -> Result<bool> {
        let session_token = self.session_token().ok_or(SessionError::NoToken)?;
        let validity_ctx = ValidityChecker {
            session_token: session_token.clone(),
            session_signer: self.session_signer(),
            authority: self.session_authority(),
            target_program: self.target_program(),
        };
        // Check if the token is valid
        session_token.validate(validity_ctx)
    }
}

pub trait SessionV2<'info> {
    fn session_token(&self) -> Option<Account<'info, SessionTokenV2>>;
    fn session_signer(&self) -> Signer<'info>;
    fn session_authority(&self) -> Pubkey;
    fn target_program(&self) -> Pubkey;

    fn is_valid(&self) -> Result<bool> {
        let session_token = self.session_token().ok_or(SessionError::NoToken)?;
        let validity_ctx = ValidityCheckerV2 {
            session_token: session_token.clone(),
            session_signer: self.session_signer(),
            authority: self.session_authority(),
            target_program: self.target_program(),
        };
        // Check if the token is valid
        session_token.validate(validity_ctx)
    }
}

#[error_code]
pub enum SessionError {
    #[msg("Requested validity is too long")]
    ValidityTooLong,
    #[msg("Invalid session token")]
    InvalidToken,
    #[msg("No session token provided")]
    NoToken,
    #[msg("Invalid authority")]
    InvalidAuthority,
}