Skip to content

feat: adds ttl_seconds support#420

Merged
jpvajda merged 1 commit into
mainfrom
feat/grant-ttl-support
Jul 21, 2025
Merged

feat: adds ttl_seconds support#420
jpvajda merged 1 commit into
mainfrom
feat/grant-ttl-support

Conversation

@jpvajda

@jpvajda jpvajda commented Jul 16, 2025

Copy link
Copy Markdown
Contributor

Add ttl_seconds support to grant token endpoint

TL;DR

Successfully implemented ttl_seconds parameter support for the grant token endpoint
🧪 SDK Implementation: Fully working with comprehensive tests - ready for production when API issue is fixed by Console Team.

🎯 What was implemented

Added support for the new ttl_seconds parameter to the deepgram.auth.grantToken() method, allowing users to specify custom token expiration times (1-3600 seconds).

Key Features:

  • ✅ Type-safe GrantTokenSchema interface with ttl_seconds parameter
  • ✅ Updated AuthRestClient.grantToken() method to accept configuration options
  • ✅ Full backward compatibility - existing code continues to work unchanged
  • ✅ Comprehensive test coverage (7 new test scenarios)
  • ✅ Updated Existing example with proper usage and logging

📁 Files Changed

New Files:

  • src/lib/types/GrantTokenSchema.ts - Schema interface for grant token parameters

Modified Files:

  • src/lib/types/index.ts - Export new schema
  • src/packages/AuthRestClient.ts - Updated method signature and implementation
  • tests/e2e/auth-grant-token.test.ts - Added comprehensive test coverage
  • tests/__utils__/mocks.ts - Updated mock to handle ttl_seconds parameter
  • examples/node-live-token/index.js - Fixed incorrect usage and added proper logging

🧪 Testing

Test Results:

  • All 229 tests passing (53 test suites)
  • 7 new grant token tests covering all scenarios
  • No regressions - all existing functionality intact
  • Backward compatibility verified

Test Coverage:

  • Default behavior (no ttl_seconds)
  • Custom ttl_seconds values
  • Custom endpoints with ttl_seconds
  • Empty options object
  • Error handling scenarios

🚀 Usage Examples

Basic usage:

// Default behavior (backward compatible)
const { result } = await deepgram.auth.grantToken();

// With custom TTL
const { result } = await deepgram.auth.grantToken({ ttl_seconds: 60 });

// With custom TTL and endpoint
const { result } = await deepgram.auth.grantToken(
  { ttl_seconds: 120 }, 
  ':version/auth/grant'
);

Real-world example:

// Generate a 5-minute token for live transcription
const { result: token, error } = await deepgram.auth.grantToken({
  ttl_seconds: 300,
});

if (!error) {
  const client = createClient({ accessToken: token.access_token });
  // Use temporary token for live transcription...
}

Types of changes

What types of changes does your code introduce to the community JavaScript SDK?
Put an x in the boxes that apply

  • Bugfix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update or tests (if none of the other choices apply)

Checklist

Put an x in the boxes that apply. You can also fill these out after creating the PR. If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your code.

  • I have read the CONTRIBUTING doc
  • I have lint'ed all of my code using repo standards
  • I have added tests that prove my fix is effective or that my feature works
  • I have added necessary documentation (if appropriate)

Further comments


Summary by CodeRabbit

  • New Features

    • Added support for specifying a custom token expiration time when generating temporary tokens.
  • Bug Fixes

    • Improved error and status logging during token generation and client creation.
  • Tests

    • Enhanced and expanded test coverage for token generation, including custom expiration times and endpoint handling.
  • Chores

    • Updated internal types and documentation to reflect new token expiration options.

@jpvajda jpvajda requested a review from lukeocodes July 16, 2025 20:36
@coderabbitai

coderabbitai Bot commented Jul 16, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

This change introduces support for specifying a token time-to-live (TTL) when generating temporary tokens. It adds a new GrantTokenSchema type with an optional ttl_seconds property, updates the AuthRestClient.grantToken method to accept and forward this option, and enhances tests and mocks to validate and simulate TTL behavior.

Changes

File(s) Change Summary
examples/node-live-token/index.js Simplified token request to use ttl_seconds, improved logging, and corrected token usage.
src/lib/types/GrantTokenSchema.ts Introduced GrantTokenSchema interface with optional ttl_seconds property.
src/lib/types/index.ts Exported GrantTokenSchema from the types index.
src/packages/AuthRestClient.ts Updated grantToken to accept GrantTokenSchema options, send as JSON body, and document it.
tests/utils/mocks.ts Enhanced mock to dynamically set expires_in based on ttl_seconds from request body.
tests/e2e/auth-grant-token.test.ts Added tests for TTL option, custom endpoint, and backward compatibility for grantToken.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant AuthRestClient
    participant AuthAPI

    Client->>AuthRestClient: grantToken({ ttl_seconds: 60 })
    AuthRestClient->>AuthAPI: POST /auth/grant (body: { ttl_seconds: 60 })
    AuthAPI-->>AuthRestClient: { access_token, expires_in }
    AuthRestClient-->>Client: { access_token, expires_in }
Loading

Possibly related PRs

  • feat: support token-based auth endpoint #377: The main PR extends the existing token grant functionality by adding TTL support and refining token request handling, building directly on the AuthRestClient's grantToken method introduced in the retrieved PR.

Suggested reviewers

  • naomi-lgbt
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/grant-ttl-support

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@codecov-commenter

Copy link
Copy Markdown

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 75.17%. Comparing base (b94ea56) to head (bfed827).

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #420      +/-   ##
==========================================
+ Coverage   75.13%   75.17%   +0.04%     
==========================================
  Files          26       26              
  Lines        1150     1152       +2     
  Branches      291      292       +1     
==========================================
+ Hits          864      866       +2     
  Misses        286      286              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
tests/e2e/auth-grant-token.test.ts (1)

75-95: LGTM! Consider validating TTL impact on expires_in.

The test properly validates the new ttl_seconds functionality. Consider adding an assertion to verify that the expires_in value reflects the requested TTL (e.g., expect(result.expires_in).toBeLessThanOrEqual(60)).

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b94ea56 and bfed827.

📒 Files selected for processing (6)
  • examples/node-live-token/index.js (1 hunks)
  • src/lib/types/GrantTokenSchema.ts (1 hunks)
  • src/lib/types/index.ts (1 hunks)
  • src/packages/AuthRestClient.ts (1 hunks)
  • tests/__utils__/mocks.ts (1 hunks)
  • tests/e2e/auth-grant-token.test.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
examples/node-live-token/index.js (6)
examples/node-agent-live/index.js (1)
  • deepgram (9-9)
examples/node-live/index.js (1)
  • deepgram (9-9)
examples/node-speak-live/index.js (1)
  • deepgram (10-10)
examples/node-read/index.js (2)
  • deepgram (8-8)
  • deepgram (11-16)
examples/node-prerecorded/index.js (6)
  • deepgram (65-65)
  • deepgram (68-75)
  • deepgram (84-84)
  • deepgram (91-93)
  • deepgram (100-100)
  • deepgram (103-105)
examples/node-speak/index.js (1)
  • deepgram (10-10)
tests/__utils__/mocks.ts (1)
tests/e2e/__mocks__/auth.ts (1)
  • mockGrantTokenResponse (5-9)
src/packages/AuthRestClient.ts (3)
src/lib/types/GrantTokenSchema.ts (1)
  • GrantTokenSchema (1-9)
src/lib/types/DeepgramResponse.ts (1)
  • DeepgramResponse (3-3)
src/lib/types/GrantTokenResponse.ts (1)
  • GrantTokenResponse (1-4)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Test Browser Builds
🔇 Additional comments (16)
src/lib/types/index.ts (1)

30-30: LGTM! Export addition follows conventions.

The export is properly placed in alphabetical order and follows the established pattern for making the new GrantTokenSchema interface publicly available.

tests/__utils__/mocks.ts (1)

127-147: LGTM! Mock enhancement properly supports ttl_seconds functionality.

The mock correctly:

  • Parses the request body to extract ttl_seconds parameter
  • Dynamically adjusts the expires_in field in the response
  • Handles JSON parsing errors gracefully by falling back to default response
  • Maintains backward compatibility
src/lib/types/GrantTokenSchema.ts (1)

1-9: LGTM! Well-designed interface with clear documentation.

The interface design is excellent:

  • Extends Record<string, unknown> for future extensibility
  • Optional ttl_seconds property maintains backward compatibility
  • Clear JSDoc documentation with appropriate constraints (1-3600 seconds)
  • Reasonable default example of 30 seconds

Note that the @minimum and @maximum constraints are documentation-only and not enforced at runtime. Consider adding runtime validation if needed.

examples/node-live-token/index.js (3)

11-15: LGTM! Example demonstrates the new API correctly.

The token generation now uses the simplified API with the ttl_seconds parameter, which clearly demonstrates the new functionality.


18-26: LGTM! Enhanced logging improves user experience.

The added console logging provides clear feedback about token generation status, expiration time, and token preview, which helps users understand the token lifecycle.


29-31: LGTM! Corrected client creation usage.

The client creation now correctly uses the accessToken property instead of a direct key, which aligns with the established pattern for token-based authentication.

src/packages/AuthRestClient.ts (4)

4-4: LGTM! Proper type import.

The import of GrantTokenSchema type is correctly added to support the new functionality.


12-12: LGTM! Documentation updated appropriately.

The JSDoc documentation clearly explains the new optional options parameter and its purpose for token configuration.


17-17: LGTM! Backward-compatible method signature.

The optional options parameter with default empty object maintains backward compatibility while enabling the new functionality.


22-25: LGTM! Proper request body serialization.

The implementation correctly:

  • Serializes the options object to JSON
  • Sets the appropriate Content-Type header
  • Maintains the existing error handling pattern
tests/e2e/auth-grant-token.test.ts (6)

26-54: LGTM! Well-structured test for basic functionality.

The test properly validates the default behavior with comprehensive assertions for error handling, result structure, and data types.


56-73: LGTM! Properly updated for new method signature.

The test correctly adapts to the new method signature by passing an empty options object as the first parameter, maintaining backward compatibility while testing custom endpoint functionality.


97-114: LGTM! Validates feature interaction properly.

The test correctly validates that ttl_seconds works in combination with custom endpoints, ensuring feature compatibility.


116-132: LGTM! Important backward compatibility test.

The test ensures that passing an empty options object maintains existing functionality, which is crucial for backward compatibility.


134-150: LGTM! Proper error handling test.

The test correctly validates DeepgramError handling with proper mocking and cleanup.


152-165: LGTM! Validates proper error re-throwing.

The test correctly validates that non-DeepgramError exceptions are re-thrown, maintaining expected error behavior.

@jpvajda jpvajda merged commit 5ed8004 into main Jul 21, 2025
7 checks passed
@jpvajda jpvajda deleted the feat/grant-ttl-support branch July 21, 2025 15:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants