@softistx/janus-oauth-mongo 0.0.0-stage → 0.18.5

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 (104) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +262 -2
  3. package/dist/authorization-collections.d.ts +43 -0
  4. package/dist/authorization-collections.d.ts.map +1 -0
  5. package/dist/clients-collection.d.ts +29 -0
  6. package/dist/clients-collection.d.ts.map +1 -0
  7. package/dist/collection-fields.d.ts +23 -0
  8. package/dist/collection-fields.d.ts.map +1 -0
  9. package/dist/collections.d.ts +211 -0
  10. package/dist/collections.d.ts.map +1 -0
  11. package/dist/details-field.d.ts +25 -0
  12. package/dist/details-field.d.ts.map +1 -0
  13. package/dist/device-collection.d.ts +28 -0
  14. package/dist/device-collection.d.ts.map +1 -0
  15. package/dist/dpop-replay-collection.d.ts +13 -0
  16. package/dist/dpop-replay-collection.d.ts.map +1 -0
  17. package/dist/dpop-replay.d.ts +27 -0
  18. package/dist/dpop-replay.d.ts.map +1 -0
  19. package/dist/grants-collection.d.ts +17 -0
  20. package/dist/grants-collection.d.ts.map +1 -0
  21. package/dist/index.d.ts +16 -0
  22. package/dist/index.d.ts.map +1 -0
  23. package/dist/index.js +1671 -0
  24. package/dist/index.js.map +52 -0
  25. package/dist/partitioned.d.ts +97 -0
  26. package/dist/partitioned.d.ts.map +1 -0
  27. package/dist/purge.d.ts +124 -0
  28. package/dist/purge.d.ts.map +1 -0
  29. package/dist/record-fields.d.ts +57 -0
  30. package/dist/record-fields.d.ts.map +1 -0
  31. package/dist/records/clients.d.ts +7 -0
  32. package/dist/records/clients.d.ts.map +1 -0
  33. package/dist/records/grants.d.ts +7 -0
  34. package/dist/records/grants.d.ts.map +1 -0
  35. package/dist/records/index.d.ts +5 -0
  36. package/dist/records/index.d.ts.map +1 -0
  37. package/dist/records/requests.d.ts +10 -0
  38. package/dist/records/requests.d.ts.map +1 -0
  39. package/dist/records/tokens.d.ts +10 -0
  40. package/dist/records/tokens.d.ts.map +1 -0
  41. package/dist/records-device.d.ts +7 -0
  42. package/dist/records-device.d.ts.map +1 -0
  43. package/dist/signing-keys/context.d.ts +11 -0
  44. package/dist/signing-keys/context.d.ts.map +1 -0
  45. package/dist/signing-keys/index.d.ts +22 -0
  46. package/dist/signing-keys/index.d.ts.map +1 -0
  47. package/dist/signing-keys/keyring.d.ts +9 -0
  48. package/dist/signing-keys/keyring.d.ts.map +1 -0
  49. package/dist/signing-keys/options.d.ts +15 -0
  50. package/dist/signing-keys/options.d.ts.map +1 -0
  51. package/dist/signing-keys/promote.d.ts +7 -0
  52. package/dist/signing-keys/promote.d.ts.map +1 -0
  53. package/dist/signing-keys/read.d.ts +7 -0
  54. package/dist/signing-keys/read.d.ts.map +1 -0
  55. package/dist/signing-keys/records.d.ts +13 -0
  56. package/dist/signing-keys/records.d.ts.map +1 -0
  57. package/dist/signing-keys/reseal.d.ts +25 -0
  58. package/dist/signing-keys/reseal.d.ts.map +1 -0
  59. package/dist/signing-keys/seal.d.ts +19 -0
  60. package/dist/signing-keys/seal.d.ts.map +1 -0
  61. package/dist/signing-keys/write.d.ts +7 -0
  62. package/dist/signing-keys/write.d.ts.map +1 -0
  63. package/dist/signing-keys-collection.d.ts +52 -0
  64. package/dist/signing-keys-collection.d.ts.map +1 -0
  65. package/dist/store/clients.d.ts +7 -0
  66. package/dist/store/clients.d.ts.map +1 -0
  67. package/dist/store/codes.d.ts +7 -0
  68. package/dist/store/codes.d.ts.map +1 -0
  69. package/dist/store/context.d.ts +21 -0
  70. package/dist/store/context.d.ts.map +1 -0
  71. package/dist/store/device.d.ts +7 -0
  72. package/dist/store/device.d.ts.map +1 -0
  73. package/dist/store/grant-reads.d.ts +7 -0
  74. package/dist/store/grant-reads.d.ts.map +1 -0
  75. package/dist/store/grants.d.ts +7 -0
  76. package/dist/store/grants.d.ts.map +1 -0
  77. package/dist/store/index.d.ts +58 -0
  78. package/dist/store/index.d.ts.map +1 -0
  79. package/dist/store/open.d.ts +9 -0
  80. package/dist/store/open.d.ts.map +1 -0
  81. package/dist/store/requests.d.ts +7 -0
  82. package/dist/store/requests.d.ts.map +1 -0
  83. package/dist/store/rotate.d.ts +6 -0
  84. package/dist/store/rotate.d.ts.map +1 -0
  85. package/dist/store/scope.d.ts +24 -0
  86. package/dist/store/scope.d.ts.map +1 -0
  87. package/dist/store/spend-devices.d.ts +20 -0
  88. package/dist/store/spend-devices.d.ts.map +1 -0
  89. package/dist/store/tokens.d.ts +7 -0
  90. package/dist/store/tokens.d.ts.map +1 -0
  91. package/dist/sync.d.ts +20 -0
  92. package/dist/sync.d.ts.map +1 -0
  93. package/dist/tokens-collections.d.ts +42 -0
  94. package/dist/tokens-collections.d.ts.map +1 -0
  95. package/dist/transaction.d.ts +13 -0
  96. package/dist/transaction.d.ts.map +1 -0
  97. package/dist/translate.d.ts +34 -0
  98. package/dist/translate.d.ts.map +1 -0
  99. package/docs/README.md +13 -0
  100. package/docs/guide/partitions.md +141 -0
  101. package/docs/guide/wiring.md +133 -0
  102. package/docs/roadmap.md +46 -0
  103. package/docs/troubleshooting.md +226 -0
  104. package/package.json +68 -5
@@ -0,0 +1 @@
1
+ {"version":3,"file":"grants.d.ts","sourceRoot":"","sources":["../../src/store/grants.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAIX,UAAU,EACV,MAAM,uBAAuB,CAAC;AAG/B,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAK9C,KAAK,YAAY,GAAG,QAAQ,CAC3B,IAAI,CACH,UAAU,EACR,aAAa,GACb,WAAW,GACX,eAAe,GACf,gBAAgB,GAChB,aAAa,GACb,kBAAkB,GAClB,wBAAwB,GACxB,kBAAkB,GAClB,kBAAkB,GAClB,oBAAoB,GACpB,iBAAiB,CACnB,CACD,CAAC;AA2MF,yGAAyG;AACzG,wBAAgB,UAAU,CAAC,GAAG,EAAE,YAAY,GAAG,YAAY,CAW1D"}
@@ -0,0 +1,58 @@
1
+ import type { OAuthStore } from '@softistx/janus-oauth';
2
+ import type { Db } from 'mongodb';
3
+ export interface MongoOAuthOptions {
4
+ /** Keeps several stores in one database (one per issuer, say). Default: none, the unpartitioned layout. Two partitions never see each other's records. */
5
+ readonly partition?: string;
6
+ }
7
+ /**
8
+ * The `OAuthStore` of `@softistx/janus-oauth`, over one MongoDB database.
9
+ *
10
+ * `{ partition }` keeps several stores in one database, one per issuer (see
11
+ * `createOAuthIssuers`): the same store over the partitioned collections,
12
+ * where every key and every index is scoped by the partition, so a client, a
13
+ * code, a token or a grant of one partition does not exist in another. It is
14
+ * opt-in and a different layout: run `syncMongoOAuthPartitioned(db)`, and
15
+ * `docs/guide/partitions.md` has the migration. Without it the storage is
16
+ * what it always was.
17
+ *
18
+ * ```ts
19
+ * await syncMongoOAuth(db); // a deployment step: creates the indexes
20
+ * const store = createMongoOAuth(db); // an OAuthStore
21
+ * const oauth = createOAuthServer({ auth, store, issuer, resources });
22
+ * ```
23
+ *
24
+ * **Every conditional write is one driver call** on a single document, so
25
+ * the database decides who wins:
26
+ *
27
+ * - `consumeOAuthCode` is one `findOneAndUpdate` filtered on
28
+ * `consumedAt: null` and `expiresAt > now`; the loser reads the document
29
+ * to tell `replayed` from `absent`;
30
+ * - `consumeAuthorizationRequest` is one `findOneAndDelete`;
31
+ * - `decideDeviceAuthorization` and every step of `pollDeviceAuthorization`
32
+ * (approved once, pending, `slow_down`) are one `findOneAndUpdate` on the
33
+ * device code's document, with the server's `now`;
34
+ * - `upsertGrant` is one upsert on the unique `(userId, clientId, resource)`
35
+ * index, and `$setOnInsert` is what keeps an existing grant's `id` and
36
+ * `createdAt`;
37
+ * - `revokeGrant` keeps a first `revokedAt` with a pipeline update and
38
+ * **always sweeps the grant's tokens that are still standing**, so a second
39
+ * call closes the window a racing rotation left.
40
+ *
41
+ * **`rotateRefreshToken` is the one method that writes several documents**,
42
+ * and the port asks it to be all or nothing, so it runs in a transaction:
43
+ * MongoDB must be a replica set or a sharded cluster, as it must be for
44
+ * `@softistx/janus-mongo`'s relation store. A standalone `mongod` rejects it with
45
+ * a `StoreFailure`.
46
+ *
47
+ * The seven collections are opened with `readPreference: 'primary'`: the server
48
+ * re-reads a grant after storing tokens and must see the latest revoke.
49
+ *
50
+ * Reads reach for the driver's `findOne` and answer a lapsed or revoked
51
+ * record as it is stored; an absence is `null`, and everything that rejects is
52
+ * a `StoreFailure`.
53
+ *
54
+ * `deleteExpiredOAuthRecords` is not implemented: TTL indexes drop lapsed
55
+ * records, which is what the port asks of a store with its own expiry.
56
+ */
57
+ export declare function createMongoOAuth(db: Db, options?: MongoOAuthOptions): OAuthStore;
58
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/store/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,SAAS,CAAC;AAWlC,MAAM,WAAW,iBAAiB;IACjC,0JAA0J;IAC1J,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiDG;AACH,wBAAgB,gBAAgB,CAC/B,EAAE,EAAE,EAAE,EACN,OAAO,GAAE,iBAAsB,GAC7B,UAAU,CAkCZ"}
@@ -0,0 +1,9 @@
1
+ import type { Db } from 'mongodb';
2
+ import type { OAuthCollections } from './context';
3
+ /**
4
+ * The seven collections of the default layout, or of the partitioned one. The
5
+ * partitioned documents carry a `partition` field the port's records do not
6
+ * read, so both layouts share the document types.
7
+ */
8
+ export declare function openCollections(db: Db, partitioned: boolean): OAuthCollections;
9
+ //# sourceMappingURL=open.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"open.d.ts","sourceRoot":"","sources":["../../src/store/open.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAc,EAAE,EAAY,MAAM,SAAS,CAAC;AA4BxD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAOlD;;;;GAIG;AACH,wBAAgB,eAAe,CAC9B,EAAE,EAAE,EAAE,EACN,WAAW,EAAE,OAAO,GAClB,gBAAgB,CAiClB"}
@@ -0,0 +1,7 @@
1
+ import type { OAuthStore } from '@softistx/janus-oauth';
2
+ import type { StoreContext } from './context';
3
+ type RequestMethods = Pick<OAuthStore, 'insertAuthorizationRequest' | 'findAuthorizationRequest' | 'consumeAuthorizationRequest'>;
4
+ /** The pending authorization requests. */
5
+ export declare function requestStore({ collections, partition, }: StoreContext): RequestMethods;
6
+ export {};
7
+ //# sourceMappingURL=requests.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"requests.d.ts","sourceRoot":"","sources":["../../src/store/requests.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AAGxD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAG9C,KAAK,cAAc,GAAG,IAAI,CACzB,UAAU,EACR,4BAA4B,GAC5B,0BAA0B,GAC1B,6BAA6B,CAC/B,CAAC;AAEF,0CAA0C;AAC1C,wBAAgB,YAAY,CAAC,EAC5B,WAAW,EACX,SAAS,GACT,EAAE,YAAY,GAAG,cAAc,CAiC/B"}
@@ -0,0 +1,6 @@
1
+ import type { OAuthStore } from '@softistx/janus-oauth';
2
+ import type { Db } from 'mongodb';
3
+ import type { StoreContext } from './context';
4
+ /** The one method that writes several documents, so the one that runs in a transaction. */
5
+ export declare function rotateStore(context: StoreContext, db: Db): Pick<OAuthStore, 'rotateRefreshToken'>;
6
+ //# sourceMappingURL=rotate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rotate.d.ts","sourceRoot":"","sources":["../../src/store/rotate.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAiB,UAAU,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,KAAK,EAAiB,EAAE,EAAE,MAAM,SAAS,CAAC;AAIjD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAK9C,2FAA2F;AAC3F,wBAAgB,WAAW,CAC1B,OAAO,EAAE,YAAY,EACrB,EAAE,EAAE,EAAE,GACJ,IAAI,CAAC,UAAU,EAAE,oBAAoB,CAAC,CASxC"}
@@ -0,0 +1,24 @@
1
+ /**
2
+ * How a partition shows in a document: its `_id`, its `partition` field and
3
+ * the filters on any other field. Pure functions of the partition, which is
4
+ * `null` for the default layout, where every one of them is the identity (the
5
+ * storage is byte for byte what it was before partitions).
6
+ */
7
+ import type { ClientDocument } from '../records';
8
+ export type Partition = string | null;
9
+ /** Any of the six documents: they all have a string `_id`. */
10
+ type Keyed = Pick<ClientDocument, '_id'>;
11
+ /** The `_id` to store or look up for the port's key. */
12
+ export declare function keyOf(partition: Partition, id: string): string;
13
+ /** The port's key behind a stored `_id`. */
14
+ export declare function plainOf(partition: Partition, stored: string): string;
15
+ /** The document to write: keyed, and carrying its partition. */
16
+ export declare function encode<D extends Keyed>(partition: Partition, document: D): D;
17
+ /** The document as the port's converters read it: its `_id` is the port's key. */
18
+ export declare function decode<D extends Keyed>(partition: Partition, document: D): D;
19
+ /** What every filter on a field other than `_id` adds. */
20
+ export declare function where(partition: Partition): {
21
+ partition?: string;
22
+ };
23
+ export {};
24
+ //# sourceMappingURL=scope.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scope.d.ts","sourceRoot":"","sources":["../../src/store/scope.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD,MAAM,MAAM,SAAS,GAAG,MAAM,GAAG,IAAI,CAAC;AAEtC,8DAA8D;AAC9D,KAAK,KAAK,GAAG,IAAI,CAAC,cAAc,EAAE,KAAK,CAAC,CAAC;AAEzC,wDAAwD;AACxD,wBAAgB,KAAK,CAAC,SAAS,EAAE,SAAS,EAAE,EAAE,EAAE,MAAM,GAAG,MAAM,CAE9D;AAED,4CAA4C;AAC5C,wBAAgB,OAAO,CAAC,SAAS,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAYpE;AAED,gEAAgE;AAChE,wBAAgB,MAAM,CAAC,CAAC,SAAS,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,GAAG,CAAC,CAG5E;AAED,kFAAkF;AAClF,wBAAgB,MAAM,CAAC,CAAC,SAAS,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,GAAG,CAAC,CAG5E;AAED,0DAA0D;AAC1D,wBAAgB,KAAK,CAAC,SAAS,EAAE,SAAS,GAAG;IAAE,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,CAElE"}
@@ -0,0 +1,20 @@
1
+ import type { StoreContext } from './context';
2
+ /** Which approvals a revoke spends: a grant's, a user's, a client's or a resource's. */
3
+ export type SpendScope = {
4
+ readonly grantId: string;
5
+ } | {
6
+ readonly userId: string;
7
+ } | {
8
+ readonly clientId: string;
9
+ } | {
10
+ readonly resource: string | Readonly<Record<'$ne', string>>;
11
+ };
12
+ /**
13
+ * Spends the approved, unconsumed device authorizations a revoke covers, at
14
+ * `at`: `status: 'denied'` with `consumedAt` left null, so a later poll
15
+ * answers `denied` (`access_denied`) and revokes nothing. A pending record has
16
+ * no grant yet; a handed-over one is a replay and stays one. `spare` is the
17
+ * `userCodeHash` of the approval that is being given right now.
18
+ */
19
+ export declare function spendDevices({ collections, partition }: StoreContext, scope: SpendScope, spare?: string): Promise<void>;
20
+ //# sourceMappingURL=spend-devices.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"spend-devices.d.ts","sourceRoot":"","sources":["../../src/store/spend-devices.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAG9C,wFAAwF;AACxF,MAAM,MAAM,UAAU,GACnB;IAAE,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GAC5B;IAAE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAC3B;IAAE,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,GAC7B;IAAE,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,QAAQ,CAAC,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC,CAAA;CAAE,CAAC;AAEnE;;;;;;GAMG;AACH,wBAAsB,YAAY,CACjC,EAAE,WAAW,EAAE,SAAS,EAAE,EAAE,YAAY,EACxC,KAAK,EAAE,UAAU,EACjB,KAAK,CAAC,EAAE,MAAM,GACZ,OAAO,CAAC,IAAI,CAAC,CAWf"}
@@ -0,0 +1,7 @@
1
+ import type { OAuthStore } from '@softistx/janus-oauth';
2
+ import type { StoreContext } from './context';
3
+ type TokenMethods = Pick<OAuthStore, 'insertAccessToken' | 'findAccessToken' | 'revokeAccessToken' | 'insertRefreshToken' | 'findRefreshToken' | 'revokeRefreshToken'>;
4
+ /** The access and refresh tokens; the rotation, which spans both, is `rotate.ts`. */
5
+ export declare function tokenStore({ collections, partition, }: StoreContext): TokenMethods;
6
+ export {};
7
+ //# sourceMappingURL=tokens.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tokens.d.ts","sourceRoot":"","sources":["../../src/store/tokens.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AAQxD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAG9C,KAAK,YAAY,GAAG,IAAI,CACvB,UAAU,EACR,mBAAmB,GACnB,iBAAiB,GACjB,mBAAmB,GACnB,oBAAoB,GACpB,kBAAkB,GAClB,oBAAoB,CACtB,CAAC;AAEF,qFAAqF;AACrF,wBAAgB,UAAU,CAAC,EAC1B,WAAW,EACX,SAAS,GACT,EAAE,YAAY,GAAG,YAAY,CAyD7B"}
package/dist/sync.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ import { type SyncOptions, type SyncReport } from '@softistx/mongo';
2
+ import type { Db } from 'mongodb';
3
+ /**
4
+ * Creates the nine collections, their validators and their indexes, and says
5
+ * what it changed. Run it twice and the second run sends nothing.
6
+ *
7
+ * A deployment step, never a request-time one: it needs the `dbAdmin` role.
8
+ * An application that deploys with `@softistx/mongo`'s `syncAll(db)` already
9
+ * syncs them with its own.
10
+ */
11
+ export declare function syncMongoOAuth(db: Db, options?: SyncOptions): Promise<SyncReport[]>;
12
+ /**
13
+ * `syncMongoOAuth` for the partitioned layout (`createMongoOAuth(db, { partition })`):
14
+ * the seven partitioned collections, the signing keys (whose collection is
15
+ * partitioned already) and `oauthDpopReplay` (its keys carry no partition). It leaves the default collections alone, so both
16
+ * layouts can sit in one database while a deployment moves from one to the
17
+ * other (`docs/guide/partitions.md`).
18
+ */
19
+ export declare function syncMongoOAuthPartitioned(db: Db, options?: SyncOptions): Promise<SyncReport[]>;
20
+ //# sourceMappingURL=sync.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sync.d.ts","sourceRoot":"","sources":["../src/sync.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,WAAW,EAChB,KAAK,UAAU,EAEf,MAAM,iBAAiB,CAAC;AACzB,OAAO,KAAK,EAAE,EAAE,EAAE,MAAM,SAAS,CAAC;AAKlC;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAC7B,EAAE,EAAE,EAAE,EACN,OAAO,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,UAAU,EAAE,CAAC,CAEvB;AAED;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CACxC,EAAE,EAAE,EAAE,EACN,OAAO,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,UAAU,EAAE,CAAC,CAMvB"}
@@ -0,0 +1,42 @@
1
+ import { z } from 'zod';
2
+ export declare const oauthAccessTokens: import("@softistx/mongo").CollectionDefinition<import("@softistx/mongo").StampedSchema<{
3
+ nonce: z.ZodOptional<z.ZodString>;
4
+ authTime: z.ZodOptional<z.ZodDate>;
5
+ amr: z.ZodOptional<z.ZodArray<z.ZodString>>;
6
+ acr: z.ZodOptional<z.ZodString>;
7
+ _id: z.ZodString;
8
+ grantId: z.ZodString;
9
+ userId: z.ZodString;
10
+ clientId: z.ZodString;
11
+ resource: z.ZodString;
12
+ scopes: z.ZodArray<z.ZodString>;
13
+ createdAt: z.ZodDate;
14
+ expiresAt: z.ZodDate;
15
+ revokedAt: z.ZodNullable<z.ZodDate>;
16
+ jkt: z.ZodOptional<z.ZodString>;
17
+ authorizationDetails: z.ZodOptional<z.ZodString>;
18
+ actor: z.ZodOptional<z.ZodObject<{
19
+ sub: z.ZodString;
20
+ clientId: z.ZodOptional<z.ZodString>;
21
+ }, z.core.$strip>>;
22
+ }, false, false, false, false>, import("@softistx/mongo").StampNamesOf<false, false, false, false>>;
23
+ export declare const oauthRefreshTokens: import("@softistx/mongo").CollectionDefinition<import("@softistx/mongo").StampedSchema<{
24
+ nonce: z.ZodOptional<z.ZodString>;
25
+ authTime: z.ZodOptional<z.ZodDate>;
26
+ amr: z.ZodOptional<z.ZodArray<z.ZodString>>;
27
+ acr: z.ZodOptional<z.ZodString>;
28
+ _id: z.ZodString;
29
+ grantId: z.ZodString;
30
+ userId: z.ZodString;
31
+ clientId: z.ZodString;
32
+ resource: z.ZodString;
33
+ scopes: z.ZodArray<z.ZodString>;
34
+ createdAt: z.ZodDate;
35
+ expiresAt: z.ZodDate;
36
+ revokedAt: z.ZodNullable<z.ZodDate>;
37
+ jkt: z.ZodOptional<z.ZodString>;
38
+ authorizationDetails: z.ZodOptional<z.ZodString>;
39
+ absoluteExpiresAt: z.ZodDate;
40
+ rotatedAt: z.ZodNullable<z.ZodDate>;
41
+ }, false, false, false, false>, import("@softistx/mongo").StampNamesOf<false, false, false, false>>;
42
+ //# sourceMappingURL=tokens-collections.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tokens-collections.d.ts","sourceRoot":"","sources":["../src/tokens-collections.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AA0BxB,eAAO,MAAM,iBAAiB;;;;;;;;;;;;;;;;;;;;mGAkB5B,CAAC;AAEH,eAAO,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;mGAwB7B,CAAC"}
@@ -0,0 +1,13 @@
1
+ import { type ClientSession, type Db } from 'mongodb';
2
+ /**
3
+ * Runs `body` in a transaction and commits it, running it again when the
4
+ * server labels the failure `TransientTransactionError`, at most
5
+ * `TRANSACTION_ATTEMPTS` times, with a short jittered pause growing with the
6
+ * attempt (an immediate retry meets the same contenders again, and with 8
7
+ * callers one used up its attempts). The commit is inside the same `try`, so
8
+ * a labelled conflict at `commitTransaction` is retried the same way. **Not the driver's `withTransaction`**, which
9
+ * retries for up to 120 seconds: under an outage a request would hang that
10
+ * long before the port heard of the failure.
11
+ */
12
+ export declare function inTransaction<T>(db: Db, body: (session: ClientSession) => Promise<T>): Promise<T>;
13
+ //# sourceMappingURL=transaction.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transaction.d.ts","sourceRoot":"","sources":["../src/transaction.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,aAAa,EAAE,KAAK,EAAE,EAAc,MAAM,SAAS,CAAC;AAgBlE;;;;;;;;;GASG;AACH,wBAAsB,aAAa,CAAC,CAAC,EACpC,EAAE,EAAE,EAAE,EACN,IAAI,EAAE,CAAC,OAAO,EAAE,aAAa,KAAK,OAAO,CAAC,CAAC,CAAC,GAC1C,OAAO,CAAC,CAAC,CAAC,CAkBZ"}
@@ -0,0 +1,34 @@
1
+ import { StoreFailure } from '@softistx/janus';
2
+ /**
3
+ * **The driver's errors, as the port's.** One file, and one default.
4
+ *
5
+ * | What happens | Becomes |
6
+ * | --- | --- |
7
+ * | A duplicate key on `_id` of an insert | nothing — the insert is a retry and writes nothing |
8
+ * | A duplicate key on `_id` or `userCodeHash` of a device authorization insert | **`false`** — the port's "already held", nothing written |
9
+ * | A duplicate key anywhere else | **`StoreFailure`**: an index this adapter never meant to collide on is a bug |
10
+ * | A `$jsonSchema` validation failure (121) | **`StoreFailure`** |
11
+ * | Anything else, absolutely | `StoreFailure`, with the driver error as `cause` |
12
+ *
13
+ * **The default is a failure, not an absence**: nothing here answers `null`,
14
+ * `false`, `0` or `absent` for an error, which is the port's first rule.
15
+ */
16
+ /** Runs one port method, and makes every rejection one the port allows. `prefix` names the port in the message. */
17
+ export declare function run<T>(operation: string, body: () => Promise<T>, prefix?: string): Promise<T>;
18
+ /** The shape of the driver's `E11000`, as far as this file reads it. */
19
+ export interface DuplicateKey {
20
+ readonly code: 11000;
21
+ readonly keyPattern?: Readonly<Record<string, unknown>>;
22
+ }
23
+ export declare function isDuplicateKey(error: unknown): error is DuplicateKey;
24
+ /** The duplicate-key error behind a write, `null` when it landed; any other rejection is rethrown. */
25
+ export declare function duplicateOf(write: Promise<unknown>): Promise<DuplicateKey | null>;
26
+ /** A duplicate on an index the adapter never meant to collide on: a bug, reported as one. */
27
+ export declare function unexpectedDuplicate(operation: string, duplicate: DuplicateKey): StoreFailure;
28
+ /** The duplicate is on `_id`, the key of every collection: the insert is a retry. */
29
+ export declare function onId(duplicate: DuplicateKey): boolean;
30
+ /** The duplicate is on the grant's `(userId, clientId, resource)` index. */
31
+ export declare function onKey(duplicate: DuplicateKey): boolean;
32
+ /** The duplicate is on a key of a device authorization: its `_id` (the device code) or its unique `userCodeHash`. */
33
+ export declare function onDeviceCode(duplicate: DuplicateKey): boolean;
34
+ //# sourceMappingURL=translate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"translate.d.ts","sourceRoot":"","sources":["../src/translate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAE3D;;;;;;;;;;;;;GAaG;AAEH,mHAAmH;AACnH,wBAAsB,GAAG,CAAC,CAAC,EAC1B,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EACtB,MAAM,SAAe,GACnB,OAAO,CAAC,CAAC,CAAC,CAUZ;AAED,wEAAwE;AACxE,MAAM,WAAW,YAAY;IAC5B,QAAQ,CAAC,IAAI,EAAE,KAAK,CAAC;IACrB,QAAQ,CAAC,UAAU,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;CACxD;AAED,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,YAAY,CAMpE;AAED,sGAAsG;AACtG,wBAAsB,WAAW,CAChC,KAAK,EAAE,OAAO,CAAC,OAAO,CAAC,GACrB,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CAQ9B;AAED,6FAA6F;AAC7F,wBAAgB,mBAAmB,CAClC,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,YAAY,GACrB,YAAY,CAKd;AAED,qFAAqF;AACrF,wBAAgB,IAAI,CAAC,SAAS,EAAE,YAAY,GAAG,OAAO,CAGrD;AAED,4EAA4E;AAC5E,wBAAgB,KAAK,CAAC,SAAS,EAAE,YAAY,GAAG,OAAO,CAEtD;AAED,qHAAqH;AACrH,wBAAgB,YAAY,CAAC,SAAS,EAAE,YAAY,GAAG,OAAO,CAG7D"}
package/docs/README.md ADDED
@@ -0,0 +1,13 @@
1
+ # @softistx/janus-oauth-mongo — documentation
2
+
3
+ The [README](../README.md) shows the wiring in one example; these pages give
4
+ the detail. The words — grant, code, rotation, replay, reuse — are
5
+ `@softistx/janus-oauth`'s, defined in
6
+ [its index](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus-oauth/docs/README.md#words).
7
+
8
+ | Page | Read it when |
9
+ | --- | --- |
10
+ | [Wiring the store to MongoDB](guide/wiring.md) | You pass the store to `createOAuthServer()`, create the collections and indexes with `syncMongoOAuth`, choose TTL graces, need to know what MongoDB must be, want to know how each method stays atomic, wire the encrypted signing-key store (`createMongoSigningKeys`), or the DPoP replay cache (`createMongoDPoPReplayCache`) |
11
+ | [Partitions](guide/partitions.md) | You keep several issuers in one database with `createMongoOAuth(db, { partition })`: the layout, the sync, and the migration of an existing deployment |
12
+ | [Troubleshooting](troubleshooting.md) | You have an error message and want its cause and its fix |
13
+ | [Roadmap](roadmap.md) | You want to know what is coming and what is deliberately not planned |
@@ -0,0 +1,141 @@
1
+ # Partitions: several issuers in one database
2
+
3
+ `createMongoOAuth(db, { partition })` is the store of one issuer among several
4
+ in a database, for `createOAuthIssuers()` in `@softistx/janus-oauth`. It is
5
+ opt-in. Without `partition` the storage is exactly what it always was.
6
+
7
+ ```ts
8
+ import {
9
+ createMongoOAuth,
10
+ createMongoSigningKeys,
11
+ syncMongoOAuthPartitioned,
12
+ } from '@softistx/janus-oauth-mongo';
13
+
14
+ await syncMongoOAuthPartitioned(db); // a deployment step, with dbAdmin
15
+
16
+ const store = createMongoOAuth(db, { partition: tenant.issuer });
17
+ const keys = createMongoSigningKeys(db, { encryptionKey, partition: tenant.issuer });
18
+ ```
19
+
20
+ ## The layout
21
+
22
+ The partitioned store uses seven collections of its own, so the default ones are
23
+ not touched and both can sit in one database:
24
+
25
+ | Collection | Same as |
26
+ | --- | --- |
27
+ | `oauthPartitionedClients` | `oauthClients` |
28
+ | `oauthPartitionedRequests` | `oauthRequests` |
29
+ | `oauthPartitionedCodes` | `oauthCodes` |
30
+ | `oauthPartitionedDeviceAuthorizations` | `oauthDeviceAuthorizations` |
31
+ | `oauthPartitionedGrants` | `oauthGrants` |
32
+ | `oauthPartitionedAccessTokens` | `oauthAccessTokens` |
33
+ | `oauthPartitionedRefreshTokens` | `oauthRefreshTokens` |
34
+
35
+ and the signing keys, whose collection (`oauthSigningKeys`) was partitioned
36
+ already: pass the same `partition` string to `createMongoSigningKeys`.
37
+
38
+ The DPoP replay cache (`oauthDpopReplay`, `createMongoDPoPReplayCache`) is not
39
+ partitioned either: its keys carry no partition, `syncMongoOAuthPartitioned`
40
+ syncs it, `purgeMongoOAuthPartition` leaves it, and its TTL empties it.
41
+
42
+ - Each document has the same fields as before plus `partition`.
43
+ - `_id` is `JSON.stringify([partition, id])` (the signing keys' form), so a
44
+ client id, a secret hash or a grant id of one partition is a different key in
45
+ another. The unique index on a secret hash is still the primary key.
46
+ - Every index except the TTL ones starts with `partition`:
47
+ `{ partition, userId }`, `{ partition, grantId }`, and the grant's unique
48
+ `{ partition, userId, clientId, resource }`: two issuers can each hold a grant
49
+ for the same user, client and resource. A TTL index stays on its own field,
50
+ since MongoDB only expires on a single-field index.
51
+ - The definitions are derived from the default ones, so a field added there
52
+ reaches both layouts. `oauthPartitionedCollections` lists them for
53
+ `@softistx/mongo`'s `syncAll`.
54
+
55
+ ## Migrating a deployment that opts in
56
+
57
+ The partitioned collections start empty. A deployment with records moves them
58
+ once. Do it in a window with no traffic, or sign users out afterwards: a record
59
+ written to the old collections after the copy is lost.
60
+
61
+ 1. **Create the new collections.** `await syncMongoOAuthPartitioned(db)`.
62
+ 2. **Copy each collection, rewriting `_id` and adding `partition`.** The partition
63
+ is the issuer's name; the key is `JSON.stringify([partition, id])`:
64
+
65
+ ```ts
66
+ const PAIRS = [
67
+ ['oauthClients', 'oauthPartitionedClients'],
68
+ ['oauthRequests', 'oauthPartitionedRequests'],
69
+ ['oauthCodes', 'oauthPartitionedCodes'],
70
+ ['oauthGrants', 'oauthPartitionedGrants'],
71
+ ['oauthAccessTokens', 'oauthPartitionedAccessTokens'],
72
+ ['oauthRefreshTokens', 'oauthPartitionedRefreshTokens'],
73
+ ] as const;
74
+
75
+ for (const [from, to] of PAIRS) {
76
+ let batch = [];
77
+ for await (const doc of db.collection(from).find()) {
78
+ batch.push({ ...doc, _id: JSON.stringify([partition, doc._id]), partition });
79
+ if (batch.length === 500) {
80
+ await db.collection(to).insertMany(batch);
81
+ batch = [];
82
+ }
83
+ }
84
+ if (batch.length > 0) await db.collection(to).insertMany(batch);
85
+ }
86
+ ```
87
+
88
+ 3. **Check the counts** of each pair (`countDocuments`).
89
+ 4. **Switch** the store to `createMongoOAuth(db, { partition })`.
90
+ 5. **Keep the signing keys' partition.** If they were stored under `partition:
91
+ 'default'`, either keep using that for `createMongoSigningKeys`, or re-insert
92
+ them under the issuer's name; their ciphertext is bound to the partition, so a
93
+ changed `partition` needs new keys (`rotateSigningKeys`), not an edit.
94
+ 6. **Drop the old collections** once you are sure (`oauthClients` ... except
95
+ `oauthSigningKeys`), or keep them as a backup until the TTL monitor has
96
+ emptied the short-lived ones.
97
+
98
+ To go back, copy the other way: take `_id` from the JSON array's second element
99
+ and remove `partition`.
100
+
101
+ ## Purging a partition
102
+
103
+ `purgeMongoOAuthPartition` removes an issuer for good. **It is destructive and
104
+ cannot be undone**: the clients, requests, codes, device authorizations, grants, access tokens,
105
+ refresh tokens and signing keys of the partition are deleted from the database.
106
+
107
+ ```ts
108
+ import { purgeMongoOAuthPartition } from '@softistx/janus-oauth-mongo';
109
+
110
+ const deleted = await purgeMongoOAuthPartition(db, { partition: 'issuer-a' });
111
+ // { clients: 2, requests: 0, codes: 1, deviceAuthorizations: 0, grants: 5, accessTokens: 9, refreshTokens: 5, signingKeys: 2 }
112
+ ```
113
+
114
+ - Every delete is filtered on the exact `partition`: another partition and the
115
+ default (unpartitioned) collections are never touched.
116
+ - It is idempotent: a second run, or a partition that never existed, answers
117
+ zeros.
118
+ - A missing, empty or non-string `partition` is a `TypeError`, before any I/O.
119
+ There is no "purge everything".
120
+ - It is not a transaction. The collections are emptied one after the other (the
121
+ tokens, codes and requests first, the signing keys last); an outage is a
122
+ `StoreFailure`, and running it again finishes the job.
123
+ - Stop serving the issuer first: a request still in flight can write a record
124
+ after its collection was emptied. A second run removes it.
125
+ - Once the signing keys are gone, no JWT access token of the partition verifies
126
+ any more, and the keys cannot be recovered. `signingKeys: false` keeps them.
127
+ - The partition named `default` is also the key set of an unpartitioned
128
+ deployment (`createMongoSigningKeys(db)` with no `partition`), so purging it
129
+ must say `signingKeys: true` or `signingKeys: false`; leaving it out is a
130
+ `TypeError`.
131
+
132
+ ## Traps
133
+
134
+ - It is a different layout. Turning `partition` on over a database with records
135
+ starts with none until you migrate.
136
+ - Run `syncMongoOAuthPartitioned`, not only `syncMongoOAuth`: without it the
137
+ unique grant index and the validators are missing.
138
+ - A partition is a name you choose. Two issuers that share one share every
139
+ record. Derive it from the issuer, never from the request.
140
+ - A document whose `_id` is not `JSON.stringify([partition, id])` for the store's
141
+ partition is refused as a `StoreFailure` rather than guessed at.
@@ -0,0 +1,133 @@
1
+ # Wiring the store to MongoDB
2
+
3
+ ```ts
4
+ import { createMongoOAuth, syncMongoOAuth } from '@softistx/janus-oauth-mongo';
5
+
6
+ await syncMongoOAuth(db); // once per deployment
7
+ const store = createMongoOAuth(db); // an OAuthStore, for createOAuthServer({ store })
8
+ ```
9
+
10
+ `db` is the `Db` of the connection your application opened with
11
+ `@softistx/mongo`. The store opens no connection of its own and creates nothing at
12
+ request time.
13
+
14
+ ## What MongoDB must be
15
+
16
+ **A replica set or a sharded cluster.** `rotateRefreshToken` stores the new
17
+ access and refresh tokens and marks the old one rotated in one transaction,
18
+ because the port asks for all or nothing. On a standalone `mongod` the first
19
+ rotation rejects with a `StoreFailure`; every other method works there. A
20
+ single-node replica set is enough for development.
21
+
22
+ **Reads go to the primary.** The store opens its seven OAuth collections, and the signing-key store its own,
23
+ with
24
+ `{ readPreference: 'primary' }` whatever the connection's default is: after it
25
+ stores a token pair the server re-reads the grant, and a lagging secondary
26
+ could answer the grant as standing when a revoke has just been acknowledged.
27
+
28
+ ## Collections and indexes: `syncMongoOAuth`
29
+
30
+ ```ts
31
+ function syncMongoOAuth(db: Db, options?: SyncOptions): Promise<SyncReport[]>;
32
+ ```
33
+
34
+ It creates the nine collections (the ninth, `oauthDpopReplay`, backs `createMongoDPoPReplayCache`), writes their `$jsonSchema` validators and
35
+ creates or rebuilds their indexes, then answers one report per collection.
36
+ **Run it twice and the second run sends nothing.** It is a deployment step,
37
+ never a request-time one: it needs the `dbAdmin` role. `dryRun` reports
38
+ without sending; `dropUnknownIndexes` drops indexes no definition names.
39
+ An application that deploys with `@softistx/mongo`'s `syncAll(db)` already syncs
40
+ these collections, since importing the package registers them.
41
+
42
+ | Collection | Indexes |
43
+ | --- | --- |
44
+ | `oauthClients` | TTL on `expiresAt`, 24 h grace (`CLIENT_GRACE_SECONDS`) |
45
+ | `oauthRequests` | TTL on `expiresAt` |
46
+ | `oauthCodes` | `userId`; TTL on `expiresAt`, 24 h grace (`CODE_GRACE_SECONDS`) |
47
+ | `oauthGrants` | unique `(userId, clientId, resource)`; partial `bound` on `(bound.type, bound.id, _id)` |
48
+ | `oauthAccessTokens` | `grantId`, `userId`; TTL on `expiresAt` |
49
+ | `oauthRefreshTokens` | `grantId`, `userId`; TTL on `absoluteExpiresAt` |
50
+ | `oauthDeviceAuthorizations` | unique `userCodeHash`; `userId`; TTL on `expiresAt`, 24 h grace (`DEVICE_GRACE_SECONDS`) |
51
+ | `oauthDpopReplay` | TTL on `expiresAt`, no grace: a lapsed document counts as unused whether or not the monitor has reaped it |
52
+
53
+ **Token exchange (RFC 8693).** The access-token collections keep the optional `actor` of a delegated token (`{ sub, clientId? }`, absent when not given, never `null`), in both layouts, and the client validator accepts `urn:ietf:params:oauth:grant-type:token-exchange` in `grantTypes`. Without the schema change the actor would be dropped and introspection would report an impersonation. **Two validators change** (`oauthClients` and both access-token collections): run `syncMongoOAuth(db)` (or `syncMongoOAuthPartitioned(db)`) before deploying, or a write answers `Document failed validation`. `revokeClientGrants` also revokes the tokens a client holds under another client's grant. [Guide](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus-oauth/docs/guide/token-exchange.md#revocation).
54
+
55
+ **Authorization details (RFC 9396).** The store keeps the optional `authorizationDetails` of requests, codes, grants, access and refresh tokens and device authorizations, in both layouts, and `authorizationDetailsTypes` of clients, absent when not given. A record's details are stored as **one canonical JSON string** (keys sorted, arrays in order; a detail's keys such as `$x` or `a.b` collide with MongoDB's field rules, and nothing queries them) and parsed back on every read; a stored value that is not a JSON list of objects is a `TypeError` naming the store, never the value. `upsertGrant` removes a grant's details when the new consent has none, and an approval carrying no details removes a device authorization's asked ones. **Seven validators change** (`oauthClients`, `oauthRequests`, `oauthCodes`, `oauthGrants`, both token collections and `oauthDeviceAuthorizations`): run `syncMongoOAuth(db)` (or `syncMongoOAuthPartitioned(db)`) **before you deploy** the new server, or a write that carries a field answers `Document failed validation` (code 121). Rows already stored need no migration. [Guide](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus-oauth/docs/guide/store.md#authorization-details).
56
+
57
+ **DPoP (RFC 9449).** The store keeps the optional `jkt` of access and refresh tokens, `dpopJkt` of requests and codes, and `dpopBoundAccessTokens` of clients, in both layouts, absent when not given. **Four validators change** (`oauthClients`, `oauthRequests`, `oauthCodes` and both token collections): run `syncMongoOAuth(db)` (or `syncMongoOAuthPartitioned(db)`) before the first write of a new field, or MongoDB answers `Document failed validation`. `createMongoDPoPReplayCache(db)` is the replay cache of the `dpop` option ([guide](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus-oauth/docs/guide/dpop.md#the-mongodb-replay-cache)):
58
+
59
+ ```ts
60
+ import { createOAuthServer } from '@softistx/janus-oauth';
61
+ import { createMongoDPoPReplayCache, createMongoOAuth } from '@softistx/janus-oauth-mongo';
62
+
63
+ const oauth = createOAuthServer({
64
+ auth,
65
+ store: createMongoOAuth(db),
66
+ issuer: 'https://auth.example.com',
67
+ resources: { 'https://api.example.com/mcp': { scopes: ['read'] } },
68
+ dpop: { replay: createMongoDPoPReplayCache(db) }, // one atomic upsert per proof
69
+ });
70
+ ```
71
+
72
+ **Device authorizations (RFC 8628).** `createMongoOAuth` implements the store's `device` capability, so `createOAuthServer({ deviceAuthorization: { verificationUri } })` works over it ([guide](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus-oauth/docs/guide/device.md)). The `_id` is `sha256(device_code)` and the unique `userCodeHash` index is what keeps two requests from sharing a user code: **run `syncMongoOAuth(db)` (or `syncMongoOAuthPartitioned(db)`) before you deploy**, or the index is missing. A poll that names another client or resource answers `absent` and writes nothing, and an approval is handed over once, even under concurrent polls. `deleteUserGrants` removes the user's device authorizations too.
73
+
74
+ **The unique index on each secret hash is `_id`**: a code and a token are keyed
75
+ by `sha256(secret)`, so a duplicate hash cannot exist.
76
+
77
+ ## Expiry: TTL indexes are hygiene
78
+
79
+ MongoDB's TTL monitor runs about every 60 seconds, and can run later under load.
80
+ A record is therefore **readable for a minute or more after it lapsed**. The
81
+ store answers it as it is stored (rule 3 of the port) and the server compares
82
+ `expiresAt` on every read, so nothing relies on the monitor. `consumeOAuthCode`
83
+ and `rotateRefreshToken` compare `expiresAt` with the `now` they are given, in
84
+ the same conditional write.
85
+
86
+ - **Codes keep 24 hours past `expiresAt`**: a code spent and presented again
87
+ must answer `replayed`, which revokes its grant, not `absent`.
88
+ - **Refresh tokens expire on `absoluteExpiresAt`**, not on the sliding
89
+ `expiresAt`: a token rotated long ago must stay as long as its chain can live
90
+ (30 days sliding, 90 days at most), or a stolen copy replayed after it
91
+ lapsed would not be recognised as reuse.
92
+ - **Metadata clients keep 24 hours** after `expiresAt`, as storage hygiene only: a lapsed copy is fetched again, and a failed refetch is `invalid_client`, never answered from the stale copy.
93
+ - Grants never expire: they are what a user allowed.
94
+
95
+ `deleteExpiredOAuthRecords` is not implemented; the TTL indexes replace it.
96
+
97
+ `listBoundGrants` is implemented too, for bound grants: a partial index `bound` on `{ 'bound.type', 'bound.id', _id }` (grants with a `bound` only) serves it, so run `syncMongoOAuth(db)` (`syncMongoOAuthPartitioned(db)` in the partitioned layout) on an existing database before deploying: the earlier validator refuses a grant with a `bound` (`Document failed validation`, code 121), and the sync replaces it and creates the index.
98
+
99
+ Pushed authorization requests need the same re-sync: a client's `requirePushedAuthorizationRequests` is refused by the earlier `oauthClients` validator (code 121) until `syncMongoOAuth(db)` replaces it. A pushed request itself is an ordinary `oauthRequests` document.
100
+
101
+ `listClients`, `listClientGrants` and `revokeClientGrants` are implemented (`clientId` index on grants, access and refresh tokens): pages are read by `_id` order with a cursor, and a `clientId` index on grants and on both token collections serves them. Run `syncMongoOAuth(db)` to create those indexes on an existing database.
102
+
103
+ ## How each method stays atomic
104
+
105
+ | Method | One driver call |
106
+ | --- | --- |
107
+ | `consumeOAuthCode` | `findOneAndUpdate` on `{ _id, consumedAt: null, expiresAt > now }`; on no match, one read tells `replayed` from `absent` |
108
+ | `consumeAuthorizationRequest` | `findOneAndDelete` |
109
+ | `rotateRefreshToken` | transaction: `findOneAndUpdate` on `{ _id, rotatedAt: null, revokedAt: null, expiresAt > now }`, then the new pair; the loser reads `reused` or `absent` |
110
+ | `upsertGrant` | upsert on the unique key, `$setOnInsert` for `id` and `createdAt` |
111
+ | `revokeGrant` | a pipeline update keeping the first `revokedAt`, then the grant's tokens still standing |
112
+ | `revokeGrantsByResource` | `updateMany` on `{ resource: <equals> or { $ne: <differs> }, revokedAt: null }` over grants, then access and refresh tokens (no index on `resource`: a scan); `dryRun` uses `countDocuments` |
113
+ | `revokeAccessToken`, `revokeRefreshToken` | a pipeline update keeping the first `revokedAt` |
114
+ | `insert…` | `insertOne`; a duplicate `_id` is a retry and writes nothing |
115
+
116
+ ## Failures
117
+
118
+ Every rejection from the driver is a `StoreFailure` from `@softistx/janus`, with the
119
+ driver's error as `cause` and `operation` the method. Nothing answers `null`,
120
+ `false`, `0` or `absent` for an error. A duplicate key on an index other than
121
+ `_id` is reported as a failure too: it means an index this adapter never wrote
122
+ on purpose.
123
+
124
+ ## Signing keys
125
+
126
+ `createMongoSigningKeys(db, { encryptionKey, partition? })` is the
127
+ `SigningKeyStore` for JWT access tokens. It reads from the primary too, and
128
+ `promote` (which retires the current key and promotes the next, all or
129
+ nothing) needs a replica set, like a refresh rotation. `partition` keeps
130
+ several key sets in one collection; two partitions never see each other's
131
+ keys. The master key, the encryption and what to do when the key is lost are in
132
+ the [README](../../README.md#encrypted-signing-keys); rotating the master key
133
+ without losing the keys is [there too](../../README.md#rotating-the-master-key).