1. dialects
prorm
  • prorm documentation
  • Known test gaps
  • Architecture
  • Core concepts
  • Database types & coverage
  • Getting started
  • Going further
  • compliance
    • Compliance
    • The security toolkit: `prorm audit`
    • Checklists by regulation
    • Declaring personal data
    • Evidence bundles
    • Evidence
    • Frameworks: `@Security`
    • Jurisdictions
    • Platform policies
    • Protecting data
    • The regulation dataset
    • Residency and cross-border transfers
    • Retention & integrity
    • Status
    • Subject rights
  • decorators
    • prorm with decorators
    • Models with decorators
    • Querying a decorated model
    • Relations with decorators
  • diagrams
    • Diagram generators
    • Chen diagram
    • Class diagram
    • Dependency diagram
    • ER diagram
    • Flow diagram
    • From your models to a diagram
    • Gantt diagram
    • Index diagram
    • Migration diagram
    • Model diagram
    • Package diagram
    • Crow’s-foot diagram
    • Schema documentation
    • Sequence diagram
    • State diagram
    • Tree diagram
  • dialects
    • SQL dialects
    • AlloyDB Dialect
    • AlloyDB Omni Dialect
    • Amazon Athena Dialect
    • Aurora DSQL Dialect
    • Amazon Aurora MySQL Dialect
    • Amazon Aurora PostgreSQL Dialect
    • Azure Database for MySQL Dialect
    • Azure Database for PostgreSQL Dialect
    • Azure SQL Database Dialect
    • Azure SQL Managed Instance Dialect
    • Google BigQuery Dialect
    • Citus Dialect
    • ClickHouse dialect
    • Cloud Authentication (`cloud-auth`)
    • Cloud SQL for SQL Server Dialect
    • Cloud SQL for MySQL Dialect
    • Cloud SQL for PostgreSQL Dialect
    • CockroachDB Dialect
    • Azure Cosmos DB for PostgreSQL Dialect
    • CrateDB Dialect
    • Cloudflare D1 Dialect
    • Databricks dialect
    • IBM Db2 Dialect
    • Dolt Dialect
    • Apache Doris Dialect
    • Druid Dialect
    • DuckDB Dialect
    • Exasol dialect
    • Microsoft Fabric Data Warehouse Dialect
    • Firebird Dialect
    • Greenplum Dialect
    • SAP HANA Dialect
    • MySQL HeatWave Dialect
    • Azure Data Explorer (Kusto) Dialect — T-SQL
    • MariaDB Dialect
    • Materialize Dialect
    • MonetDB Dialect
    • MotherDuck Dialect
    • Microsoft SQL Server Dialect
    • MySQL Dialect
    • Neon Dialect
    • OceanBase Dialect
    • openGauss Dialect
    • Oracle Dialect
    • Oracle Autonomous Database Dialect
    • ParadeDB Dialect
    • PolarDB Dialect
    • PostgreSQL Dialect
    • Presto Dialect
    • QuestDB Dialect
    • Aurora RDS Data API Dialect (`rdsdata`)
    • Amazon RDS for Db2 Dialect
    • Amazon RDS for MariaDB Dialect
    • Amazon RDS for SQL Server Dialect
    • Amazon RDS for MySQL Dialect
    • Amazon RDS for Oracle Dialect
    • Amazon RDS for PostgreSQL Dialect
    • Amazon Redshift
    • Amazon Redshift Data API Dialect
    • RisingWave Dialect
    • rqlite Dialect
    • SingleStore Dialect
    • Snowflake Dialect
    • Google Cloud Spanner Dialect
    • Spanner (PostgreSQL interface) Dialect
    • SQLite Dialect
    • StarRocks Dialect
    • Supabase Dialect
    • Azure Synapse Analytics (dedicated SQL pool)
    • Teradata Dialect
    • TiDB Dialect
    • TimescaleDB Dialect
    • Trino Dialect
    • Turso / libSQL Dialect
    • Vertica dialect
    • Vitess Dialect
    • Yellowbrick Dialect
    • YugabyteDB Dialect
  • guides
    • Access rules and behaviour profiles
    • ArangoDB (AQL)
    • Associations
    • Audit levels and escalation
    • Audit logging
    • In the browser
    • Bulk operations
    • Caching
    • Capabilities, tiers and team roles
    • CLI
    • Cloudflare
    • Compliance & data protection
    • Connection Pooling & Performance
    • Security in the console
    • Couchbase: structured N1QL queries
    • Data types
    • Decorators
    • Eager loading
    • Enums and constants
    • Error handling & error types
    • Extensions
    • External fields
    • Foreign data wrappers
    • Graph databases
    • Hooks & lifecycle events
    • Indexes & constraints
    • InfluxDB: structured Flux pipelines
    • klock-errors
    • klock — the `.klock` file
    • Local databases (`prorm db up`)
    • Structured log search — Splunk, Graylog, Papertrail, Sumo Logic
    • Logging
    • Grafana Loki: structured LogQL queries
    • MCP server
    • Migrate — the data transfer subsystem
    • Migrations & Schema Sync
    • Models from an existing database
    • Defining models
    • Multiple databases
    • OrientDB, Neptune and TigerGraph
    • Passwords
    • Importing a Prisma schema
    • Structured PromQL and MetricsQL
    • Query firewall
    • QueryInterface
    • Query operators reference
    • Query optimization
    • Composing find options with `pipe()` and `Q`
    • Query safety: the fail-closed WHERE guard
    • Querying
    • Raw Queries & Query Building
    • Read replicas
    • Schema diffing & migration generation
    • Views, triggers & other schema objects
    • Scopes & default scopes
    • Seeders
    • SPARQL / RDF triplestores
    • SQL constants
    • SQL features
    • SQL function builders
    • SQLite advanced features
    • StoreKey — a prod-orm database as the storage
    • Streaming results
    • Terraform
    • Transactions & Isolation Levels
    • Type mapping: legacy and modern
    • TypeScript types
    • Database users, roles & privileges
    • Validation & constraints
    • Virtual & Computed Fields
    • Writing docs
  • javascript
    • prorm in JavaScript
    • Models in JavaScript
    • Querying in JavaScript
    • Relations in JavaScript
  • runbooks
    • Operational runbooks
    • Connection failures
    • Credential rotation
    • Failover
    • Incident checklist
    • Deploying klock v2
    • Migration rollback
  • running-databases
    • Running databases in Docker
    • Running prorm under Bun in Docker
    • Running Cassandra in Docker with prorm
    • Running ClickHouse in Docker with prorm
    • Running CockroachDB in Docker with prorm
    • Running prorm under Deno in Docker
    • Running Elasticsearch in Docker with prorm
    • Running MariaDB in Docker with prorm
    • Running MongoDB in Docker with prorm
  • prorm control plane
    • Introduction
    • Authentication
    • Errors
    • Getting started
      • Service
        • Is it up
        • This description
    • Account
      • Sign-up and verification
        • Create an account
        • Exchange credentials for a token
        • Verify with the emailed code
        • Verify by clicking the emailed link
        • Name the parent or guardian
        • What a consent link is about
        • Give consent for a child's account
        • Ask the parent or guardian again
        • Send a new code and link
      • Family
        • Everyone this account is responsible for
        • One child, in detail
        • Turn a limit on or off
      • Profile
        • Who am I
        • Change the account
        • Every address on the account
        • Add an address
        • Confirm an address with the code mailed to it
        • Mail a fresh code to an unconfirmed address
        • Make an address primary
        • Remove an address
        • What this caller may do
    • Security
      • Sessions
        • Everywhere this account is signed in
        • Sign out everywhere else
        • Sign one out
        • A token for the CLI on a named machine
        • A token for the customer console, from the staff one
        • Park a sign-in for the CLI to collect
        • The CLI collecting its sign-in
        • The team's members' live sessions
        • Sign a member's session out
        • Sign an account out everywhere
        • Everywhere the account is signed in
        • Sign an account's session out
      • Single sign-on
        • Begin a single sign-on
        • The provider's return
        • Link the signed-in account to a team's provider
        • Which team an address signs in to
        • The team's single sign-on, as a member sees it
        • Set the team's OpenID Connect provider up, or change it
        • Remove the provider
        • The team's domain claims and the DNS record each needs
        • Prove a claimed domain
      • MFA and passwords
        • Start enrolling a second factor
        • Prove the app has it
        • Remove the second factor
        • Ask for a reset link
        • Set a new password with the emailed token
      • Klock
        • Open a device-bound klock session
        • Check in, for the next grant
        • Step up the session asking
        • Rotate the device key
        • Freeze a session
        • Unfreeze a session
        • A guest grant
        • The revocation feed
        • The published keyset
        • What this control plane supports
      • Devices
        • Your devices, or a team's
        • Approve a new device's pairing code
        • One device
        • Rename a device
        • Revoke a device
        • Suspend a device
        • Reinstate a suspended device
        • Wipe a device
        • Ask a device to rotate its key
        • The team's members' devices
        • Revoke a member's device
        • An account's devices
        • Revoke an account's device
        • Wipe an account's device
        • The device fleet
      • Access rules and behaviour
        • The access rules that bear on you
        • Add an access rule
        • This request, as the rules see it
        • One access rule
        • Remove an access rule
        • The behaviour profiles that bear on you
        • Add or change a behaviour profile
        • The profile presets
        • Your behaviour findings
        • Acknowledge a finding
        • One behaviour profile
        • Remove a behaviour profile
        • The team's access rules
        • Add a team access rule
        • Remove a team access rule
        • The team's behaviour profiles
        • Add or change a team behaviour profile
        • Remove a team behaviour profile
        • What the team's profiles caught
        • Acknowledge a team finding
      • Recovery and lockdown
        • Ask for a recovery link
        • Recover access with the emailed code
        • Is the account locked down
        • Lock the account down
        • Release a lockdown
        • Lock a member down
        • Release a member's lockdown
      • MCP tokens
        • Make a delegated token for one MCP client
        • The account's delegated tokens
        • Revoke a delegated token
        • What a delegated token may do now
        • Run one MCP tool with a delegated token
        • Run a device-signed MCP tool call relayed by the MCP Worker
      • Kerberos
        • Give the team its own Kerberos realm
        • The team's realm
        • Remove the team's realm
    • Logging and monitoring
      • Audit log
        • What has been done to the account
        • What has happened to this account
        • The account's audit trail
      • Operations
        • Everything that has been asked of this database
        • One, with its steps
        • Stop it
        • Put a failed one back in the queue
        • Every operation, across all accounts
      • Metrics and events
        • Every measurement, for a graph
        • Who did what to it
    • Billing
      • Plans and pricing
        • What the plans allow
        • The rate card
        • What one database would cost
        • What this account is paying for, itemised
      • Subscriptions and invoices
        • What this month's invoice will say
        • What this account is on
        • What it has been charged
        • Start a Stripe Checkout session
        • Open the customer portal
        • Stripe's events
        • Buy more connection pools
      • Team billing
        • The team's billing account
        • What the team has been charged
        • What this month's invoice will say
        • The team's cards
        • Add a card, through a Stripe-hosted setup session
        • Make a card the team's default
        • Remove a card
        • Start the team paying
        • Open the Stripe portal on the team's customer
        • Change the team's plan
        • Who receives the team's bills
        • How the team pays for transfers
    • Support
      • Support chat
        • My conversations
        • Start a conversation
        • Every support conversation, open first
        • A ticket for the socket
        • One conversation, with who is in it and who is connected
        • Rename a group; open or close a support conversation
        • The lines, oldest first
        • Say something
        • Add somebody
        • Mark read
    • Administration
      • Users
        • Every account
        • One account, with everything hanging off it
        • Grant or revoke admin
        • Verify an account by hand
        • Lock or unlock sign-in
        • Allow or hold provisioning
        • Send the verification mail again
        • Set the plan by hand
      • Platform
        • Every database and store, across all accounts
        • The counts worth putting on a dashboard
      • Staff and permissions
        • What kind of admin the caller is, and which scopes they hold
        • The admin presets
        • Every admin, and the scopes each resolves to
        • Make an account an admin of a kind
        • Change an admin's kind, or a custom admin's scopes
        • Revoke admin
      • Team administration
        • Every team, with its owner and size
        • One team in full — members with their accounts, and projects
        • Hand the team to another member
        • Put an account in the team, active at once
        • Change a member's role
        • Remove a member
      • Assumed identities
        • Assume an identity — act as a customer account
        • The identities the caller holds open
        • End an assumed identity
      • Support inbox
        • The platform's addresses
        • Add a platform address
        • One address, with its counts
        • Change an address's label, routing, or whether it accepts mail
        • Remove an address that holds no mail
        • Make, adopt or repair the address's routing rule
        • Every admin's personal address, made where missing
        • File a raw message, as if it had arrived
        • The inbox
        • One message, whole
        • Mark a message
        • Hand a message to an admin, or take it back
        • Leave an internal note
        • Reply, from the address the message came to
        • What is waiting
    • Databases
      • Databases
        • Data stores
          • Every data store on the account
          • Provision a data store
          • Change a data store that is already running
          • One data store
          • Deprovision it
          • Report what it is using
          • How to reach a data store
        • Connections and credentials
          • The api keys on a database
          • Issue a key
          • Revoke a key
          • The engine users we created
          • Create a user inside the database
          • Give a user a new password
          • Drop a user
          • How the database is reached
          • Set how it is reached
          • Revoke every api key on it
          • How to connect to it
          • The ssh keys that open its bastion
          • Add a key, or have one made
          • The private half of a generated key, once
          • Revoke an ssh key
        • Schema and objects
          • The SQL objects we put in it
          • Create one, and apply it
          • What is in the database, as the engine reports it
          • One table
          • What it would run, without running it
          • Redefine an object in place
          • Drop it
          • The extensions installed in it
        • Migrations
          • A plan compiled to statements, recording nothing
          • The migrations recorded for it
          • Record one
          • Apply everything recorded and not yet run
          • Apply everything pending, oldest version first
        • Lifecycle
          • Grow or shrink it
          • Stop it accepting connections
          • Start it again
          • Move it to another region
        • Backups and replicas
          • Take a backup
          • The backups it has
          • Restore one into it
          • What has been restored into it, and from where
          • Its read copies
          • Add one
        • Policies
          • The catalog
          • One policy
          • What this database is held to
          • Switch a policy on, or change its knobs
          • Switch it off
          • Mark the policies reviewed
          • Evaluate the periodic policies now
          • Who is behind a credential
        • Passwordless
          • The database's passwordless sessions
          • Issue a passwordless session (v1)
          • Revoke a passwordless session
          • Bind a session to a device key
          • Issue a v2 session for a host to bind
          • Redeem an enrolment ticket on the host
          • Check a passwordless credential
          • Run one described query under a passwordless credential
        • Database roles
          • The database's roles
          • Define a role
          • One role
          • Change what a role permits
          • Delete a role, and revoke every key granted it
          • Grant a role, which mints a key
          • Who holds a role
          • The api keys bound to a role
        • Pools
          • A database's connection pools, and how busy each is
          • Open another pool
          • Rename a pool or change its size
          • Close a pool
        • Data plane
          • Run a query against a database
          • Several statements, in order, over one connection
          • Is this database answering
          • What the proxy itself is holding
        • Transfers
          • The strategies this account's tier may use
          • Price a transfer without creating it
          • The account's transfer jobs, newest first
          • Create a transfer job
          • One job, and whether its certificate holds
          • Cancel an unfinished job
          • Start a created job, confirming its price
          • Report a job's status (the runner, or the owner's side of a local run)
        • Every database on the account
        • Provision a database
        • Change a database that is already running
        • One database
        • Deprovision it
        • Read or write it
        • Report what it is using
        • The engines this API will provision
        • Where a managed database can be put
    • Teams
      • Teams
        • Members
          • Who is on it
          • Invite somebody
          • Accept an invitation
          • Change somebody's role
          • Remove somebody
        • Projects
          • The projects a team runs
          • Start one
          • Rename a project, or move its environment
          • Delete a project
          • One project, and what is in it
          • Put a database or store in it
          • What is in a project
          • Take one out
        • The teams this account is on
        • Start one
        • The twelve roles, and what each may do
        • Rename a team
        • Close a team
        • One team
        • Hand the team to somebody else
        • Leave a team
    • Schemas
      • Error
      • ValidationErrors
      • Token
      • PolicyCategory
      • PolicySeverity
      • PolicyAction
      • PolicyTrigger
      • PolicyParam
      • Policy
      • PolicyCatalog
      • PolicyAssignment
      • PolicyOutcome
      • PolicyFiring
      • CredentialTrace
      • Relation
      • Restrictions
      • ChildSummary
      • SignupRequest
      • SigninRequest
      • UpdateMeRequest
      • User
      • Address
      • GeoPoint
      • D1Region
      • Usage
      • UsageReport
      • Resource
      • Database
      • DataStore
      • NewDatabase
      • NewDataStore
      • QueryRequest
      • DatabasePrivilege
      • ApiKey
      • DbUser
      • Access
      • AccessRequest
      • DatabaseObject
      • NewDatabaseObject
      • NewMigration
      • SchemaOperation
      • Migration
      • Operation
      • Session
      • AdminPowers
      • Admin
      • AuditEntry
      • TeamRole
      • Conversation
      • ChatMessage
      • TeamSso
      • Team
      • TeamMember
      • SshKey
      • ConnectionInfo
      • InboxAddress
      • InboxMailbox
      • InboxMessageSummary
      • InboxMessage
      • InboxNote
      • Page
      • Quote
      • Plan
      • ApiError
      • CapabilityRefusal
      • KlockErrorCode
      • PageWindow
      • SessionView
      • KlockStepUpRequest
      • KlockOpenRequest
      • KlockOpenedSession
      • UpdateMeResult
      • CapabilitiesView
      • SessionLimits
      • Device
      • DeviceListed
      • DeviceTeamRef
      • DeviceCommand
      • DeviceAuditLine
      • DeviceActionRequest
      • StaffActionRequest
      • ManagedSession
      • SessionRevoked
      • AccessRule
      • AccessRuleRequest
      • BehaviourProfile
      • BehaviourProfileRequest
      • BehaviourProfileSaved
      • BehaviourFinding
      • BehaviourFindingAck
      • StepUpProof
      • Removed
      • MemberLockdownRequest
      • McpClient
      • McpDelegatedView
      • McpToolCall
      • McpForwardRequest
      • PasswordlessScope
      • RoleScope
      • PasswordlessSession
      • PasswordlessTlsMaterial
      • PasswordlessKerberosMaterial
      • ServiceDeviceKeys
      • ServiceSession
      • DatabaseRole
      • TransferEndpoint
      • TransferJobRequest
      • TransferQuote
      • TransferStrategy
      • TransferJob
      • TransferJobAccess
      • Pool
      • PoolAllowance
      • BillingSubscription
      • Invoice
      • BillingContact
      • PaymentMethod
      • UpcomingCharges
      • TeamBilling
      • TeamKerberosRealm
      • TeamSsoDomain
      • TeamSsoResponse
      • StoreConnection
      • BatchFailure
      • ProxyStatus
  1. dialects

Cloud Authentication (`cloud-auth`)

Overview

src/dialects/cloud-auth/ is the shared authentication layer for managed-cloud
dialects: AWS RDS/Aurora IAM, Microsoft Entra ID (Azure SQL, Synapse,
Fabric, Azure Database for PostgreSQL/MySQL, Kusto, Cosmos DB) and Google
Cloud SQL / AlloyDB IAM
. It is not a dialect; dialects import it.

It has three layers, each usable on its own:

LayerExports
Token providersrdsIamTokenProvider, entraTokenProvider, googleIamTokenProvider, cachedTokenProvider
Driver wiringpgAuth, mysqlAuth, tediousAuth, tediousTokenCredentialAuth, tokenCredentialFrom
ConnectorscloudSqlConnectorOptions, alloyDbConnectorOptions
TLSrdsCaBundle, rdsCaBundleUrl, pgVerifiedTls, mysqlVerifiedTls, tediousVerifiedTls, assessTls
SafetyCloudAuthError, redactSecrets, registerSecret
// Inside the package (a dialect under src/dialects/):
import { rdsIamTokenProvider, pgAuth, pgVerifiedTls, rdsCaBundle } from '../cloud-auth';

The module is not exported from the package root; applications reach it through
the managed dialects' dialectOptions (iamAuth, entra, cloudSql.iam, …).
Each of these pages has a tab per login method under Managed and cloud
variants
:

  • {icon:cloud} RDS / Aurora PostgreSQL — iamAuth: an RDS IAM token per connection (Aurora too)
  • {icon:cloud} RDS / Aurora MySQL — iamAuth over mysql_clear_password (Aurora too)
  • {icon:cloud} Aurora DSQL — its own @aws-sdk/dsql-signer token, or your tokenProvider
  • {icon:cloud} Azure SQL Database — entra with a default, managed-identity or service-principal credential (Managed Instance, Fabric)
  • {icon:cloud} Azure Database for PostgreSQL — entra, the principal as the user (MySQL, Cosmos DB for PostgreSQL)
  • {icon:cloud} Kusto — an Entra credential scoped to the cluster
  • {icon:cloud} Cloud SQL for PostgreSQL — the Cloud SQL connector, with or without IAM (MySQL, SQL Server)
  • {icon:cloud} AlloyDB — manual Google IAM with iam: true

[!CAUTION] RDS for MariaDB refuses IAM
RDS for MariaDB throws on iamAuth and tokenProvider:
the mariadb connector takes a password fixed when the pool is created, so a
15-minute token would break every connection opened after it expires.

Optional SDKs

Every cloud SDK is an optional peer dependency, loaded with a literal
require() inside a function the first time a token is needed. Importing
cloud-auth, or constructing a provider, loads nothing. A missing SDK throws
CloudAuthError with code: 'SDK_MISSING', packageName, and the
npm install line.

PackageNeeded for
@aws-sdk/rds-signerrdsIamTokenProvider
@azure/identityentraTokenProvider (not for credential: { type: 'credential' })
google-auth-librarygoogleIamTokenProvider (not when you pass authClient)
@google-cloud/cloud-sql-connectorcloudSqlConnectorOptions (not when you pass connector)

Token providers

Every provider is a TokenProvider:

type TokenProvider = () => Promise<{ token: string; expiresAt: Date }>;

The built-in ones return a CachedTokenProvider, which:

  • returns the cached token until expiresAt − margin (margin 2 minutes by
    default, clamped to half the token's lifetime);
  • shares a single in-flight fetch between concurrent callers;
  • serves the previous token if a refresh fails while it is still unexpired,
    and throws once it has expired;
  • has invalidate(), peek(), provider and a secret-free description.

Wrap your own source (a vault, a sidecar) with cachedTokenProvider(fetch)
to get the same behaviour and use the driver helpers with it.

AWS RDS / Aurora IAM

const provider = rdsIamTokenProvider({
  hostname: 'mydb.abc123.us-east-1.rds.amazonaws.com', // the real endpoint, not a Route 53 alias
  port: 5432,
  username: 'app_user',
  region: 'us-east-1', // optional: resolved by the SDK otherwise
  // credentials: { accessKeyId, secretAccessKey, sessionToken } | async () => creds,
  // profile: 'prod',           // used only when credentials is not set
});

@aws-sdk/rds-signer's Signer is built once with { hostname, port, username, region, credentials | profile } and getAuthToken() (no
arguments) signs a token locally. Tokens last 15 minutes; with temporary
credentials that expire sooner, expiresAt is capped to their expiration.
Credentials default to the Node provider chain. Works for RDS and Aurora
PostgreSQL / MySQL / MariaDB and for RDS Proxy. Aurora DSQL uses
@aws-sdk/dsql-signer instead (see the auroradsql dialect).

Microsoft Entra ID

const provider = entraTokenProvider({
  target: 'postgres-flexible', // or scope: '…/.default'
  credential: { type: 'default' }, // the default
});
targetScope
azure-sql, synapse, fabrichttps://database.windows.net/.default
postgres-flexible, mysql-flexiblehttps://ossrdbms-aad.database.windows.net/.default
kusto + kustoClusterUrihttps://<cluster>.<region>.kusto.windows.net/.default
kusto without a clusterhttps://kusto.kusto.windows.net/.default
cosmoshttps://cosmos.azure.com/.default
cosmos-postgreshttps://token.postgres.cosmos.azure.com/.default

Public-cloud values. For sovereign clouds pass scope (e.g.
https://ossrdbms-aad.database.usgovcloudapi.net/.default).

[!WARNING] One audience per token
Microsoft has announced that from January 2027 Azure Database for MySQL
will only accept tokens for the ossrdbms audience, so do not reuse a token
minted for another scope.

Credentials:

credentialBuilt with
{ type: 'default', managedIdentityClientId?, tenantId? }DefaultAzureCredential
{ type: 'managed-identity', clientId? | resourceId? }ManagedIdentityCredential
{ type: 'client-secret', tenantId, clientId, clientSecret }ClientSecretCredential
{ type: 'credential', credential }your TokenCredential (no SDK loaded)

Entra tokens are valid for 5–60 minutes; the expiry reported by the
credential is used.

Google Cloud SQL / AlloyDB IAM (manual)

const provider = googleIamTokenProvider({ target: 'cloud-sql' }); // or 'alloydb'

Uses Application Default Credentials (or keyFilename, credentials, or your
own authClient) with the login scope:

TargetScope
cloud-sqlhttps://www.googleapis.com/auth/sqlservice.login
alloydbhttps://www.googleapis.com/auth/alloydb.login

The database user is the IAM principal: googleIamDatabaseUser(email, 'postgres') strips a service account's .gserviceaccount.com;
googleIamDatabaseUser(email, 'mysql') keeps the part before @.

How a token reaches the server

The three flows differ in who mints the token and where TLS comes from, but
every one goes through the same cache and the same per-connection hook. The
diagram follows cachedTokenProvider() (core.ts), pgAuth() (drivers.ts)
and cloudSqlConnectorOptions() (google.ts).

sequenceDiagram
  participant D as Dialect.connect()
  participant P as CachedTokenProvider
  participant S as Cloud SDK
  participant Drv as pg / mysql2 / tedious
  participant DB as Database
  D->>Drv: pool config + auth fragment
  Drv->>P: new connection: password()
  alt cached and before refreshAt
    P-->>Drv: cached token
  else fetch (one in flight)
    alt AWS RDS IAM
      P->>S: Signer.getAuthToken()
      S-->>P: presigned token, 15 min
    else Azure Entra ID
      P->>S: credential.getToken(scope)
      S-->>P: JWT with expiresOnTimestamp
    else Cloud SQL / AlloyDB manual IAM
      P->>S: authClient.getAccessToken()
      S-->>P: OAuth2 token (ADC)
    end
    P-->>Drv: validated, registered as secret
  end
  Drv->>DB: login over verified TLS

The provider hands out the cached token until expiresAt − margin, shares one
in-flight refresh between concurrent callers, and the driver hook (password()
on pg, the mysql_clear_password plugin on mysql2, beforeConnect on
mssql) runs for every new pooled connection, so a pool that outlives a token
keeps logging in.

sequenceDiagram
  participant D as Cloud SQL dialect connect()
  participant C as Cloud SQL connector
  participant G as Google APIs
  participant Drv as pg / mysql2 / tedious
  participant DB as Cloud SQL instance
  D->>C: cloudSqlConnectorOptions(driver, options)
  C->>G: instance metadata + ephemeral client certificate
  G-->>C: certificate, server CA, IP
  C-->>D: { stream } or { connector, encrypt: false }
  D->>Drv: pool config with the connector options
  Drv->>C: open connection
  C->>DB: mTLS tunnel (IAM login inside it when iam is automatic)
  DB-->>Drv: session

With the connector there is no token in the client at all for the database
login: the connector authenticates the tunnel with Google credentials and,
for pg and mysql2, logs in as the IAM principal inside it. SQL Server has
no IAM login, so iam with the tedious connector throws UNSUPPORTED.

Wiring a provider into a driver

A token read once when the pool is created works until it expires and then
every new pooled connection fails. Each helper returns the fragment that makes
the driver fetch a current token per new connection. Pass the pool's TLS
settings so the helper can warn when the token would travel without verified
TLS.

DriverMechanismDialect call site
pgpassword as an async functionPostgresDialect.connect() pool config
mysql2authPlugins.mysql_clear_password (async)MySQLDialect.connect() pool config
tedious / mssqlaccess token + beforeConnect swapMSSQLDialect.connect() config
tedious ≥ 18authentication.type: 'token-credential'same

pg

const ssl = pgVerifiedTls(rdsCaBundle()); // or pgVerifiedTls() for Azure
const pool = new Pool({
  host,
  port,
  database,
  user: 'app_user',
  ssl,
  ...pgAuth(provider, { ssl }), // { password: async () => token }
});

Used by: RDS/Aurora PostgreSQL, Azure Database for PostgreSQL, Cloud SQL
PostgreSQL and AlloyDB (manual IAM), Cosmos DB for PostgreSQL.

mysql2

const ssl = mysqlVerifiedTls(rdsCaBundle());
const pool = mysql.createPool({
  host,
  port,
  database,
  user: 'app_user',
  ssl,
  ...mysqlAuth(provider, { ssl }), // { authPlugins: { mysql_clear_password } }
});

mysql2 has no password callback, and the pool's connection event fires only
after login, so neither can refresh a token. RDS IAM (AWSAuthenticationPlugin),
Azure MySQL Entra and Cloud SQL IAM all make the server switch to
mysql_clear_password; mysql2 then calls the plugin, asynchronously, for each
new connection. Do not set password or enableCleartextPlugin. The
plugin refuses (INSECURE_TRANSPORT) to send the token on a connection with no
ssl, no connector stream and no local socketPath.

Used by: RDS/Aurora MySQL and MariaDB, Azure Database for MySQL, Cloud SQL MySQL.

tedious / mssql

const auth = tediousAuth(provider, { tls: tediousVerifiedTls() });
await auth.prime(); // before creating the pool
const pool = new mssql.ConnectionPool({
  server,
  database,
  options: tediousVerifiedTls(),
  authentication: auth.authentication, // no user/password
  beforeConnect: auth.beforeConnect,
});

tedious validates authentication.options.token when each Connection is
constructed and reads it again only when it sends the login packet. mssql
deep-clones its config once, when the pool is created, so the clone holds
whatever token existed then; beforeConnect (which mssql calls for each new
pooled connection, before login) writes the current token into that
connection. Reading the token inside the refresh margin starts a background
refresh — no timers. Works with tedious 16 (bundled by mssql 10) and 18.

With tedious ≥ 18 / mssql ≥ 11 there is a fully async alternative:

const pool = new mssql.ConnectionPool({
  server,
  database,
  options: tediousVerifiedTls(),
  ...tediousTokenCredentialAuth(provider, { tls: tediousVerifiedTls() }),
});

Used by: Azure SQL Database / Managed Instance, Synapse, Fabric.

Cloud SQL connector

const cx = await cloudSqlConnectorOptions('pg', {
  instanceConnectionName: 'project:region:instance',
  ipType: 'PRIVATE', // 'PUBLIC' (default) | 'PRIVATE' | 'PSC'
  iam: true, // automatic IAM auth; pg and mysql2 only
});
const pool = new Pool({ ...cx.driverOptions, user: 'sa@project.iam', database: 'app' });
// shutdown: await pool.end(); await cx.close();

driverOptions is { stream } for pg and mysql2, and { connector, encrypt: false } for tedious (merge into tedious/mssql options). The
connector does mTLS itself, so pass 'connector' as the TLS posture to the
driver helpers. Automatic IAM is not available for SQL Server; asking for it
throws UNSUPPORTED before anything loads. close() closes only a connector
this module created.

AlloyDB

alloyDbConnectorOptions({ instanceUri, ipType, iam, connector? }) returns
pg options from an AlloyDB connector object with a getOptions({ instanceUri, ipType, authType }) method. Google documents AlloyDB language connectors for
Java, Python and Go, and there is no Node.js connector package on npm, so
nothing is loaded for you: without a connector it throws UNSUPPORTED. Pass
your own connector, or use manual IAM: googleIamTokenProvider({ target: 'alloydb' }) with pgAuth() and TLS (or the AlloyDB Auth Proxy).

TLS

[!IMPORTANT] Tokens are bearer credentials
Anyone who intercepts one can log in until it expires. Every driver helper
classifies the TLS config (assessTls) and warns once when it is none or
unverified.

CloudDefault server-sideWhat the client needs for verified TLS
AWSTLS available; PG 15+ defaults rds.force_ssl=1The RDS CA bundle — not in Node's trust store. ssl: pgVerifiedTls(rdsCaBundle()). RDS Proxy uses ACM certificates Node already trusts. mysql2 also accepts its built-in ssl: 'Amazon RDS' profile.
AzurePG/MySQL flexible server require TLS; Azure SQL always encryptsPublic roots (DigiCert / Microsoft), so pgVerifiedTls() / mysqlVerifiedTls() with the default trust store; tedious encrypt: true, trustServerCertificate: false.
GoogleConnectors: mTLS, alwaysUse a connector (tls: 'connector'), or for direct connections the instance's server CA, downloaded from the instance.

Strict mode: tls: 'verify'

Three dialects whose service presents a certificate Node does not trust by
default — Supabase (SupabaseTlsMode), MySQL HeatWave
(HeatWaveTlsMode) and AlloyDB (AlloyDBTlsMode) — take a
tls option in dialectOptions with two values:

tlsWithout a CA (sslRootCert / tlsCa / ssl)With a CA
'prefer-verify' (default)falls back to encrypted-but-unverified TLS and logs one warningverified
'verify'throws at construction rather than fall backverified

An explicit ssl of your own always wins over the default. No other dialect
has this option; the managed AWS, Azure and Cloud SQL dialects refuse to send
a token over unverified TLS (INSECURE_TRANSPORT) but leave a password
login to the driver's defaults.

The RDS CA bundle

This module does not vendor or download it. Download it once, from AWS:

  • all commercial regions: https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem
  • one region: https://truststore.pki.rds.amazonaws.com/<region>/<region>-bundle.pem
    (rdsCaBundleUrl(region); GovCloud uses truststore.pki.us-gov-west-1.rds.amazonaws.com)

Then rdsCaBundle('/path/global-bundle.pem'), or set
PRORM_RDS_CA_BUNDLE=/path/global-bundle.pem and call rdsCaBundle(). It
throws INVALID_CONFIG (with the download URL) if no path is set, the file is
unreadable, or it holds no PEM certificate.

Errors and redaction

Everything throws CloudAuthError with a code:

CodeMeaning
SDK_MISSINGOptional SDK not installed; packageName says which
TOKEN_FETCH_FAILEDThe SDK or credential chain failed
INVALID_TOKENA provider returned no token, no valid expiresAt, or an expired one
TOKEN_UNAVAILABLEtediousAuth read before prime() / after the token expired
INVALID_CONFIGBad options
INSECURE_TRANSPORTmysql2 plugin refused to send a token without TLS
UNSUPPORTEDe.g. IAM through the tedious connector

Tokens never appear in errors or log lines:

  • every minted token (and any client secret or AWS secret key passed in) is
    registered, and redactSecrets() replaces it wherever it appears;
  • pattern redaction covers RDS presigned signatures/credentials, JWTs, Google
    ya29. tokens, Bearer headers and password= / token: pairs;
  • CloudAuthError.message and its cause (rebuilt from the original error,
    with message and stack redacted and other properties dropped) go through it;
  • token objects keep the secret out of JSON.stringify, util.inspect,
    String() and object spread — only .token returns it.

For dialect authors

  1. Build the provider in the constructor (cheap; loads nothing).
  2. In connect(), merge the driver helper's fragment into the pool config, and
    pass the same ssl/tls value you give the pool.
  3. On an authentication failure, call provider.invalidate() before retrying.
  4. Close connector handles in disconnect().

The base PostgresDialect, MySQLDialect and MSSQLDialect currently build
their pool configs from fixed fields, so a function password,
authPlugins, stream or beforeConnect cannot reach the driver without a
small hook in each base class.

Modified at 2026-10-04 00:40:16
Previous
ClickHouse dialect
Next
Cloud SQL for SQL Server Dialect
Built with