@rebasepro/server-postgres 0.10.1-canary.31c773c → 0.10.1-canary.6f89f77

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  import { NodePgDatabase } from "drizzle-orm/node-postgres";
2
2
  import type { RebasePgTable } from "../types";
3
- import { UserRepository, TokenRepository, MfaRepository, AuthRepository, UserData, CreateUserData, RoleData, CreateRoleData, RefreshTokenInfo, PasswordResetTokenInfo, MagicLinkTokenInfo, UserIdentityData, ListUsersOptions, PaginatedUsersResult, MfaFactor, MfaChallengeInfo, RoleData as Role } from "@rebasepro/server";
3
+ import { UserRepository, TokenRepository, MfaRepository, AuthRepository, UserData, CreateUserData, RoleData, CreateRoleData, RefreshTokenInfo, RefreshTokenSession, PasswordResetTokenInfo, MagicLinkTokenInfo, UserIdentityData, ListUsersOptions, PaginatedUsersResult, MfaFactor, MfaChallengeInfo, RoleData as Role } from "@rebasepro/server";
4
4
  export type { Role };
5
5
  export interface AuthSchemaTables {
6
6
  users: RebasePgTable;
@@ -90,9 +90,38 @@ export declare class UserService implements UserRepository {
90
90
  export declare class RefreshTokenService {
91
91
  private db;
92
92
  private refreshTokensTable;
93
+ private usersTable;
93
94
  constructor(db: NodePgDatabase, tableOrTables?: RebasePgTable | Partial<AuthSchemaTables>);
94
- createToken(uid: string, tokenHash: string, expiresAt: Date, userAgent?: string, ipAddress?: string): Promise<void>;
95
+ /**
96
+ * Whether the table actually carries a column, so a host application that
97
+ * supplied its own `refresh_tokens` table — one that predates session
98
+ * grouping — degrades instead of throwing on every sign-in.
99
+ */
100
+ private has;
101
+ private col;
102
+ /** The columns to read back, narrowed to the ones this table has. */
103
+ private selection;
104
+ createToken(uid: string, tokenHash: string, expiresAt: Date, userAgent?: string, ipAddress?: string, session?: RefreshTokenSession): Promise<void>;
95
105
  findByHash(tokenHash: string): Promise<RefreshTokenInfo | null>;
106
+ /**
107
+ * Record that a token was rotated away, keeping the row.
108
+ *
109
+ * The row is what lets `/auth/refresh` distinguish "you already used this,
110
+ * here is a fresh one" from "no idea what this is". Deleting it — which is
111
+ * what this used to do — collapsed both into a 401 and signed the user out
112
+ * for the crime of losing a response.
113
+ */
114
+ markRotated(tokenHash: string): Promise<void>;
115
+ /** Final kill of one sign-in: logout, or revoking a device remotely. */
116
+ revokeSession(sessionId: string): Promise<void>;
117
+ /**
118
+ * Housekeeping: rotation would otherwise leave a row per refresh forever.
119
+ * Superseded rows are only needed for as long as a straggler might still
120
+ * present them, and expired ones are dead weight everywhere.
121
+ */
122
+ prune(uid: string, sessionId: string, supersededBefore: Date): Promise<void>;
123
+ getTokensValidAfter(uid: string): Promise<Date | null>;
124
+ setTokensValidAfter(uid: string, at: Date): Promise<void>;
96
125
  deleteByHash(tokenHash: string): Promise<void>;
97
126
  deleteAllForUser(uid: string): Promise<void>;
98
127
  listForUser(uid: string): Promise<RefreshTokenInfo[]>;
@@ -153,7 +182,12 @@ export declare class PostgresTokenRepository implements TokenRepository {
153
182
  private passwordResetTokenService;
154
183
  private magicLinkTokenService;
155
184
  constructor(db: NodePgDatabase, tableOrTables?: RebasePgTable | Partial<AuthSchemaTables>);
156
- createRefreshToken(uid: string, tokenHash: string, expiresAt: Date, userAgent?: string, ipAddress?: string): Promise<void>;
185
+ createRefreshToken(uid: string, tokenHash: string, expiresAt: Date, userAgent?: string, ipAddress?: string, session?: RefreshTokenSession): Promise<void>;
186
+ markRefreshTokenRotated(tokenHash: string): Promise<void>;
187
+ revokeRefreshTokenSession(sessionId: string): Promise<void>;
188
+ pruneRefreshTokens(uid: string, sessionId: string, supersededBefore: Date): Promise<void>;
189
+ getTokensValidAfter(uid: string): Promise<Date | null>;
190
+ setTokensValidAfter(uid: string, at: Date): Promise<void>;
157
191
  findRefreshTokenByHash(tokenHash: string): Promise<RefreshTokenInfo | null>;
158
192
  deleteRefreshToken(tokenHash: string): Promise<void>;
159
193
  deleteAllRefreshTokensForUser(uid: string): Promise<void>;
@@ -205,7 +239,12 @@ export declare class PostgresAuthRepository implements AuthRepository {
205
239
  createRole(_data: CreateRoleData): Promise<RoleData>;
206
240
  updateRole(id: string, data: Partial<Omit<RoleData, "id">>): Promise<RoleData | null>;
207
241
  deleteRole(_id: string): Promise<void>;
208
- createRefreshToken(uid: string, tokenHash: string, expiresAt: Date, userAgent?: string, ipAddress?: string): Promise<void>;
242
+ createRefreshToken(uid: string, tokenHash: string, expiresAt: Date, userAgent?: string, ipAddress?: string, session?: RefreshTokenSession): Promise<void>;
243
+ markRefreshTokenRotated(tokenHash: string): Promise<void>;
244
+ revokeRefreshTokenSession(sessionId: string): Promise<void>;
245
+ pruneRefreshTokens(uid: string, sessionId: string, supersededBefore: Date): Promise<void>;
246
+ getTokensValidAfter(uid: string): Promise<Date | null>;
247
+ setTokensValidAfter(uid: string, at: Date): Promise<void>;
209
248
  findRefreshTokenByHash(tokenHash: string): Promise<RefreshTokenInfo | null>;
210
249
  deleteRefreshToken(tokenHash: string): Promise<void>;
211
250
  deleteAllRefreshTokensForUser(uid: string): Promise<void>;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Replay a `pg_dumpall --globals-only` script one statement at a time,
3
+ * tolerating per-statement failures. On a same-cluster restore the roles
4
+ * usually already exist (`CREATE ROLE` → "already exists") and on a managed
5
+ * provider an `ALTER ROLE <superuser>` may be refused; neither should abort
6
+ * recreation of the roles that *are* missing. Returns how many statements
7
+ * applied vs were skipped.
8
+ *
9
+ * `runStatement` executes one SQL statement and rejects on error.
10
+ */
11
+ export declare function applyGlobalsWith(runStatement: (sql: string) => Promise<void>, globalsSql: string, log?: (message: string) => void): Promise<{
12
+ applied: number;
13
+ skipped: number;
14
+ }>;
15
+ /**
16
+ * Delete each pruned dump together with its `.globals.sql` roles sidecar, so
17
+ * pruning never orphans the roles file. The sidecar is best-effort — older
18
+ * backups predate it, so a missing-sidecar failure is swallowed while a
19
+ * failure deleting the dump itself propagates.
20
+ *
21
+ * `deleteObject` removes one key and rejects if it cannot (e.g. not found).
22
+ */
23
+ export declare function pruneWith(keys: string[], deleteObject: (key: string) => Promise<void>): Promise<void>;
@@ -5,8 +5,8 @@ export declare class BackupToolError extends Error {
5
5
  readonly hint?: string | undefined;
6
6
  constructor(message: string, hint?: string | undefined);
7
7
  }
8
- /** Locate `pg_dump` / `pg_restore`, honouring an env override. */
9
- export declare function resolvePgBinary(tool: "pg_dump" | "pg_restore", env?: Record<string, string | undefined>): string | null;
8
+ /** Locate `pg_dump` / `pg_restore` / `pg_dumpall`, honouring an env override. */
9
+ export declare function resolvePgBinary(tool: "pg_dump" | "pg_restore" | "pg_dumpall", env?: Record<string, string | undefined>): string | null;
10
10
  /** Run `<bin> --version` and extract the major version. */
11
11
  export declare function detectToolMajor(bin: string): Promise<number | null>;
12
12
  /** Query the server for its major version via `server_version_num`. */
@@ -27,11 +27,22 @@ export interface BackupResult {
27
27
  localFile: string;
28
28
  fileName: string;
29
29
  sizeBytes: number;
30
+ /**
31
+ * Absolute path of the `.globals.sql` sidecar holding cluster-wide roles
32
+ * (present unless globals capture was disabled or unavailable).
33
+ */
34
+ globalsFile?: string;
35
+ globalsSizeBytes?: number;
30
36
  }
31
37
  /**
32
38
  * Produce a custom-format dump on local disk. When `outDir` is omitted the
33
39
  * file is written to the OS temp directory (used by the upload path, which
34
40
  * cleans it up afterwards).
41
+ *
42
+ * Alongside the `-Fc` dump it writes a `<name>.globals.sql` sidecar via
43
+ * `pg_dumpall --globals-only` so the roles the dump's GRANT/RLS statements
44
+ * depend on can be recreated on restore. Set `includeGlobals: false` to skip
45
+ * it (e.g. when the caller has no privilege to read cluster globals).
35
46
  */
36
47
  export declare function createDump(opts: {
37
48
  connectionString: string;
@@ -41,19 +52,50 @@ export declare function createDump(opts: {
41
52
  excludeSchemas?: string[];
42
53
  noOwner?: boolean;
43
54
  inheritStdio?: boolean;
55
+ includeGlobals?: boolean;
44
56
  env?: Record<string, string | undefined>;
45
57
  }): Promise<BackupResult>;
58
+ /**
59
+ * Cheap integrity check on a freshly written dump: it must be non-empty and
60
+ * `pg_restore --list` must parse its table of contents without error. Used
61
+ * before pruning older backups so a corrupt-but-exit-0 dump never becomes
62
+ * the reason the last good backup is deleted.
63
+ */
64
+ export declare function validateDump(localFile: string, env?: Record<string, string | undefined>): Promise<{
65
+ ok: boolean;
66
+ reason?: string;
67
+ }>;
68
+ /**
69
+ * Replay a `pg_dumpall --globals-only` script to recreate cluster roles
70
+ * before a restore, so the dump's GRANT/RLS statements (which reference
71
+ * `rebase_user` and any owner roles) actually apply. Runs statement by
72
+ * statement and tolerates per-statement failures — on a same-cluster restore
73
+ * the roles usually already exist (`CREATE ROLE` → "already exists"), and on
74
+ * a managed provider an `ALTER ROLE <superuser>` may be refused; neither
75
+ * should abort role recreation. Returns how many statements applied vs were
76
+ * skipped.
77
+ */
78
+ export declare function applyGlobals(connectionString: string, globalsSql: string, log?: (message: string) => void): Promise<{
79
+ applied: number;
80
+ skipped: number;
81
+ }>;
46
82
  /**
47
83
  * Restore a custom-format dump into the database named by
48
84
  * `connectionString`. Destructive when `clean` is set (drops objects
49
85
  * first). Never called automatically — the CLI gates it behind explicit
50
86
  * confirmation.
87
+ *
88
+ * Runs with `--exit-on-error` by default: a restore that logs-and-continues
89
+ * past a failed GRANT (because a role was missing) reports success with RLS
90
+ * un-enforced. Callers should recreate roles first (see {@link applyGlobals})
91
+ * and only set `exitOnError: false` deliberately.
51
92
  */
52
93
  export declare function restoreDump(opts: {
53
94
  connectionString: string;
54
95
  inputFile: string;
55
96
  clean?: boolean;
56
97
  noOwner?: boolean;
98
+ exitOnError?: boolean;
57
99
  inheritStdio?: boolean;
58
100
  env?: Record<string, string | undefined>;
59
101
  }): Promise<void>;
@@ -99,10 +99,50 @@ export declare function buildPgRestoreArgs(opts: {
99
99
  inputFile: string;
100
100
  /** Drop objects before recreating them (destructive but idempotent). */
101
101
  clean?: boolean;
102
- /** Continue past individual errors instead of aborting. */
102
+ /**
103
+ * Abort on the first error instead of logging and continuing. Defaults
104
+ * ON: a restore that silently skips failed GRANT/RLS statements (because
105
+ * a role is missing) "succeeds" with RLS un-enforced — a security hole.
106
+ * Fail loudly instead so the operator knows the restore is incomplete.
107
+ */
103
108
  exitOnError?: boolean;
104
109
  noOwner?: boolean;
105
110
  }): string[];
111
+ /**
112
+ * Assemble the `pg_restore --list` argument vector. Reading a dump's table
113
+ * of contents parses the whole archive without touching a database, so it is
114
+ * a cheap integrity check that the file isn't truncated or corrupt.
115
+ */
116
+ export declare function buildPgRestoreListArgs(inputFile: string): string[];
117
+ /**
118
+ * Assemble the `pg_dumpall --globals-only` argument vector. Roles (and other
119
+ * cluster-wide objects) live outside any single database, so a per-database
120
+ * `pg_dump` omits them. Without the `rebase_user` role the RLS GRANT
121
+ * statements in the main dump fail on restore and RLS is silently lost — so
122
+ * every backup captures the globals into a sidecar `.globals.sql`.
123
+ *
124
+ * `--no-role-passwords` keeps role secrets out of the artifact (backups may
125
+ * be shipped off-box); roles are recreated password-less and re-secured by
126
+ * the operator.
127
+ */
128
+ export declare function buildPgDumpallGlobalsArgs(opts: {
129
+ connectionString: string;
130
+ outFile: string;
131
+ }): string[];
132
+ /**
133
+ * Derive the globals sidecar path/key for a given `.dump` file. Keeps the
134
+ * two artifacts adjacent so listing, uploading and pruning can find one from
135
+ * the other. A name that doesn't end in `.dump` is returned unchanged with a
136
+ * `.globals.sql` suffix appended.
137
+ */
138
+ export declare function globalsFileForDump(dumpPath: string): string;
139
+ /**
140
+ * Split a `pg_dumpall --globals-only` script into individual statements.
141
+ * Used when replaying globals on restore so each `CREATE ROLE` / `GRANT`
142
+ * can run independently and a benign "role already exists" on one doesn't
143
+ * abort the rest. Drops `--` comment lines and blank statements.
144
+ */
145
+ export declare function splitGlobalsStatements(sql: string): string[];
106
146
  /**
107
147
  * Resolve the Postgres connection string the backup commands should use,
108
148
  * mirroring the precedence the branch command already relies on.
@@ -4,4 +4,36 @@ export declare function getTableIncludesFromCollections(collections: CollectionC
4
4
  export declare function getTableIncludes(collectionsPath: string): Promise<string[]>;
5
5
  export declare function getDevDatabaseUrl(databaseUrl: string): string;
6
6
  export declare function ensureDevDatabaseExists(databaseUrl: string, devDatabaseUrl: string): Promise<void>;
7
- export declare function getTableExcludes(databaseUrl: string, collectionsPath: string): Promise<string[]>;
7
+ /**
8
+ * Query the live database for every user table/view outside the system
9
+ * catalogs. Separated from {@link getTableExcludes} so its failure mode can
10
+ * be handled explicitly (fail closed) and so tests can inject a stub.
11
+ */
12
+ export declare function queryExistingTables(databaseUrl: string): Promise<string[]>;
13
+ /**
14
+ * Raised when the exclude list could not be built. `db push` MUST abort on
15
+ * this rather than continue: the exclude list is the only thing shielding
16
+ * non-collection (user/system) tables from the auto-approved declarative
17
+ * apply. A partial list — the old fail-open behaviour — meant a transient
18
+ * introspection hiccup dropped every table not present in `schema.sql`.
19
+ */
20
+ export declare class ExcludeIntrospectionError extends Error {
21
+ readonly cause?: unknown | undefined;
22
+ constructor(message: string, cause?: unknown | undefined);
23
+ }
24
+ /**
25
+ * Build the `--exclude` list that protects tables Rebase doesn't manage from
26
+ * the declarative apply. Anything not backing a collection (or its M2M
27
+ * junctions) is excluded so Atlas never drops it.
28
+ *
29
+ * Fails **closed**: if the database can't be introspected we cannot know
30
+ * which tables to protect, so we throw {@link ExcludeIntrospectionError}
31
+ * instead of returning a near-empty list and letting the caller drop
32
+ * everything.
33
+ *
34
+ * `deps` is injectable for tests; production uses the real pg-backed queries.
35
+ */
36
+ export declare function getTableExcludes(databaseUrl: string, collectionsPath: string, deps?: {
37
+ queryExistingTables?: (databaseUrl: string) => Promise<string[]>;
38
+ getIncludes?: (collectionsPath: string) => Promise<string[]>;
39
+ }): Promise<string[]>;