import pg, {type PoolConfig} from 'pg'; import {parseIntoClientConfig} from 'pg-connection-string'; import {Session} from '@shopify/shopify-api'; import { SessionStorage, RdbmsSessionStorageOptions, } from '@shopify/shopify-app-session-storage'; import {migrationList} from './migrations'; import {PostgresConnection} from './postgres-connection'; import {PostgresSessionStorageMigrator} from './postgres-migrator'; export interface PostgreSQLSessionStorageOptions extends RdbmsSessionStorageOptions { port: number; /** * TLS settings for the connection, passed to `pg` as its `ssl` option. They * replace any TLS settings in the database URL. */ ssl?: PoolConfig['ssl']; /** * Connect without verified TLS when `NODE_ENV` is `production`. Set this * only for a PostgreSQL server on a network you trust. */ allowInsecureConnection?: boolean; } const defaultPostgreSQLSessionStorageOptions: PostgreSQLSessionStorageOptions = { sessionTableName: 'shopify_sessions', port: 3211, migratorOptions: { migrationDBIdentifier: 'shopify_sessions_migrations', migrationNameColumnName: 'migration_name', }, allowInsecureConnection: false, }; // pg 8 reads PGSSLMODE this way, only when neither the ssl option nor the URL // sets TLS. Check this again when pg changes its sslmode meanings in pg 9. function sslFromEnvironment(): PoolConfig['ssl'] { switch (process.env.PGSSLMODE) { case 'prefer': case 'require': case 'verify-ca': case 'verify-full': return true; case 'disable': return false; case 'no-verify': return {rejectUnauthorized: false}; default: return pg.defaults.ssl; } } function verifiesServer(ssl: PoolConfig['ssl']): boolean { return ( ssl === true || (typeof ssl === 'object' && ssl.rejectUnauthorized !== false) ); } function usesVerifiedTls(dbUrl: string, ssl: PoolConfig['ssl']): boolean { if (ssl != null) return verifiesServer(ssl); const urlSsl = parseIntoClientConfig(dbUrl).ssl; if (urlSsl === undefined) return verifiesServer(sslFromEnvironment()); // With uselibpqcompat, sslmode=require and verify-ca turn off the host name // check through checkServerIdentity. return ( verifiesServer(urlSsl) && !(typeof urlSsl === 'object' && urlSsl.checkServerIdentity) ); } export class PostgreSQLSessionStorage implements SessionStorage { static withCredentials( host: string, dbName: string, username: string, password: string, opts: Partial, ) { return new PostgreSQLSessionStorage( new URL( `postgres://${encodeURIComponent(username)}:${encodeURIComponent( password, )}@${host}/${encodeURIComponent(dbName)}`, ), opts, ); } public readonly ready: Promise; private internalInit: Promise; private options: PostgreSQLSessionStorageOptions; private client: PostgresConnection; private migrator: PostgresSessionStorageMigrator; constructor( dbUrl: URL | string, opts: Partial = {}, ) { this.options = {...defaultPostgreSQLSessionStorageOptions, ...opts}; const url = typeof dbUrl === 'string' ? dbUrl : dbUrl.toString(); if ( process.env.NODE_ENV === 'production' && !this.options.allowInsecureConnection && !usesVerifiedTls(url, this.options.ssl) ) { throw new Error( 'PostgreSQLSessionStorage requires TLS with certificate and host ' + 'name verification in production. Add sslmode=verify-full to the ' + 'URL or pass the ssl option, and do not use sslmode=disable, ' + 'sslmode=no-verify or rejectUnauthorized: false. For a server on ' + 'a network you trust, set allowInsecureConnection: true.', ); } this.internalInit = this.init(url); this.migrator = new PostgresSessionStorageMigrator( this.client, this.options.migratorOptions, migrationList, ); this.ready = this.migrator.applyMigrations(this.internalInit); } public async storeSession(session: Session): Promise { await this.ready; // Note milliseconds to seconds conversion for `expires` property const entries = session .toPropertyArray(true) .map(([key, value]) => key === 'expires' ? [key, Math.floor((value as number) / 1000)] : [key, value], ); const query = ` INSERT INTO "${this.options.sessionTableName}" (${entries.map(([key]) => `"${key}"`).join(', ')}) VALUES (${entries .map((_, i) => `${this.client.getArgumentPlaceholder(i + 1)}`) .join(', ')}) ON CONFLICT ("id") DO UPDATE SET ${entries .map(([key]) => `"${key}" = Excluded."${key}"`) .join(', ')}; `; await this.client.query( query, entries.map(([_key, value]) => value), ); return true; } public async loadSession(id: string): Promise { await this.ready; const query = ` SELECT * FROM "${this.options.sessionTableName}" WHERE "id" = ${this.client.getArgumentPlaceholder(1)}; `; const rows = await this.client.query(query, [id]); if (!Array.isArray(rows) || rows?.length !== 1) return undefined; const rawResult = rows[0] as any; return this.databaseRowToSession(rawResult); } public async deleteSession(id: string): Promise { await this.ready; const query = ` DELETE FROM "${this.options.sessionTableName}" WHERE "id" = ${this.client.getArgumentPlaceholder(1)}; `; await this.client.query(query, [id]); return true; } public async deleteSessions(ids: string[]): Promise { await this.ready; const query = ` DELETE FROM "${this.options.sessionTableName}" WHERE "id" IN (${ids .map((_, i) => `${this.client.getArgumentPlaceholder(i + 1)}`) .join(', ')}); `; await this.client.query(query, ids); return true; } public async findSessionsByShop(shop: string): Promise { await this.ready; const query = ` SELECT * FROM "${this.options.sessionTableName}" WHERE "shop" = ${this.client.getArgumentPlaceholder(1)}; `; const rows = await this.client.query(query, [shop]); if (!Array.isArray(rows) || rows?.length === 0) return []; const results: Session[] = rows.map((row: any) => { return this.databaseRowToSession(row); }); return results; } public disconnect(): Promise { return this.client.disconnect(); } private async init(dbUrl: string) { this.client = new PostgresConnection( dbUrl, this.options.sessionTableName, this.options.ssl, ); await this.connectClient(); await this.createTable(); } private async connectClient(): Promise { await this.client.connect(); } private async createTable() { const query = ` CREATE TABLE IF NOT EXISTS "${this.options.sessionTableName}" ( "id" varchar(255) NOT NULL PRIMARY KEY, "shop" varchar(255) NOT NULL, "state" varchar(255) NOT NULL, "isOnline" boolean NOT NULL, "scope" varchar(255), "expires" integer, "accessToken" varchar(255), "refreshToken" varchar(255), "refreshTokenExpires" bigint, "userId" bigint, "firstName" varchar(255), "lastName" varchar(255), "email" varchar(255), "accountOwner" boolean, "locale" varchar(255), "collaborator" boolean, "emailVerified" boolean ) `; await this.client.query(query); } private databaseRowToSession(row: any): Session { // convert seconds to milliseconds prior to creating Session object if (row.expires) row.expires *= 1000; // PostgreSQL returns bigint as string, convert to number for Session if (row.refreshTokenExpires) row.refreshTokenExpires = Number(row.refreshTokenExpires); return Session.fromPropertyArray(Object.entries(row), true); } }