@agentlogin/issuer 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.
Files changed (58) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +237 -2
  3. package/dist/agents.d.ts +40 -0
  4. package/dist/agents.js +257 -0
  5. package/dist/agents.js.map +1 -0
  6. package/dist/app.d.ts +3 -0
  7. package/dist/app.js +652 -0
  8. package/dist/app.js.map +1 -0
  9. package/dist/clients.d.ts +20 -0
  10. package/dist/clients.js +272 -0
  11. package/dist/clients.js.map +1 -0
  12. package/dist/constants.d.ts +30 -0
  13. package/dist/constants.js +32 -0
  14. package/dist/constants.js.map +1 -0
  15. package/dist/context.d.ts +37 -0
  16. package/dist/context.js +2 -0
  17. package/dist/context.js.map +1 -0
  18. package/dist/errors.d.ts +10 -0
  19. package/dist/errors.js +17 -0
  20. package/dist/errors.js.map +1 -0
  21. package/dist/index.d.ts +45 -0
  22. package/dist/index.js +107 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/owner-address.d.ts +2 -0
  25. package/dist/owner-address.js +24 -0
  26. package/dist/owner-address.js.map +1 -0
  27. package/dist/safefetch.d.ts +38 -0
  28. package/dist/safefetch.js +164 -0
  29. package/dist/safefetch.js.map +1 -0
  30. package/dist/server.d.ts +1 -0
  31. package/dist/server.js +89 -0
  32. package/dist/server.js.map +1 -0
  33. package/dist/signing-configuration.d.ts +14 -0
  34. package/dist/signing-configuration.js +35 -0
  35. package/dist/signing-configuration.js.map +1 -0
  36. package/dist/signing-state.d.ts +22 -0
  37. package/dist/signing-state.js +14 -0
  38. package/dist/signing-state.js.map +1 -0
  39. package/dist/sqlite-store.d.ts +24 -0
  40. package/dist/sqlite-store.js +81 -0
  41. package/dist/sqlite-store.js.map +1 -0
  42. package/dist/state.d.ts +30 -0
  43. package/dist/state.js +77 -0
  44. package/dist/state.js.map +1 -0
  45. package/dist/store.d.ts +693 -0
  46. package/dist/store.js +883 -0
  47. package/dist/store.js.map +1 -0
  48. package/dist/tokens.d.ts +37 -0
  49. package/dist/tokens.js +167 -0
  50. package/dist/tokens.js.map +1 -0
  51. package/dist/transactions.d.ts +90 -0
  52. package/dist/transactions.js +449 -0
  53. package/dist/transactions.js.map +1 -0
  54. package/dist/util.d.ts +29 -0
  55. package/dist/util.js +113 -0
  56. package/dist/util.js.map +1 -0
  57. package/package.json +37 -4
  58. package/static/wait.js +42 -0
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,238 @@
1
- # Temporary Holding Version
1
+ # @agentlogin/issuer
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
+ Reference issuer for the pinned [Agent Login Core draft](https://github.com/agentlogin/spec): an OpenID Provider that
4
+ signs software agents in with keys they hold. Written against the specification section by section so that the code
5
+ reads as a second description of the protocol; Hono for HTTP and jose for JOSE behind a `Store` interface.
6
+ The production storage target is [`@agentlogin/store-postgres`](../store-postgres/README.md), with normalized
7
+ records and atomic operations across instances. Memory and SQLite remain local reference/test adapters.
8
+ Requires Node.js 22.13 or newer.
9
+
10
+ Selected draft 0.2 requirements are implemented; the [compatibility status](../../docs/draft-0.2-status.md) pins the
11
+ target specification and records remaining gaps. `max_age` is parsed and stored with the transaction. A positive
12
+ value limits authentication age at code authorization, redemption and token issuance, including database waits;
13
+ stale completion ends `denied/login_required`, and a stale Token Request gets `invalid_grant`. Owner approval and
14
+ retries preserve the original accepted assertion time. Zero requires a fresh assertion for that transaction and
15
+ allows delayed approval/delivery within the ordinary transaction and code lifetimes. Nonempty wire values must
16
+ contain decimal digits only; an empty optional value is omitted per RFC 6749. Values larger than the safe timestamp
17
+ range act as an unlimited age bound within that range.
18
+
19
+ The stored age fields are additive and need no PostgreSQL schema migration. Stop old issuer processes before
20
+ upgrading: mixed versions can lose the new checks. Records created without an age constraint retain their previous
21
+ behavior. Custom `Store` adapters must implement the new atomic freshness checks even though the method signatures
22
+ are unchanged; run the shared store contract tests when upgrading an adapter.
23
+
24
+ ```bash
25
+ npm run issuer # http://localhost:3000, handle domain localhost, prints a generated ADMIN_TOKEN
26
+ DATABASE_URL=postgresql://... npm run issuer:migrate
27
+ DATABASE_URL=postgresql://... ISSUER=https://issuer.example HANDLE_DOMAINS=example.com,*.agents.example ADMIN_TOKEN=... SIGNING_JWK='{...}' npm run issuer
28
+ ```
29
+
30
+ Endpoints (spec section in brackets): `/.well-known/openid-configuration` and `/.well-known/jwks.json` (2.4, 7.7),
31
+ `/.well-known/webfinger` for served handles (2.2), `/authorize` GET and POST (5.1–5.3), `/transactions/{id}` with
32
+ `/assertion`, `/review`, `/continue/{secret}` and the `/wait` page (6), `/token` and `/userinfo` (5.6, 3.3),
33
+ `/register` (RFC 7591 with the admin token as initial access token, 4.3), `/agents/{handle}/...` management (7.2, 7.8),
34
+ `/owner/transactions/{id}` and `/decision` (6.6, API form).
35
+
36
+ Owner sign-in by email (7.5; how an Owner authenticates is outside the wire protocol): `POST /owner/sessions/email
37
+ {email}` sends a one-time code through the `sendOwnerCode` option of `createIssuer` (the standalone server prints it
38
+ in development mode; without the option the endpoint answers `501`), and `POST /owner/sessions/email/verify
39
+ {email, code}` returns an Owner Credential. That credential comes from a one-time code alone, so it manages the
40
+ Owner's Agents but neither approves a transaction nor grants `share_owner` (6.6, 7.8).
41
+
42
+ A registration stating `relay_issuer` (4.4) is accepted only when every redirect URI is on that host and the Relay's
43
+ metadata can be fetched under the protections of 2.2; its `op_policy_uri`, as of registration, is what the approval
44
+ view shows.
45
+
46
+ Bootstrap, outside the specification: `POST /admin/owners {email, name, verified_via, session_auth}` returns an Owner
47
+ Credential; `POST /admin/agents {handle, owner_id, name}`; `POST /admin/credentials {owner_id, kind: "delegated",
48
+ handle}` or `{owner_id, kind: "owner", session_auth}`; `PATCH /admin/agents/{handle} {enabled}` (Section 7.4 effects);
49
+ `DELETE /admin/agents/{handle}` (deletes the Agent with its keys, Consent Records, Accounts and Delegated Credentials;
50
+ the Section 7.6 count is retained). `session_auth` states how the session that obtained an Owner Credential
51
+ authenticated the Owner: `passkey`, `oidc`, `domain`, `email_factor` or `email_only`. Only the first four approve a
52
+ transaction or grant `share_owner` (Sections 6.6, 7.8); a caller that omits it gets `email_only`, and a stored
53
+ credential with no recorded session does not qualify either. `owner_verified_via` records a method supplied by the trusted operator (7.5); these historical labels are not assurance levels. The bootstrap markers do not themselves authenticate a human. All with `Authorization: Bearer ADMIN_TOKEN`.
54
+
55
+ Status: passes the automated probes in `@agentlogin/conformance` (`npm test`); the report keeps evidence gaps,
56
+ including unverified entropy generation, explicit. Not yet implemented: Ed25519 agent keys,
57
+ `private_key_jwt`, rate limits (6.7), Owner authentication by passkey, OIDC or domain (credentials from such sessions
58
+ are issued by the bootstrap API on the operator's word) and the HTML pages for Owner sign-in and approval,
59
+ Relay profile (8), the `pairwise` subject type. Development mode (`INSECURE_DEV=1`, or an
60
+ `http` issuer) permits loopback clients and private addresses in metadata fetches; never run it that way in production.
61
+
62
+ Concurrency and persistence: every guarantee spanning records is a single `Store` operation. A database adapter
63
+ must commit the full transition, including its preconditions and effects, in one database transaction:
64
+
65
+ | Operation | Atomic guarantee |
66
+ | --- | --- |
67
+ | `putAgent` | Insert only when the handle is absent; an existing identity is never overwritten |
68
+ | `resolveManagement`, `readManagementKeys`, `readManagementAccounts` | Read the credential, immutable Agent identity and protected resources in one snapshot; reject stale authorization |
69
+ | `insertKey` | The credential, Owner and immutable Agent subject still match the authorization; enforce Agent-scoped pending uniqueness and revocation history |
70
+ | `activateKey`, `patchKey`, `revokeKey` | Match the exact enrollment; activation rechecks the proof window and claims global active-key exclusivity; explicit revocation also denies open transactions, removes bearer hashes from all matching transactions (including terminal ones), and invalidates codes and tokens |
71
+ | `updateTransaction` | Recheck a supplied transaction bearer before version/terminal checks; compare the open version, check subject identity, disable versions, transaction/assertion expiry and consent reliance, and commit cap admission, reservation and consent effects together |
72
+ | `completeTransaction` | Recheck a supplied transaction bearer before version/terminal checks; check the ready version, subject, expiry and reservation; complete, issue the code, update the Account and signup count, and release the reservation together |
73
+ | `setAgentEnabled`, `setAccountStatus` | Check the authorized Agent identity, increment the persistent disable version, and invalidate dependent records together |
74
+ | `deleteAgent`, `revokeAllKeys` | Check the immutable identity and apply all cleanup in the same transaction |
75
+ | `redeemCode`, `insertAccessToken` | Redeem once; validate lifecycle fences, and refuse token insertion for replayed codes |
76
+
77
+ `readTransaction` computes effective lifecycle/expiry state and retention without writing. Polling does not determine
78
+ whether a reservation counts or a credential remains valid. `currentTime` supplies the adapter's authoritative clock:
79
+ memory and SQLite use the supplied application clock, while PostgreSQL uses the database clock. Mutations recheck
80
+ expiry and the verified assertion window at acceptance. ID-token `iat` and `exp` come from the persisted access-token
81
+ issuance bounds, including when lock contention moves the database's issuance time past the application's timestamp.
82
+ A first assertion arriving at its original transaction deadline throws `TransactionExpiredError` without persisting
83
+ identity, a token, an extended Owner-approval deadline, consent, or quota. This check precedes the signed assertion's
84
+ window check. A first assertion also rechecks its key and enabled Agent identity/version, throwing
85
+ `AssertionSubjectError` (`unknown_key` or `key_revoked`) without consuming the challenge if authority changed.
86
+ Account denial remains an accepted assertion gate. First assertions also compare `expectedShareOwner` with the
87
+ current permission; a conflict has no effects and the handler recomputes Owner approval for the same verified
88
+ enrollment. Explicit revocation removes transaction bearer authority without changing existing terminal outcomes
89
+ or retention; natural key expiry preserves that bearer until retention ends. Review and completion pass the identified
90
+ bearer's hash to the atomic store operation, which throws `TransactionTokenError` if that authority was revoked.
91
+
92
+ Agent subjects never change or transfer to a replacement at the same handle. Keys remember the authorizing subject;
93
+ transactions, codes and access tokens retain that subject, their key enrollment, and Agent/Account disable versions.
94
+ Management authorization resolves the credential and Agent together. Protected reads validate that authorization
95
+ with the returned records; protocol key mutations revalidate the credential, session permissions and Agent identity
96
+ inside the write. A delegated request cannot acquire a replacement Agent's identity after its credential was deleted.
97
+ The optional authorization arguments of `patchKey` and `revokeKey` are mandatory for protocol callers; omission is
98
+ reserved for trusted internal lifecycle operations. Custom adapters must implement the three management snapshot
99
+ methods and honor these mutation preconditions; the stored format does not change.
100
+ Unproved pending enrollments are scoped to the Agent: an attacker knowing only a public key cannot reserve it
101
+ against another Agent. Only successful proof activation claims the one active enrollment for that key across the
102
+ issuer. Conflicting valid proofs fail with `400 invalid_request`; other enrollments remain untouched. Store callers
103
+ should use `getKey(kid, handle)`; an unscoped lookup returns an active or sole record and refuses ambiguous pending keys.
104
+ Pending timeout cleanup uses `deleteKey(kid, enrollment, pendingExpiredAt)`, which atomically requires the same
105
+ enrollment to remain pending and expired. A stale reader cannot delete a key that another request activated.
106
+ Disable versions increase even if an Agent or Account is subsequently enabled. Delayed work cannot become valid again
107
+ simply because the current enabled flag is true. Reservation helpers are private to the state machine: a losing
108
+ assertion cannot release the winning assertion's place. Consent changes commit with their transition, so delayed
109
+ cleanup cannot write to a replacement Agent. Previously granted scopes carry forward only while the redirect host,
110
+ client name, terms URI and policy URI remain unchanged; accepting changed terms replaces the scope set. Invalidation
111
+ preserves an expired transaction's original terminal time and never restarts its retention window.
112
+
113
+ Use PostgreSQL for multi-instance deployments; see its package README for schema migration, connection pools,
114
+ locking and recovery requirements. The following adapters are retained for local reference and testing.
115
+
116
+ `MemoryStore` implements these operations synchronously within one process. `SQLiteStore` runs that same state machine
117
+ inside `BEGIN IMMEDIATE`/`COMMIT` for mutations, with WAL and `synchronous=FULL`; reads use `BEGIN` and never update the
118
+ snapshot or acquire the writer lock. It uses Node’s built-in `node:sqlite` module (experimental in Node 22). Every
119
+ operation loads the complete fresh snapshot, and mutations serialize it back; no cached state or JavaScript lock
120
+ determines cross-process ownership. A failed commit rolls
121
+ back the whole operation. Tests exercise separate database connections, independent writer processes, persistence
122
+ across reopen, injected database write failures, and adversarial HTTP lifecycle schedules against both adapters.
123
+ SQLite has a known deadline limitation: it can apply a caller timestamp captured before waiting for the writer
124
+ lock. It is excluded from the PostgreSQL production hardening target and is not a production storage option.
125
+
126
+ Snapshot format 2 stores scoped key enrollments. Memory and SQLite read version 1 snapshots and convert their
127
+ key map in memory; the next mutation writes version 2. Stop old issuer instances before upgrading, and do not mix
128
+ versions or roll back the binary against a version 2 snapshot. Keep a backup for rollback of the whole deployment;
129
+ restoring it still requires the security-state reconciliation described in the implementation guidance.
130
+
131
+ ```ts
132
+ import { createIssuer, SQLiteStore } from '@agentlogin/issuer';
133
+ const store = new SQLiteStore('/private/app/issuer.sqlite');
134
+ const { app } = await createIssuer({ issuer, handleDomains, adminToken, signingJwk, store });
135
+ // Drain requests before calling store.close().
136
+ ```
137
+
138
+ For the standalone server, set `DATABASE_PATH` and a persistent `SIGNING_JWK`. All issuer processes sharing the
139
+ database must use the same issuer configuration and signing key. Keep the database and its WAL files in a private
140
+ application directory on a local filesystem; the adapter is for processes on one host, not a network filesystem.
141
+ Back up a live database using SQLite's backup facilities, not by copying only the main file while WAL is active.
142
+ The adapter deliberately serializes mutations and rewrites the full snapshot. Reads still parse the full snapshot,
143
+ and synchronous SQLite calls block the Node event loop. It is a durable, auditable reference adapter, not a
144
+ high-throughput database design. Large deployments need normalized/indexed storage,
145
+ retention cleanup, capacity planning and operational testing while preserving this transaction contract.
146
+
147
+ Migration: the `Store` API and stored records have changed. Custom adapters must implement `currentTime`, read-only
148
+ `readTransaction`, the new atomic operations, assertion/proof-window and consent-context checks, persisted token issuance timestamps
149
+ the optional transaction-bearer checks and branded assertion-subject and transaction-expiry/token errors, and identity/version fields; do not run old and new issuers against the same store. This adapter creates a new schema;
150
+ there is no migration from third-party stores. The RP handler also now requires explicit shared callback storage
151
+ (see `@agentlogin/rp`). These fixes do not implement rate limiting or a production Owner authentication system, so
152
+ passing the tests is not a deployment approval.
153
+
154
+ Transactions now persist `clientPresentation`, a snapshot of only the public client name, logo, legal URLs and
155
+ Relay presentation that was displayed when authorization began. Authentication credentials, signup caps and
156
+ review policy remain on the current Client record. On upgrade, issuer startup cancels open transactions that
157
+ lack this snapshot with `access_denied`; users must start a new sign-in. It never backfills acceptance from
158
+ current metadata. Cancellation reads batches of at most 256 through `listLegacyTransactions`, uses the existing
159
+ atomic transition to release reservations, preserves effective expiry, and fixes terminal retention once. Custom
160
+ adapters must implement that filtered, bounded read and preserve `clientPresentation` on every transition.
161
+ PostgreSQL schema v3 includes its partial index; MemoryStore indexes legacy IDs and SQLite retains its documented
162
+ whole-snapshot storage behavior. Drain old issuer processes before upgrading; mixed versions are unsupported.
163
+
164
+ ### Signing-key lifecycle
165
+
166
+ An issuer database now owns the active signing-key identity and the public-key
167
+ history. Private keys remain in the process's configured key ring. Every replica
168
+ reads shared authority before signing and rechecks withdrawal before delivery;
169
+ a replica missing the active private key fails closed.
170
+
171
+ `createIssuer({ signingJwks: [privateJwk, ...], jwksCacheSeconds: 3600 })` publishes
172
+ the supplied ES256 keys. Only an empty database selects the first key as its
173
+ bootstrap key. Adding a key to an existing database stages it without selecting
174
+ it. Use the returned `publishSigningKeys`, `activateSigningKey` and
175
+ `removeSigningKey` methods for lifecycle changes. Activation requires publication
176
+ to precede it on the authoritative database clock. Deploy the new private material
177
+ to every replica, verify the public JWKS, and then activate it.
178
+
179
+ Ordinary retirement is refused while a key is active or its issued-token lifetime
180
+ plus the longest JWKS cache lifetime has not elapsed. PostgreSQL reserves a
181
+ conservative extra minute when recording issuance to avoid a write for every
182
+ signature. `removeSigningKey(kid, true)` immediately withdraws a suspected
183
+ compromised key. Removed keys cannot be republished. Existing cached JWKS readers
184
+ may still trust a removed key until their cache expires; withdrawal is not an
185
+ instantaneous revocation of every relying-party session.
186
+
187
+ When upgrading a snapshot or PostgreSQL schema that predates signing history,
188
+ stop and drain every older issuer before migration, and include every previously
189
+ published key needed by outstanding tokens in the first configured upgrade ring.
190
+ The adapter cannot reconstruct those public keys from tokens or private keys that
191
+ were not supplied. Unknown issuance and cache history receives a fixed conservative
192
+ 87,000-second overlap (Core T_TOKEN 600 plus maximum T_CACHE 86,400), even if the
193
+ new JWKS cache setting is zero. SQLite starts this deadline at the first successful
194
+ publication after upgrade; PostgreSQL fixes it at migration, after the old issuers
195
+ have stopped. The pending SQLite guard survives unrelated writes and restarts.
196
+ Publication transfers the guard atomically to the initial ring; later restarts and
197
+ publication never renew it. If a legacy key continues signing, each new signing
198
+ reservation preserves the maximum historical cache bound after that token expires;
199
+ only new issuance can extend the floor. This conservative behavior stays with that
200
+ legacy key until retirement. New installations and subsequently added keys keep
201
+ normal retirement timing. Compromised-key withdrawal still takes effect immediately.
202
+ This automatic bound covers Core-conforming historical lifetimes; deployments
203
+ that previously exceeded them must retain the prior keys for their longer overlap.
204
+
205
+ The standalone server also accepts `SIGNING_KEYS_FILE`, mutually exclusive with
206
+ `SIGNING_JWK`. Its JSON object has `keys` (private JWK array), and optional
207
+ `activateKid`, `retireKids`, and `compromisedKids`. Identifiers are SHA-256 JWK
208
+ thumbprints. Removed keys must be absent from `keys`. Atomically replace the file
209
+ and send `SIGHUP` to reload. The complete file is validated before changes begin.
210
+ Publication, activation and removal are separate durable operations: if activation
211
+ or retirement is premature, publication remains staged and the existing active
212
+ key remains selected. Emergency removal is never reversed by a later failure.
213
+ Publish a new key in one reload and activate it in a subsequent reload.
214
+
215
+ ### Owner deletion and quota inheritance
216
+
217
+ `ownerDeletionRetentionSeconds` is a fixed non-negative integer, defaulting to
218
+ zero; the standalone variable is `OWNER_DELETION_RETENTION_SECONDS`. Metadata
219
+ publishes `op_policy_uri`, defaulting to the issuer's `/policy` document. A custom
220
+ `policyUri` / `OP_POLICY_URI` must describe the same configured period.
221
+
222
+ Trusted Owner integrations call `store.putOwner(owner, now)` after verified
223
+ address changes and `store.deleteOwner(id, ownerSub, now, retentionSeconds)` for
224
+ deletions. The latter must receive the configured published retention period.
225
+ Deletion invalidates dependent authority atomically. Counts are inherited only
226
+ while the deleted Owner's fixed deadline remains live; policy changes never move
227
+ that deadline. Zero ends inheritance immediately. Use fresh immutable Owner IDs
228
+ and subjects; deleted identities cannot be reused.
229
+
230
+ Quota membership records identify individual Account-creation events, including a new creation after Account deletion,
231
+ so repeated verification or address changes do not double-count an account.
232
+ Live Owners sharing a verified address share completed counts and pending
233
+ capacity. Moving an address preserves the Owner's existing counts and inherits
234
+ eligible history at the new address. Email identity preserves the parsed local
235
+ part exactly and compares lower-case A-label domains; no provider alias folding
236
+ is performed. These address links are personal data. PostgreSQL `cleanup()`
237
+ removes expired deleted-Owner links in bounded batches, while preserving copied
238
+ history still belonging to a live Owner. Schedule that cleanup regularly.
@@ -0,0 +1,40 @@
1
+ import type { IssuerContext } from './context.js';
2
+ import { type Agent, type AgentKey, type Credential, type ManagementAuthorization, type P256Jwk } from './store.js';
3
+ /** Section 7.2: strict public-key validation. */
4
+ export declare function validateP256Jwk(jwk: unknown): Promise<P256Jwk>;
5
+ export declare const getLiveKey: (ctx: IssuerContext, kid: string, handle: string, authorization?: ManagementAuthorization) => Promise<AgentKey | undefined>;
6
+ export declare function listLiveKeys(ctx: IssuerContext, handle: string, authorization?: ManagementAuthorization): Promise<AgentKey[]>;
7
+ export declare function keyRecord(ctx: IssuerContext, k: AgentKey): Record<string, unknown>;
8
+ /** Section 7.2: create a pending key. */
9
+ export declare function enrollKey(ctx: IssuerContext, handle: string, body: unknown, authorization: ManagementAuthorization, enrollmentId?: string, challengeExpiresAt?: number): Promise<{
10
+ record: Record<string, unknown>;
11
+ challenge: string;
12
+ proof_url: string;
13
+ enrollmentId: string;
14
+ }>;
15
+ /** Section 7.2: verify the enrollment proof and activate the key. */
16
+ export declare function proveKey(ctx: IssuerContext, handle: string, kid: string, body: unknown): Promise<Record<string, unknown>>;
17
+ /** Section 7.3: revocation and all its effects are one enrollment-conditional store transaction. */
18
+ export declare function revokeKeyEffects(ctx: IssuerContext, key: Pick<AgentKey, 'kid' | 'enrollment'>, authorization: ManagementAuthorization): Promise<void>;
19
+ /** Section 7.3: a stale bulk request can affect only the immutable Agent identity it authorized. */
20
+ export declare function revokeAllKeys(ctx: IssuerContext, handle: string, cred: ManagementAuthorization): Promise<void>;
21
+ /** Section 7.4: status, invalidation fence and dependent records change in one store transaction. */
22
+ export declare function setAccountStatus(ctx: IssuerContext, handle: string, clientId: string, status: 'enabled' | 'disabled', authorization: ManagementAuthorization): Promise<Record<string, unknown>>;
23
+ export declare function setAgentEnabled(ctx: IssuerContext, agent: Agent, enabled: boolean): Promise<Agent | undefined>;
24
+ /** Deletion and the removal of dependent records are atomic; a replacement cannot be swept by stale cleanup. */
25
+ export declare function deleteAgent(ctx: IssuerContext, agent: Agent): Promise<void>;
26
+ /**
27
+ * Sections 6.6 and 7.8: only an Owner Credential from a session that authenticated the Owner by `passkey`, `oidc`,
28
+ * `domain`, or `email` plus a factor the Agent cannot read approves a transaction or grants `share_owner`. An allow-list:
29
+ * a credential whose session is not recorded, or was established by a one-time code or link alone, does not qualify.
30
+ */
31
+ export declare const approvalSession: (cred: Credential) => boolean;
32
+ export declare function accountRecord(a: {
33
+ clientId: string;
34
+ status: string;
35
+ firstSignedInAt: number;
36
+ lastSignedInAt: number;
37
+ signInCount: number;
38
+ }): Record<string, unknown>;
39
+ /** Section 7.8: resolves the credential and checks that the handle belongs to its Owner. */
40
+ export declare function authorizeManagement(ctx: IssuerContext, authorization: string | undefined, handle: string, delegable: boolean): Promise<ManagementAuthorization>;