@agentlogin/rp-store-postgres 0.0.0-stage → 0.2.0-beta.2

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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,115 @@
1
- # Temporary Holding Version
1
+ # PostgreSQL RP callback store
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `@agentlogin/rp-store-postgres` implements `CallbackStateStore` from `@agentlogin/rp` for applications running on
4
+ several hosts. Login can start on one replica and return to another; concurrent callbacks compete for one durable
5
+ claim before either can exchange the authorization code. PostgreSQL 17 is exercised by the integration suite.
6
+
7
+ This is separate from the issuer's `@agentlogin/store-postgres`. The callback table contains only opaque HMAC
8
+ state digests, expiry times and consumption flags. Pending cookies, PKCE verifiers, authorization codes, issuer
9
+ records, application accounts and application sessions are not stored here. The
10
+ [Hono example](../../examples/rp-hono/README.md) demonstrates separate PostgreSQL account and session tables, using
11
+ the same bounded connection pool while keeping callback and session lifecycles independent.
12
+
13
+ ```ts
14
+ import { createHandlers, RelyingParty } from '@agentlogin/rp';
15
+ import { PostgresCallbackStateStore } from '@agentlogin/rp-store-postgres';
16
+
17
+ const callbackStore = new PostgresCallbackStateStore({
18
+ connectionString: process.env.RP_DATABASE_URL!,
19
+ schema: 'agentlogin_rp', // Optional; this is the default.
20
+ });
21
+ await callbackStore.verifySchema(); // Migrate separately before serving requests.
22
+ const rp = new RelyingParty({
23
+ clientId: 'https://app.example/client-metadata.json',
24
+ redirectUri: 'https://app.example/auth/agent/callback',
25
+ issuers: ['https://issuer.example'],
26
+ stateSecret: process.env.STATE_SECRET!, // Stable and shared by every application replica.
27
+ });
28
+ const auth = createHandlers(rp, { callbackStore, onSignIn });
29
+ // Wire auth.login and auth.callback to your framework; onSignIn creates your application session.
30
+ // Periodically await callbackStore.cleanup(1000).
31
+ // Drain requests and maintenance jobs, then await callbackStore.close() at shutdown.
32
+ ```
33
+
34
+ ## Setup and connection ownership
35
+
36
+ The installed package provides `agentlogin-rp-migrate`; in this repository run `npm run rp:migrate`. Both require
37
+ `RP_DATABASE_URL` and accept `RP_DATABASE_SCHEMA` (default `agentlogin_rp`). Run migrations with a deployment role;
38
+ normal application startup calls `verifySchema()` and ordinary operations perform no DDL. The programmatic
39
+ equivalent for migration tooling is `await callbackStore.migrate()`.
40
+
41
+ Schema names are lowercase SQL identifiers of at most 63 characters and cannot begin with `pg_`. Migrations are
42
+ transactional and use a migration-only advisory lock; request operations do not take that lock.
43
+
44
+ Use a dedicated schema and a runtime role limited to the schema usage, table DML, metadata reads and clock
45
+ function execution it needs. Keep schema creation and alteration privileges with the migration role. Verify the
46
+ schema before exposing the application to traffic, and do not change it underneath a running incompatible version.
47
+
48
+ Supply exactly one of `connectionString` or an externally configured `pg.Pool` as `pool`. An external pool is
49
+ useful for custom authenticated TLS, observability and connection policy; its caller owns and closes it. The
50
+ adapter closes only pools it creates. Its own pool defaults to ten connections; budget the sum of replica pools
51
+ against PostgreSQL's connection limit. External pools need bounded acquisition and connection timeouts too.
52
+ Use the authoritative primary, not a read replica or cache, for every callback operation.
53
+
54
+ Defaults are five seconds for connection acquisition and lock waits, ten seconds per statement and thirty seconds
55
+ for idle transactions. Configure them through `connectionTimeoutMs`, `lockTimeoutMs`, `statementTimeoutMs` and
56
+ `idleTransactionTimeoutMs`; `maxConnections` sets the owned pool's size. External pools retain their own connection
57
+ settings. `onPoolError` can report idle connection failures; redact driver errors before logging them.
58
+
59
+ ## Registration, claims and time
60
+
61
+ `register(key, expiresAt)` accepts the opaque digest supplied by the RP handlers and an absolute Unix timestamp in
62
+ milliseconds. It inserts only if the key is absent; `false` means an existing record was preserved, whether used,
63
+ unused or expired but not yet cleaned up. Reusing a key never renews its stored expiry or resets its consumption.
64
+
65
+ `claim(key)` returns `claimed` to one request, `duplicate` for a live consumed record, or `missing` when absent or
66
+ expired. It acquires the table lock needed for a write and locks that callback row, reads the database clock after
67
+ those waits, and changes an unused live row to used in the same transaction. The table lock is compatible with
68
+ ordinary readers and writers; other keys can proceed independently. No network request to an issuer or
69
+ application callback runs while that transaction is open.
70
+
71
+ The adapter uses `READ COMMITTED` with an explicit row lock and one checked-out connection per transaction, as
72
+ described by [PostgreSQL row locking](https://www.postgresql.org/docs/17/explicit-locking.html#LOCKING-ROWS) and
73
+ [node-postgres transactions](https://node-postgres.com/features/transactions). Expiry uses a SQL wrapper around
74
+ [`clock_timestamp()`](https://www.postgresql.org/docs/17/functions-datetime.html#FUNCTIONS-DATETIME-CURRENT),
75
+ which advances during a transaction. A timestamp captured before a lock wait cannot authorize a late claim.
76
+
77
+ The RP handlers choose the pending cookie's expiry using the application's clock; the database enforces the
78
+ registered deadline with its clock. Keep both synchronized and monitor clock drift. The test suite changes the
79
+ clock function only inside disposable schemas; production requests cannot supply a replacement clock.
80
+
81
+ ## Failures and retention
82
+
83
+ The adapter does not automatically retry operations. Errors fail closed: the handlers return `state_store_failed`
84
+ without exchanging a code. An uncertain commit discards the connection; it never turns a later reread of
85
+ `used` into proof that this request won. After an uncertain claim or token exchange, start a new sign-in. Never
86
+ release a claim after token validation or session creation fails.
87
+
88
+ Call `cleanup(limit)` from controlled maintenance, with a default batch of 1,000 and a maximum of 10,000 rows.
89
+ Cleanup uses the expiry index and skips locked records; it deletes only expired records and does not make expiry
90
+ effective. Overlapping jobs are safe, but avoid scheduling more database work than your deployment needs. Monitor
91
+ retained rows and increase maintenance frequency when sign-in volume outgrows the deletion rate. Never evict live
92
+ records to reclaim space.
93
+
94
+ Acknowledged claims must survive failover. Configure PostgreSQL durability and replication to preserve them before
95
+ another primary serves callbacks; this adapter cannot repair a database rollback. Restoring older data can restore
96
+ an unused state whose code was already exchanged. Before serving traffic after a restore or any failover that
97
+ might lose acknowledged claims, rotate `stateSecret` across every replica and reject cookies using the old secret.
98
+ Do not keep the old secret as a decryption fallback. This ends pending sign-ins; it does not replace application
99
+ session recovery. Protect database access, backups and TLS credentials, and do not log pending cookies or secrets.
100
+
101
+ ## Protocol boundary and tests
102
+
103
+ [Core Section 5.7](https://github.com/agentlogin/spec/blob/main/agent-login-core.md#57-id-token-validation) requires
104
+ response and session/issuer validation before state consumption and keeps state consumed after a failed or
105
+ uncertain exchange. It recommends atomic coordination across serving instances; this adapter provides that
106
+ coordination for the existing handlers. The store does not replace their PKCE, nonce or issuer checks. Those
107
+ checks follow [RFC 9700](https://www.rfc-editor.org/rfc/rfc9700.html#section-2.1) and
108
+ [RFC 9207 Section 2.4](https://www.rfc-editor.org/rfc/rfc9207.html#section-2.4).
109
+
110
+ Run `npm test` for the repository suite or `npm run test:postgres` for both PostgreSQL packages. Database tests use
111
+ the explicit `AGENTLOGIN_TEST_POSTGRES_URL`, isolate their schemas, and skip when it is absent. Set
112
+ `REQUIRE_POSTGRES_TESTS=1` to fail on missing configuration, as CI does. Concurrency and failure tests provide
113
+ correctness evidence; they do not establish deployment capacity. Load testing, application session policy,
114
+ rate limiting and operational recovery remain application responsibilities. The Hono example supplies shared
115
+ session storage; other applications may integrate their existing session system.
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ // Keep the entry point available before workspace TypeScript compilation.
3
+ import '../dist/migrate.js';
@@ -0,0 +1 @@
1
+ export { PostgresCallbackStateStore, UncertainCommitError, type PostgresCallbackStateStoreOptions, type CallbackStoreCheckpoint, } from './postgres-callback-store.js';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { PostgresCallbackStateStore, UncertainCommitError, } from './postgres-callback-store.js';
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,0BAA0B,EAC1B,oBAAoB,GAGrB,MAAM,8BAA8B,CAAC"}
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,45 @@
1
+ #!/usr/bin/env node
2
+ import { PostgresCallbackStateStore } from './postgres-callback-store.js';
3
+ if (process.argv.includes('--help') || process.argv.includes('-h')) {
4
+ console.log(`agentlogin-rp-migrate - install the Agent Login RP callback schema
5
+
6
+ Usage: RP_DATABASE_URL=postgresql://... agentlogin-rp-migrate
7
+
8
+ Environment:
9
+ RP_DATABASE_URL Required connection string for a DDL-capable migration role
10
+ RP_DATABASE_SCHEMA Schema name (default: agentlogin_rp)
11
+
12
+ Applications verify the installed schema at startup; callback requests never migrate it.`);
13
+ }
14
+ else if (!process.env.RP_DATABASE_URL) {
15
+ console.error('RP_DATABASE_URL is required to migrate RP callback storage. RP_DATABASE_SCHEMA defaults to agentlogin_rp.');
16
+ process.exitCode = 1;
17
+ }
18
+ else {
19
+ let store;
20
+ try {
21
+ store = new PostgresCallbackStateStore({
22
+ connectionString: process.env.RP_DATABASE_URL,
23
+ schema: process.env.RP_DATABASE_SCHEMA,
24
+ maxConnections: 1,
25
+ });
26
+ await store.migrate();
27
+ await store.verifySchema();
28
+ console.log(`RP callback PostgreSQL schema ${store.schema} is ready.`);
29
+ }
30
+ catch (error) {
31
+ const code = error && typeof error === 'object' && 'code' in error && typeof error.code === 'string' && /^[A-Z0-9_]+$/.test(error.code) ? error.code : undefined;
32
+ console.error('RP callback migration failed. Check connectivity, DDL privileges, and RP_DATABASE_SCHEMA configuration.', { code });
33
+ process.exitCode = 1;
34
+ }
35
+ finally {
36
+ try {
37
+ await store?.close();
38
+ }
39
+ catch {
40
+ console.error('Unable to close the migration connection pool.');
41
+ process.exitCode = 1;
42
+ }
43
+ }
44
+ }
45
+ //# sourceMappingURL=migrate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migrate.js","sourceRoot":"","sources":["../src/migrate.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAE1E,IAAI,OAAO,CAAC,IAAI,CA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AC;QAC7B,MAAM,CAAC;YAAC,OAAO,CAAC,KAAK,CAAC,gDAAgD,CAAC,CAAC;YAAC,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;QAAC,CAAC;IAClG,CAAC;AACH,CAAC"}
@@ -0,0 +1,60 @@
1
+ import type { CallbackClaim, CallbackStateStore } from '@agentlogin/rp';
2
+ import { Pool, type PoolClient } from 'pg';
3
+ type Operation = 'register' | 'claim' | 'cleanup' | 'migrate' | 'verifySchema';
4
+ export interface CallbackStoreCheckpoint {
5
+ operation: Operation;
6
+ phase: 'after-lock' | 'before-commit' | 'after-commit';
7
+ client: PoolClient;
8
+ }
9
+ export interface PostgresCallbackStateStoreOptions {
10
+ /** Supply exactly one connection source, connected to the authoritative primary. */
11
+ connectionString?: string;
12
+ /** Externally managed pool: its owner controls pool limits and connection acquisition timeouts. */
13
+ pool?: Pool;
14
+ schema?: string;
15
+ maxConnections?: number;
16
+ connectionTimeoutMs?: number;
17
+ statementTimeoutMs?: number;
18
+ lockTimeoutMs?: number;
19
+ idleTransactionTimeoutMs?: number;
20
+ /** Fault injection / scheduling only. Never log query values or perform application work here. */
21
+ onCheckpoint?: (event: CallbackStoreCheckpoint) => Promise<void> | void;
22
+ /** Optional reporting for idle pool errors. Raw driver errors may contain sensitive data. */
23
+ onPoolError?: (error: Error) => void;
24
+ }
25
+ /** The callback must fail closed. A second attempt cannot establish ownership of an earlier claim. */
26
+ export declare class UncertainCommitError extends Error {
27
+ readonly operation: Operation;
28
+ constructor(operation: Operation, cause: unknown);
29
+ }
30
+ /**
31
+ * Durable one-use callbacks shared across RP instances. Each operation uses one connection and one transaction.
32
+ * No application, network, or token exchange work belongs inside these transactions. Claims are never released.
33
+ */
34
+ export declare class PostgresCallbackStateStore implements CallbackStateStore {
35
+ readonly schema: string;
36
+ private readonly pool;
37
+ private readonly ownedPool;
38
+ private readonly statementTimeoutMs;
39
+ private readonly lockTimeoutMs;
40
+ private readonly idleTransactionTimeoutMs;
41
+ private readonly hook?;
42
+ private readonly poolErrorHandler;
43
+ private closed;
44
+ constructor(options: PostgresCallbackStateStoreOptions);
45
+ private name;
46
+ private checkpoint;
47
+ private now;
48
+ private transaction;
49
+ register(key: string, expiresAt: number): Promise<boolean>;
50
+ claim(key: string): Promise<CallbackClaim>;
51
+ /** Remove only expired rows in a bounded indexed batch. Schedule separately from login and callback requests. */
52
+ cleanup(limit?: number): Promise<number>;
53
+ /** Deployment operation using a DDL-capable role; ordinary requests never create database objects. */
54
+ migrate(): Promise<void>;
55
+ /** Startup check: requires schema usage, function execute, callback-table DML and migration-version SELECT. */
56
+ verifySchema(): Promise<void>;
57
+ /** Drain application requests before closing. An external pool retains its owner-controlled lifecycle. */
58
+ close(): Promise<void>;
59
+ }
60
+ export {};
@@ -0,0 +1,249 @@
1
+ import { Pool } from 'pg';
2
+ /** The callback must fail closed. A second attempt cannot establish ownership of an earlier claim. */
3
+ export class UncertainCommitError extends Error {
4
+ operation;
5
+ constructor(operation, cause) {
6
+ super(`The commit outcome for ${operation} is uncertain; abandon this sign-in instead of repeating the operation`, { cause });
7
+ this.name = 'UncertainCommitError';
8
+ this.operation = operation;
9
+ }
10
+ }
11
+ const SCHEMA_VERSION = 1;
12
+ const MAX_KEY_BYTES = 1024;
13
+ const MAX_SAFE_TIME = Number.MAX_SAFE_INTEGER;
14
+ const quote = (identifier) => `"${identifier}"`;
15
+ function integer(value, fallback, name, max = 2_147_483_647) {
16
+ const actual = value ?? fallback;
17
+ if (!Number.isSafeInteger(actual) || actual < 1 || actual > max)
18
+ throw new RangeError(`${name} must be an integer from 1 to ${max}`);
19
+ return actual;
20
+ }
21
+ function validateKey(key) {
22
+ if (typeof key !== 'string' || key.length === 0 || key.includes('\0') || Buffer.byteLength(key, 'utf8') > MAX_KEY_BYTES) {
23
+ throw new TypeError('Callback state key must be nonempty UTF-8 text of at most 1024 bytes, without NUL');
24
+ }
25
+ }
26
+ function sqlState(error) {
27
+ return error && typeof error === 'object' && 'code' in error && typeof error.code === 'string' ? error.code : undefined;
28
+ }
29
+ /**
30
+ * Durable one-use callbacks shared across RP instances. Each operation uses one connection and one transaction.
31
+ * No application, network, or token exchange work belongs inside these transactions. Claims are never released.
32
+ */
33
+ export class PostgresCallbackStateStore {
34
+ schema;
35
+ pool;
36
+ ownedPool;
37
+ statementTimeoutMs;
38
+ lockTimeoutMs;
39
+ idleTransactionTimeoutMs;
40
+ hook;
41
+ poolErrorHandler;
42
+ closed = false;
43
+ constructor(options) {
44
+ if (!options || (!!options.pool === (options.connectionString !== undefined))) {
45
+ throw new TypeError('Supply exactly one of pool or connectionString');
46
+ }
47
+ if (options.connectionString !== undefined && (typeof options.connectionString !== 'string' || options.connectionString.trim() === '')) {
48
+ throw new TypeError('connectionString must be nonempty');
49
+ }
50
+ this.schema = options.schema ?? 'agentlogin_rp';
51
+ if (typeof this.schema !== 'string' || !/^[a-z_][a-z0-9_]{0,62}$/.test(this.schema) || this.schema.startsWith('pg_')) {
52
+ throw new TypeError('PostgreSQL schema must be a lowercase SQL identifier of at most 63 characters, outside pg_*');
53
+ }
54
+ this.statementTimeoutMs = integer(options.statementTimeoutMs, 10_000, 'statementTimeoutMs');
55
+ this.lockTimeoutMs = integer(options.lockTimeoutMs, 5_000, 'lockTimeoutMs');
56
+ this.idleTransactionTimeoutMs = integer(options.idleTransactionTimeoutMs, 30_000, 'idleTransactionTimeoutMs');
57
+ const max = integer(options.maxConnections, 10, 'maxConnections', 1000);
58
+ const connectionTimeoutMillis = integer(options.connectionTimeoutMs, 5_000, 'connectionTimeoutMs');
59
+ this.ownedPool = !options.pool;
60
+ this.pool = options.pool ?? new Pool({ connectionString: options.connectionString, max, connectionTimeoutMillis, idleTimeoutMillis: 30_000 });
61
+ this.hook = options.onCheckpoint;
62
+ this.poolErrorHandler = (error) => { options.onPoolError?.(error); };
63
+ this.pool.on('error', this.poolErrorHandler);
64
+ }
65
+ name(name) {
66
+ return `${quote(this.schema)}.${quote(name)}`;
67
+ }
68
+ async checkpoint(client, operation, phase) {
69
+ await this.hook?.({ client, operation, phase });
70
+ }
71
+ async now(client) {
72
+ const result = await client.query(`SELECT ${this.name('app_now_ms')}() AS now`);
73
+ const raw = result.rows[0]?.now;
74
+ const now = raw === null || raw === undefined ? NaN : Number(raw);
75
+ if (!Number.isSafeInteger(now) || now < 0)
76
+ throw new Error('app_now_ms() must return a nonnegative safe integer Unix time in milliseconds');
77
+ return now;
78
+ }
79
+ async transaction(operation, action, readOnly = false) {
80
+ if (this.closed)
81
+ throw new Error('PostgreSQL callback store is closed');
82
+ const client = await this.pool.connect();
83
+ let committing = false;
84
+ let committed = false;
85
+ let discard = false;
86
+ let connectionError;
87
+ // pg-pool handles idle connections only. A checked-out client emits errors independently of query rejection.
88
+ const onClientError = (error) => { connectionError = error; discard = true; };
89
+ client.on('error', onClientError);
90
+ try {
91
+ await client.query(`BEGIN ISOLATION LEVEL READ COMMITTED ${readOnly ? 'READ ONLY' : 'READ WRITE'}`);
92
+ await client.query(`SELECT
93
+ set_config('statement_timeout', $1, true),
94
+ set_config('lock_timeout', $2, true),
95
+ set_config('idle_in_transaction_session_timeout', $3, true),
96
+ set_config('search_path', 'pg_catalog', true),
97
+ set_config('synchronous_commit', 'on', true)`, [
98
+ String(this.statementTimeoutMs), String(this.lockTimeoutMs), String(this.idleTransactionTimeoutMs),
99
+ ]);
100
+ const result = await action(client);
101
+ await this.checkpoint(client, operation, 'before-commit');
102
+ if (connectionError)
103
+ throw connectionError;
104
+ committing = true;
105
+ const commit = await client.query('COMMIT');
106
+ if (commit.command !== 'COMMIT') {
107
+ committing = false;
108
+ throw new Error('PostgreSQL rolled back the callback transaction instead of committing');
109
+ }
110
+ committed = true;
111
+ await this.checkpoint(client, operation, 'after-commit');
112
+ if (connectionError)
113
+ throw connectionError;
114
+ return result;
115
+ }
116
+ catch (error) {
117
+ // Never replay a mutation whose commit may have reached PostgreSQL. In particular, used=true is not proof
118
+ // that this caller won. A hook after COMMIT models a lost acknowledgement after a durable claim.
119
+ if (committed || committing) {
120
+ discard = true;
121
+ throw new UncertainCommitError(operation, error);
122
+ }
123
+ try {
124
+ await client.query('ROLLBACK');
125
+ }
126
+ catch {
127
+ discard = true;
128
+ }
129
+ throw error;
130
+ }
131
+ finally {
132
+ try {
133
+ client.release(discard);
134
+ }
135
+ finally {
136
+ client.removeListener('error', onClientError);
137
+ }
138
+ }
139
+ }
140
+ async register(key, expiresAt) {
141
+ validateKey(key);
142
+ if (!Number.isSafeInteger(expiresAt) || expiresAt <= 0)
143
+ throw new TypeError('Callback expiry must be a positive safe integer Unix time in milliseconds');
144
+ return this.transaction('register', async (client) => {
145
+ const inserted = await client.query(`INSERT INTO ${this.name('callback_states')} (key, expires_at) VALUES ($1, $2) ON CONFLICT (key) DO NOTHING`, [key, expiresAt]);
146
+ await this.checkpoint(client, 'register', 'after-lock');
147
+ // Uniqueness checks can wait on another transaction. An expiry sampled before that wait is insufficient.
148
+ if (expiresAt <= await this.now(client))
149
+ throw new Error('Callback state registration has expired');
150
+ return inserted.rowCount === 1;
151
+ });
152
+ }
153
+ async claim(key) {
154
+ validateKey(key);
155
+ return this.transaction('claim', async (client) => {
156
+ // Acquire the UPDATE's table lock before sampling time. It is compatible with other ordinary readers and
157
+ // writers, but prevents a later lock upgrade waiting behind maintenance after the expiry decision.
158
+ await client.query(`LOCK TABLE ${this.name('callback_states')} IN ROW EXCLUSIVE MODE`);
159
+ // Do not put expiry in this predicate: a lock-only blocker can outlast expiry without changing the row.
160
+ const found = await client.query(`SELECT expires_at, used FROM ${this.name('callback_states')} WHERE key = $1 FOR UPDATE`, [key]);
161
+ await this.checkpoint(client, 'claim', 'after-lock');
162
+ const now = await this.now(client);
163
+ const row = found.rows[0];
164
+ if (!row || Number(row.expires_at) <= now)
165
+ return 'missing';
166
+ if (row.used)
167
+ return 'duplicate';
168
+ await client.query(`UPDATE ${this.name('callback_states')} SET used = true WHERE key = $1`, [key]);
169
+ return 'claimed';
170
+ });
171
+ }
172
+ /** Remove only expired rows in a bounded indexed batch. Schedule separately from login and callback requests. */
173
+ async cleanup(limit = 1000) {
174
+ if (typeof limit !== 'number')
175
+ throw new TypeError('cleanup limit must be a number');
176
+ integer(limit, 1000, 'cleanup limit', 10_000);
177
+ return this.transaction('cleanup', async (client) => {
178
+ const now = await this.now(client);
179
+ const selected = await client.query(`SELECT key FROM ${this.name('callback_states')} WHERE expires_at <= $1
180
+ ORDER BY expires_at, key LIMIT $2 FOR UPDATE SKIP LOCKED`, [now, limit]);
181
+ await this.checkpoint(client, 'cleanup', 'after-lock');
182
+ if (!selected.rows.length)
183
+ return 0;
184
+ const deleted = await client.query(`DELETE FROM ${this.name('callback_states')} WHERE key = ANY($1::text[]) AND expires_at <= $2`, [selected.rows.map((row) => row.key), await this.now(client)]);
185
+ return deleted.rowCount ?? 0;
186
+ });
187
+ }
188
+ /** Deployment operation using a DDL-capable role; ordinary requests never create database objects. */
189
+ async migrate() {
190
+ await this.transaction('migrate', async (client) => {
191
+ await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1, 0))', [`agentlogin-rp-store-postgres:${this.schema}`]);
192
+ await this.checkpoint(client, 'migrate', 'after-lock');
193
+ await client.query(`CREATE SCHEMA IF NOT EXISTS ${quote(this.schema)}`);
194
+ await client.query(`CREATE TABLE IF NOT EXISTS ${this.name('schema_migrations')} (
195
+ version integer PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT clock_timestamp()
196
+ )`);
197
+ const found = await client.query(`SELECT version FROM ${this.name('schema_migrations')} ORDER BY version DESC LIMIT 1`);
198
+ const version = found.rows[0]?.version ?? 0;
199
+ if (version === SCHEMA_VERSION)
200
+ return;
201
+ if (version !== 0)
202
+ throw new Error('PostgreSQL callback schema version is not supported by this adapter');
203
+ await client.query(`
204
+ CREATE FUNCTION ${this.name('app_now_ms')}() RETURNS bigint LANGUAGE sql VOLATILE
205
+ SET search_path = pg_catalog
206
+ AS 'SELECT floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint';
207
+ CREATE TABLE ${this.name('callback_states')} (
208
+ key text PRIMARY KEY CHECK (octet_length(key) BETWEEN 1 AND ${MAX_KEY_BYTES}),
209
+ expires_at bigint NOT NULL CHECK (expires_at BETWEEN 1 AND ${MAX_SAFE_TIME}),
210
+ used boolean NOT NULL DEFAULT false
211
+ );
212
+ CREATE INDEX callback_states_expiry ON ${this.name('callback_states')} (expires_at, key);
213
+ INSERT INTO ${this.name('schema_migrations')} (version) VALUES (${SCHEMA_VERSION});
214
+ `);
215
+ });
216
+ }
217
+ /** Startup check: requires schema usage, function execute, callback-table DML and migration-version SELECT. */
218
+ async verifySchema() {
219
+ try {
220
+ await this.transaction('verifySchema', async (client) => {
221
+ const found = await client.query(`SELECT version FROM ${this.name('schema_migrations')} ORDER BY version DESC LIMIT 1`);
222
+ if (found.rows[0]?.version !== SCHEMA_VERSION)
223
+ throw new Error('PostgreSQL callback schema version is not supported by this adapter');
224
+ await client.query(`SELECT key, expires_at, used FROM ${this.name('callback_states')} LIMIT 0`);
225
+ await this.now(client);
226
+ }, true);
227
+ }
228
+ catch (error) {
229
+ if (['42P01', '3F000', '42883'].includes(sqlState(error) ?? '')) {
230
+ throw new Error('PostgreSQL callback schema is not initialized. Run agentlogin-rp-migrate before serving callbacks.', { cause: error });
231
+ }
232
+ throw error;
233
+ }
234
+ }
235
+ /** Drain application requests before closing. An external pool retains its owner-controlled lifecycle. */
236
+ async close() {
237
+ if (this.closed)
238
+ return;
239
+ this.closed = true;
240
+ try {
241
+ if (this.ownedPool)
242
+ await this.pool.end();
243
+ }
244
+ finally {
245
+ this.pool.removeListener('error', this.poolErrorHandler);
246
+ }
247
+ }
248
+ }
249
+ //# sourceMappingURL=postgres-callback-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres-callback-store.js","sourceRoot":"","sources":["../src/postgres-callback-store.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAmB,MAAM,IAAI,CAAC;AA2B3C,sGAAsG;AACtG,MAAM,OAAO,oBAAqB,SAAQ,KAA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,CAAC;YACD,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;IAED,0GAA0G;IAC1G,KAAK,CAAC,KAAK;QACT,IAAI,IAAI,CAAC,MAAM;YAAE,OAAO;QACxB,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;QACnB,IAAI,CAAC;YAAC,IAAI,IAAI,CAAC,SAAS;gBAAE,MAAM,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC;QAAC,CAAC;gBAC1C,CAAC;YAAC,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,OAAO,EAAE,IAAI,CAAC,gBAAgB,CAAC,CAAC;QAAC,CAAC;IACvE,CAAC;CACF"}
package/package.json CHANGED
@@ -1,6 +1,44 @@
1
1
  {
2
2
  "name": "@agentlogin/rp-store-postgres",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0-beta.2",
4
+ "description": "Shared PostgreSQL callback state for Agent Login relying parties",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "main": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": "./dist/index.js"
11
+ },
12
+ "bin": {
13
+ "agentlogin-rp-migrate": "bin/agentlogin-rp-migrate.js"
14
+ },
15
+ "files": [
16
+ "bin",
17
+ "dist",
18
+ "README.md",
19
+ "LICENSE"
20
+ ],
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/agentlogin/reference.git",
24
+ "directory": "packages/rp-store-postgres"
25
+ },
26
+ "dependencies": {
27
+ "@agentlogin/rp": "0.2.0-beta.2",
28
+ "pg": "^8.16.3"
29
+ },
30
+ "devDependencies": {
31
+ "@types/pg": "^8.23.1"
32
+ },
33
+ "scripts": {
34
+ "prepack": "tsc -b"
35
+ },
36
+ "engines": {
37
+ "node": ">=22.13"
38
+ },
39
+ "publishConfig": {
40
+ "access": "public",
41
+ "tag": "beta",
42
+ "registry": "https://registry.npmjs.org/"
43
+ }
44
+ }