Сервис qbo_auth: OAuth-токены QuickBooks Online (callback services/api/qbo/callback), исследование и предложение quickbooks_bookkeeper (п.84)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
119
packages/qbo_auth/src/store.ts
Normal file
119
packages/qbo_auth/src/store.ts
Normal file
@@ -0,0 +1,119 @@
|
||||
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>;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
private toConn(row: Record<string, unknown>): Connection {
|
||||
return {
|
||||
environment: row.environment as Env,
|
||||
realmId: 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, c.realmId, encrypt(c.accessToken, this.key), encrypt(c.refreshToken, this.key), c.accessExpiresAt, c.refreshExpiresAt, c.authorizedAt, c.refreshedAt, c.status],
|
||||
);
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Хранилище в памяти (тесты). */
|
||||
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);
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user