142 lines
6.0 KiB
TypeScript
142 lines
6.0 KiB
TypeScript
import { withTx, type Pool } from "khb_common";
|
|
import { decrypt, encrypt } from "./crypto.js";
|
|
|
|
export type Env = "sandbox" | "production";
|
|
|
|
export interface Connection {
|
|
environment: Env;
|
|
realmId: string;
|
|
accessToken: string;
|
|
refreshToken: string;
|
|
accessExpiresAt: Date;
|
|
refreshExpiresAt: Date;
|
|
authorizedAt: Date;
|
|
refreshedAt: Date;
|
|
/** ok | reauth_needed (refresh token отозван или просрочен: нужна новая авторизация человеком) */
|
|
status: "ok" | "reauth_needed";
|
|
}
|
|
|
|
/** Операции над соединением внутри блокировки (одно обновление токена за раз: refresh token одноразовый). */
|
|
export interface LockedConn {
|
|
get(): Connection | null;
|
|
save(c: Connection): Promise<void>;
|
|
/** Удалить соединение (токены) совсем. */
|
|
remove(): Promise<void>;
|
|
}
|
|
|
|
export interface Store {
|
|
saveState(state: string, env: Env): Promise<void>;
|
|
/** Одноразово: возвращает окружение, если state есть и моложе 10 минут; затем удаляет. */
|
|
consumeState(state: string): Promise<Env | null>;
|
|
withLock<T>(env: Env, fn: (c: LockedConn) => Promise<T>): Promise<T>;
|
|
read(env: Env): Promise<Connection | null>;
|
|
}
|
|
|
|
export class PgStore implements Store {
|
|
constructor(
|
|
private readonly pool: Pool,
|
|
private readonly key: Buffer,
|
|
) {}
|
|
|
|
async saveState(state: string, env: Env): Promise<void> {
|
|
await this.pool.query("delete from qbo_oauth_state where created_at < now() - interval '1 hour'");
|
|
await this.pool.query("insert into qbo_oauth_state (state, environment) values ($1, $2)", [state, env]);
|
|
}
|
|
|
|
async consumeState(state: string): Promise<Env | null> {
|
|
const r = await this.pool.query(
|
|
"delete from qbo_oauth_state where state = $1 returning environment, created_at > now() - interval '10 minutes' as fresh",
|
|
[state],
|
|
);
|
|
const row = r.rows[0] as { environment: Env; fresh: boolean } | undefined;
|
|
return row && row.fresh ? row.environment : null;
|
|
}
|
|
|
|
/** realmId хранится зашифрованным (требование Intuit); открытое значение из старых записей читается как есть. */
|
|
private readRealm(v: string): string {
|
|
return v.startsWith("v1.") ? decrypt(v, this.key) : v;
|
|
}
|
|
|
|
/** Однократно шифрует realm_id в уже существующих записях (вызывается при старте). */
|
|
async encryptExistingRealms(): Promise<number> {
|
|
const r = await this.pool.query("select environment, realm_id from qbo_connection where realm_id not like 'v1.%'");
|
|
for (const row of r.rows as Array<{ environment: string; realm_id: string }>) {
|
|
await this.pool.query("update qbo_connection set realm_id = $2 where environment = $1", [row.environment, encrypt(row.realm_id, this.key)]);
|
|
}
|
|
return r.rows.length;
|
|
}
|
|
|
|
private toConn(row: Record<string, unknown>): Connection {
|
|
return {
|
|
environment: row.environment as Env,
|
|
realmId: this.readRealm(row.realm_id as string),
|
|
accessToken: decrypt(row.access_token_enc as string, this.key),
|
|
refreshToken: decrypt(row.refresh_token_enc as string, this.key),
|
|
accessExpiresAt: row.access_expires_at as Date,
|
|
refreshExpiresAt: row.refresh_expires_at as Date,
|
|
authorizedAt: row.authorized_at as Date,
|
|
refreshedAt: row.refreshed_at as Date,
|
|
status: row.status as Connection["status"],
|
|
};
|
|
}
|
|
|
|
async read(env: Env): Promise<Connection | null> {
|
|
const r = await this.pool.query("select * from qbo_connection where environment = $1", [env]);
|
|
return r.rows[0] ? this.toConn(r.rows[0]) : null;
|
|
}
|
|
|
|
async withLock<T>(env: Env, fn: (c: LockedConn) => Promise<T>): Promise<T> {
|
|
return withTx(this.pool, async (client) => {
|
|
await client.query("select pg_advisory_xact_lock(hashtext($1))", [`qbo_connection:${env}`]);
|
|
const r = await client.query("select * from qbo_connection where environment = $1 for update", [env]);
|
|
const current = r.rows[0] ? this.toConn(r.rows[0]) : null;
|
|
return fn({
|
|
get: () => current,
|
|
save: async (c) => {
|
|
await client.query(
|
|
`insert into qbo_connection (environment, realm_id, access_token_enc, refresh_token_enc, access_expires_at, refresh_expires_at, authorized_at, refreshed_at, status)
|
|
values ($1,$2,$3,$4,$5,$6,$7,$8,$9)
|
|
on conflict (environment) do update set realm_id = excluded.realm_id, access_token_enc = excluded.access_token_enc,
|
|
refresh_token_enc = excluded.refresh_token_enc, access_expires_at = excluded.access_expires_at,
|
|
refresh_expires_at = excluded.refresh_expires_at, authorized_at = excluded.authorized_at,
|
|
refreshed_at = excluded.refreshed_at, status = excluded.status`,
|
|
[c.environment, encrypt(c.realmId, this.key), encrypt(c.accessToken, this.key), encrypt(c.refreshToken, this.key), c.accessExpiresAt, c.refreshExpiresAt, c.authorizedAt, c.refreshedAt, c.status],
|
|
);
|
|
},
|
|
remove: async () => {
|
|
await client.query("delete from qbo_connection where environment = $1", [env]);
|
|
},
|
|
});
|
|
});
|
|
}
|
|
}
|
|
|
|
/** Хранилище в памяти (тесты). */
|
|
export class MemoryStore implements Store {
|
|
states = new Map<string, { env: Env; at: number }>();
|
|
conns = new Map<Env, Connection>();
|
|
now = () => Date.now();
|
|
async saveState(state: string, env: Env) {
|
|
this.states.set(state, { env, at: this.now() });
|
|
}
|
|
async consumeState(state: string) {
|
|
const s = this.states.get(state);
|
|
this.states.delete(state);
|
|
return s && this.now() - s.at < 10 * 60_000 ? s.env : null;
|
|
}
|
|
async read(env: Env) {
|
|
return this.conns.get(env) ?? null;
|
|
}
|
|
async withLock<T>(env: Env, fn: (c: LockedConn) => Promise<T>) {
|
|
return fn({
|
|
get: () => this.conns.get(env) ?? null,
|
|
save: async (c) => {
|
|
this.conns.set(env, c);
|
|
},
|
|
remove: async () => {
|
|
this.conns.delete(env);
|
|
},
|
|
});
|
|
}
|
|
}
|