@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.
- package/LICENSE +21 -0
- package/README.md +262 -2
- package/dist/authorization-collections.d.ts +43 -0
- package/dist/authorization-collections.d.ts.map +1 -0
- package/dist/clients-collection.d.ts +29 -0
- package/dist/clients-collection.d.ts.map +1 -0
- package/dist/collection-fields.d.ts +23 -0
- package/dist/collection-fields.d.ts.map +1 -0
- package/dist/collections.d.ts +211 -0
- package/dist/collections.d.ts.map +1 -0
- package/dist/details-field.d.ts +25 -0
- package/dist/details-field.d.ts.map +1 -0
- package/dist/device-collection.d.ts +28 -0
- package/dist/device-collection.d.ts.map +1 -0
- package/dist/dpop-replay-collection.d.ts +13 -0
- package/dist/dpop-replay-collection.d.ts.map +1 -0
- package/dist/dpop-replay.d.ts +27 -0
- package/dist/dpop-replay.d.ts.map +1 -0
- package/dist/grants-collection.d.ts +17 -0
- package/dist/grants-collection.d.ts.map +1 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1671 -0
- package/dist/index.js.map +52 -0
- package/dist/partitioned.d.ts +97 -0
- package/dist/partitioned.d.ts.map +1 -0
- package/dist/purge.d.ts +124 -0
- package/dist/purge.d.ts.map +1 -0
- package/dist/record-fields.d.ts +57 -0
- package/dist/record-fields.d.ts.map +1 -0
- package/dist/records/clients.d.ts +7 -0
- package/dist/records/clients.d.ts.map +1 -0
- package/dist/records/grants.d.ts +7 -0
- package/dist/records/grants.d.ts.map +1 -0
- package/dist/records/index.d.ts +5 -0
- package/dist/records/index.d.ts.map +1 -0
- package/dist/records/requests.d.ts +10 -0
- package/dist/records/requests.d.ts.map +1 -0
- package/dist/records/tokens.d.ts +10 -0
- package/dist/records/tokens.d.ts.map +1 -0
- package/dist/records-device.d.ts +7 -0
- package/dist/records-device.d.ts.map +1 -0
- package/dist/signing-keys/context.d.ts +11 -0
- package/dist/signing-keys/context.d.ts.map +1 -0
- package/dist/signing-keys/index.d.ts +22 -0
- package/dist/signing-keys/index.d.ts.map +1 -0
- package/dist/signing-keys/keyring.d.ts +9 -0
- package/dist/signing-keys/keyring.d.ts.map +1 -0
- package/dist/signing-keys/options.d.ts +15 -0
- package/dist/signing-keys/options.d.ts.map +1 -0
- package/dist/signing-keys/promote.d.ts +7 -0
- package/dist/signing-keys/promote.d.ts.map +1 -0
- package/dist/signing-keys/read.d.ts +7 -0
- package/dist/signing-keys/read.d.ts.map +1 -0
- package/dist/signing-keys/records.d.ts +13 -0
- package/dist/signing-keys/records.d.ts.map +1 -0
- package/dist/signing-keys/reseal.d.ts +25 -0
- package/dist/signing-keys/reseal.d.ts.map +1 -0
- package/dist/signing-keys/seal.d.ts +19 -0
- package/dist/signing-keys/seal.d.ts.map +1 -0
- package/dist/signing-keys/write.d.ts +7 -0
- package/dist/signing-keys/write.d.ts.map +1 -0
- package/dist/signing-keys-collection.d.ts +52 -0
- package/dist/signing-keys-collection.d.ts.map +1 -0
- package/dist/store/clients.d.ts +7 -0
- package/dist/store/clients.d.ts.map +1 -0
- package/dist/store/codes.d.ts +7 -0
- package/dist/store/codes.d.ts.map +1 -0
- package/dist/store/context.d.ts +21 -0
- package/dist/store/context.d.ts.map +1 -0
- package/dist/store/device.d.ts +7 -0
- package/dist/store/device.d.ts.map +1 -0
- package/dist/store/grant-reads.d.ts +7 -0
- package/dist/store/grant-reads.d.ts.map +1 -0
- package/dist/store/grants.d.ts +7 -0
- package/dist/store/grants.d.ts.map +1 -0
- package/dist/store/index.d.ts +58 -0
- package/dist/store/index.d.ts.map +1 -0
- package/dist/store/open.d.ts +9 -0
- package/dist/store/open.d.ts.map +1 -0
- package/dist/store/requests.d.ts +7 -0
- package/dist/store/requests.d.ts.map +1 -0
- package/dist/store/rotate.d.ts +6 -0
- package/dist/store/rotate.d.ts.map +1 -0
- package/dist/store/scope.d.ts +24 -0
- package/dist/store/scope.d.ts.map +1 -0
- package/dist/store/spend-devices.d.ts +20 -0
- package/dist/store/spend-devices.d.ts.map +1 -0
- package/dist/store/tokens.d.ts +7 -0
- package/dist/store/tokens.d.ts.map +1 -0
- package/dist/sync.d.ts +20 -0
- package/dist/sync.d.ts.map +1 -0
- package/dist/tokens-collections.d.ts +42 -0
- package/dist/tokens-collections.d.ts.map +1 -0
- package/dist/transaction.d.ts +13 -0
- package/dist/transaction.d.ts.map +1 -0
- package/dist/translate.d.ts +34 -0
- package/dist/translate.d.ts.map +1 -0
- package/docs/README.md +13 -0
- package/docs/guide/partitions.md +141 -0
- package/docs/guide/wiring.md +133 -0
- package/docs/roadmap.md +46 -0
- package/docs/troubleshooting.md +226 -0
- package/package.json +68 -5
package/dist/index.js
ADDED
|
@@ -0,0 +1,1671 @@
|
|
|
1
|
+
// src/authorization-collections.ts
|
|
2
|
+
import { defineCollection } from "@softistx/mongo";
|
|
3
|
+
import { z as z2 } from "zod";
|
|
4
|
+
|
|
5
|
+
// src/collection-fields.ts
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
var at = z.date();
|
|
8
|
+
var scopes = z.array(z.string());
|
|
9
|
+
var authorizationDetails = z.string().optional();
|
|
10
|
+
var openIdFields = {
|
|
11
|
+
nonce: z.string().optional(),
|
|
12
|
+
authTime: at.optional(),
|
|
13
|
+
amr: z.array(z.string()).optional(),
|
|
14
|
+
acr: z.string().optional()
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
// src/authorization-collections.ts
|
|
18
|
+
var CODE_GRACE_SECONDS = 24 * 60 * 60;
|
|
19
|
+
var oauthRequests = defineCollection({
|
|
20
|
+
name: "oauthRequests",
|
|
21
|
+
schema: z2.object({
|
|
22
|
+
_id: z2.string(),
|
|
23
|
+
clientId: z2.string(),
|
|
24
|
+
redirectUri: z2.string(),
|
|
25
|
+
resource: z2.string(),
|
|
26
|
+
scopes,
|
|
27
|
+
state: z2.string().nullable(),
|
|
28
|
+
nonce: z2.string().optional(),
|
|
29
|
+
dpopJkt: z2.string().optional(),
|
|
30
|
+
authorizationDetails,
|
|
31
|
+
acrValues: z2.array(z2.string()).optional(),
|
|
32
|
+
maxAge: z2.number().int().nonnegative().optional(),
|
|
33
|
+
prompt: z2.array(z2.string()).optional(),
|
|
34
|
+
loginHint: z2.string().optional(),
|
|
35
|
+
codeChallenge: z2.string(),
|
|
36
|
+
codeChallengeMethod: z2.literal("S256"),
|
|
37
|
+
createdAt: at,
|
|
38
|
+
expiresAt: at
|
|
39
|
+
}),
|
|
40
|
+
indexes: [{ key: { expiresAt: 1 }, name: "expiry", expireAfterSeconds: 0 }]
|
|
41
|
+
});
|
|
42
|
+
var oauthCodes = defineCollection({
|
|
43
|
+
name: "oauthCodes",
|
|
44
|
+
schema: z2.object({
|
|
45
|
+
_id: z2.string(),
|
|
46
|
+
clientId: z2.string(),
|
|
47
|
+
userId: z2.string(),
|
|
48
|
+
grantId: z2.string(),
|
|
49
|
+
redirectUri: z2.string(),
|
|
50
|
+
resource: z2.string(),
|
|
51
|
+
scopes,
|
|
52
|
+
codeChallenge: z2.string(),
|
|
53
|
+
codeChallengeMethod: z2.literal("S256"),
|
|
54
|
+
createdAt: at,
|
|
55
|
+
expiresAt: at,
|
|
56
|
+
consumedAt: at.nullable(),
|
|
57
|
+
dpopJkt: z2.string().optional(),
|
|
58
|
+
authorizationDetails,
|
|
59
|
+
...openIdFields
|
|
60
|
+
}),
|
|
61
|
+
indexes: [
|
|
62
|
+
{ key: { userId: 1 }, name: "userId" },
|
|
63
|
+
{
|
|
64
|
+
key: { expiresAt: 1 },
|
|
65
|
+
name: "expiry",
|
|
66
|
+
expireAfterSeconds: CODE_GRACE_SECONDS
|
|
67
|
+
}
|
|
68
|
+
]
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
// src/clients-collection.ts
|
|
72
|
+
import { defineCollection as defineCollection2 } from "@softistx/mongo";
|
|
73
|
+
import { z as z3 } from "zod";
|
|
74
|
+
var CLIENT_GRACE_SECONDS = 24 * 60 * 60;
|
|
75
|
+
var oauthClients = defineCollection2({
|
|
76
|
+
name: "oauthClients",
|
|
77
|
+
schema: z3.object({
|
|
78
|
+
_id: z3.string(),
|
|
79
|
+
name: z3.string(),
|
|
80
|
+
redirectUris: z3.array(z3.string()),
|
|
81
|
+
source: z3.enum(["registered", "metadata"]),
|
|
82
|
+
createdAt: at,
|
|
83
|
+
expiresAt: at.nullable(),
|
|
84
|
+
tokenEndpointAuthMethod: z3.enum(["none", "client_secret_basic"]).optional(),
|
|
85
|
+
secretHash: z3.string().optional(),
|
|
86
|
+
grantTypes: z3.array(z3.enum([
|
|
87
|
+
"authorization_code",
|
|
88
|
+
"refresh_token",
|
|
89
|
+
"urn:ietf:params:oauth:grant-type:device_code",
|
|
90
|
+
"urn:ietf:params:oauth:grant-type:token-exchange"
|
|
91
|
+
])).optional(),
|
|
92
|
+
requirePushedAuthorizationRequests: z3.boolean().optional(),
|
|
93
|
+
dpopBoundAccessTokens: z3.boolean().optional(),
|
|
94
|
+
authorizationDetailsTypes: z3.array(z3.string()).optional()
|
|
95
|
+
}),
|
|
96
|
+
indexes: [
|
|
97
|
+
{
|
|
98
|
+
key: { expiresAt: 1 },
|
|
99
|
+
name: "expiry",
|
|
100
|
+
expireAfterSeconds: CLIENT_GRACE_SECONDS
|
|
101
|
+
}
|
|
102
|
+
]
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
// src/device-collection.ts
|
|
106
|
+
import { defineCollection as defineCollection3 } from "@softistx/mongo";
|
|
107
|
+
import { z as z4 } from "zod";
|
|
108
|
+
var at2 = z4.date();
|
|
109
|
+
var DEVICE_GRACE_SECONDS = 24 * 60 * 60;
|
|
110
|
+
var oauthDeviceAuthorizations = defineCollection3({
|
|
111
|
+
name: "oauthDeviceAuthorizations",
|
|
112
|
+
schema: z4.object({
|
|
113
|
+
_id: z4.string(),
|
|
114
|
+
userCodeHash: z4.string(),
|
|
115
|
+
clientId: z4.string(),
|
|
116
|
+
resource: z4.string(),
|
|
117
|
+
scopes: z4.array(z4.string()),
|
|
118
|
+
intervalMs: z4.number(),
|
|
119
|
+
lastPolledAt: at2.nullable(),
|
|
120
|
+
status: z4.enum(["pending", "approved", "denied"]),
|
|
121
|
+
userId: z4.string().optional(),
|
|
122
|
+
grantId: z4.string().optional(),
|
|
123
|
+
createdAt: at2,
|
|
124
|
+
expiresAt: at2,
|
|
125
|
+
consumedAt: at2.nullable(),
|
|
126
|
+
authorizationDetails,
|
|
127
|
+
nonce: z4.string().optional(),
|
|
128
|
+
authTime: at2.optional(),
|
|
129
|
+
amr: z4.array(z4.string()).optional(),
|
|
130
|
+
acr: z4.string().optional()
|
|
131
|
+
}),
|
|
132
|
+
indexes: [
|
|
133
|
+
{ key: { userCodeHash: 1 }, name: "userCodeHashUnique", unique: true },
|
|
134
|
+
{ key: { userId: 1 }, name: "userId" },
|
|
135
|
+
{ key: { grantId: 1 }, name: "grantId", sparse: true },
|
|
136
|
+
{ key: { clientId: 1 }, name: "clientId" },
|
|
137
|
+
{
|
|
138
|
+
key: { expiresAt: 1 },
|
|
139
|
+
name: "expiry",
|
|
140
|
+
expireAfterSeconds: DEVICE_GRACE_SECONDS
|
|
141
|
+
}
|
|
142
|
+
]
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
// src/dpop-replay-collection.ts
|
|
146
|
+
import { defineCollection as defineCollection4 } from "@softistx/mongo";
|
|
147
|
+
import { z as z5 } from "zod";
|
|
148
|
+
var oauthDpopReplay = defineCollection4({
|
|
149
|
+
name: "oauthDpopReplay",
|
|
150
|
+
schema: z5.object({
|
|
151
|
+
_id: z5.string(),
|
|
152
|
+
expiresAt: z5.date()
|
|
153
|
+
}),
|
|
154
|
+
indexes: [{ key: { expiresAt: 1 }, name: "expiry", expireAfterSeconds: 0 }]
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
// src/grants-collection.ts
|
|
158
|
+
import { defineCollection as defineCollection5 } from "@softistx/mongo";
|
|
159
|
+
import { z as z6 } from "zod";
|
|
160
|
+
var oauthGrants = defineCollection5({
|
|
161
|
+
name: "oauthGrants",
|
|
162
|
+
schema: z6.object({
|
|
163
|
+
_id: z6.string(),
|
|
164
|
+
userId: z6.string(),
|
|
165
|
+
clientId: z6.string(),
|
|
166
|
+
resource: z6.string(),
|
|
167
|
+
scopes,
|
|
168
|
+
createdAt: at,
|
|
169
|
+
updatedAt: at,
|
|
170
|
+
revokedAt: at.nullable(),
|
|
171
|
+
bound: z6.object({ type: z6.string(), id: z6.string() }).optional(),
|
|
172
|
+
authorizationDetails
|
|
173
|
+
}),
|
|
174
|
+
indexes: [
|
|
175
|
+
{
|
|
176
|
+
key: { userId: 1, clientId: 1, resource: 1 },
|
|
177
|
+
name: "userClientResourceUnique",
|
|
178
|
+
unique: true
|
|
179
|
+
},
|
|
180
|
+
{ key: { clientId: 1 }, name: "clientId" },
|
|
181
|
+
{
|
|
182
|
+
key: { "bound.type": 1, "bound.id": 1, _id: 1 },
|
|
183
|
+
name: "bound",
|
|
184
|
+
partialFilterExpression: { "bound.type": { $exists: true } }
|
|
185
|
+
}
|
|
186
|
+
]
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
// src/signing-keys-collection.ts
|
|
190
|
+
import { defineCollection as defineCollection6 } from "@softistx/mongo";
|
|
191
|
+
import { z as z7 } from "zod";
|
|
192
|
+
var at3 = z7.date();
|
|
193
|
+
var jwk = z7.object({
|
|
194
|
+
kty: z7.enum(["EC", "OKP"]),
|
|
195
|
+
crv: z7.enum(["P-256", "Ed25519"]),
|
|
196
|
+
x: z7.string(),
|
|
197
|
+
y: z7.string().optional(),
|
|
198
|
+
kid: z7.string(),
|
|
199
|
+
alg: z7.enum(["ES256", "EdDSA"]),
|
|
200
|
+
use: z7.literal("sig")
|
|
201
|
+
});
|
|
202
|
+
var oauthSigningKeys = defineCollection6({
|
|
203
|
+
name: "oauthSigningKeys",
|
|
204
|
+
schema: z7.object({
|
|
205
|
+
_id: z7.string(),
|
|
206
|
+
partition: z7.string(),
|
|
207
|
+
kid: z7.string(),
|
|
208
|
+
alg: z7.enum(["ES256", "EdDSA"]),
|
|
209
|
+
status: z7.enum(["current", "next", "retired"]),
|
|
210
|
+
slot: z7.enum(["current", "next"]).nullable(),
|
|
211
|
+
publicJwk: jwk,
|
|
212
|
+
sealed: z7.object({ iv: z7.string(), data: z7.string() }),
|
|
213
|
+
createdAt: at3,
|
|
214
|
+
activateAt: at3,
|
|
215
|
+
activatedAt: at3.nullable(),
|
|
216
|
+
retiredAt: at3.nullable(),
|
|
217
|
+
publishUntil: at3.nullable()
|
|
218
|
+
}),
|
|
219
|
+
indexes: [
|
|
220
|
+
{ key: { partition: 1, status: 1 }, name: "partitionStatus" },
|
|
221
|
+
{
|
|
222
|
+
key: { partition: 1, slot: 1 },
|
|
223
|
+
name: "partitionSlotUnique",
|
|
224
|
+
unique: true,
|
|
225
|
+
partialFilterExpression: { slot: { $type: "string" } }
|
|
226
|
+
},
|
|
227
|
+
{
|
|
228
|
+
key: { publishUntil: 1 },
|
|
229
|
+
name: "publishUntilExpiry",
|
|
230
|
+
expireAfterSeconds: 0
|
|
231
|
+
}
|
|
232
|
+
]
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
// src/tokens-collections.ts
|
|
236
|
+
import { defineCollection as defineCollection7 } from "@softistx/mongo";
|
|
237
|
+
import { z as z8 } from "zod";
|
|
238
|
+
var tokenFields = {
|
|
239
|
+
_id: z8.string(),
|
|
240
|
+
grantId: z8.string(),
|
|
241
|
+
userId: z8.string(),
|
|
242
|
+
clientId: z8.string(),
|
|
243
|
+
resource: z8.string(),
|
|
244
|
+
scopes,
|
|
245
|
+
createdAt: at,
|
|
246
|
+
expiresAt: at,
|
|
247
|
+
revokedAt: at.nullable(),
|
|
248
|
+
jkt: z8.string().optional(),
|
|
249
|
+
authorizationDetails,
|
|
250
|
+
...openIdFields
|
|
251
|
+
};
|
|
252
|
+
var oauthAccessTokens = defineCollection7({
|
|
253
|
+
name: "oauthAccessTokens",
|
|
254
|
+
schema: z8.object({
|
|
255
|
+
...tokenFields,
|
|
256
|
+
actor: z8.object({ sub: z8.string(), clientId: z8.string().optional() }).optional()
|
|
257
|
+
}),
|
|
258
|
+
indexes: [
|
|
259
|
+
{ key: { grantId: 1 }, name: "grantId" },
|
|
260
|
+
{ key: { userId: 1 }, name: "userId" },
|
|
261
|
+
{ key: { clientId: 1 }, name: "clientId" },
|
|
262
|
+
{ key: { expiresAt: 1 }, name: "expiry", expireAfterSeconds: 0 }
|
|
263
|
+
]
|
|
264
|
+
});
|
|
265
|
+
var oauthRefreshTokens = defineCollection7({
|
|
266
|
+
name: "oauthRefreshTokens",
|
|
267
|
+
schema: z8.object({
|
|
268
|
+
...tokenFields,
|
|
269
|
+
absoluteExpiresAt: at,
|
|
270
|
+
rotatedAt: at.nullable()
|
|
271
|
+
}),
|
|
272
|
+
indexes: [
|
|
273
|
+
{ key: { grantId: 1 }, name: "grantId" },
|
|
274
|
+
{ key: { userId: 1 }, name: "userId" },
|
|
275
|
+
{ key: { clientId: 1 }, name: "clientId" },
|
|
276
|
+
{
|
|
277
|
+
key: { absoluteExpiresAt: 1 },
|
|
278
|
+
name: "expiry",
|
|
279
|
+
expireAfterSeconds: 0
|
|
280
|
+
}
|
|
281
|
+
]
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
// src/collections.ts
|
|
285
|
+
var oauthCollections = [
|
|
286
|
+
oauthClients,
|
|
287
|
+
oauthRequests,
|
|
288
|
+
oauthCodes,
|
|
289
|
+
oauthDeviceAuthorizations,
|
|
290
|
+
oauthGrants,
|
|
291
|
+
oauthAccessTokens,
|
|
292
|
+
oauthRefreshTokens,
|
|
293
|
+
oauthSigningKeys,
|
|
294
|
+
oauthDpopReplay
|
|
295
|
+
];
|
|
296
|
+
// src/dpop-replay.ts
|
|
297
|
+
import { systemClock } from "@softistx/janus";
|
|
298
|
+
import { getCollection } from "@softistx/mongo";
|
|
299
|
+
|
|
300
|
+
// src/translate.ts
|
|
301
|
+
import { JanusError, StoreFailure } from "@softistx/janus";
|
|
302
|
+
async function run(operation, body, prefix = "oauthStore") {
|
|
303
|
+
try {
|
|
304
|
+
return await body();
|
|
305
|
+
} catch (error) {
|
|
306
|
+
if (error instanceof JanusError)
|
|
307
|
+
throw error;
|
|
308
|
+
throw new StoreFailure(`${prefix}.${operation}: the store could not answer`, { operation, cause: error });
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
function isDuplicateKey(error) {
|
|
312
|
+
return typeof error === "object" && error !== null && error.code === 11000;
|
|
313
|
+
}
|
|
314
|
+
async function duplicateOf(write) {
|
|
315
|
+
try {
|
|
316
|
+
await write;
|
|
317
|
+
return null;
|
|
318
|
+
} catch (error) {
|
|
319
|
+
if (isDuplicateKey(error))
|
|
320
|
+
return error;
|
|
321
|
+
throw error;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
function unexpectedDuplicate(operation, duplicate) {
|
|
325
|
+
return new StoreFailure(`oauthStore.${operation}: a duplicate key on ${Object.keys(duplicate.keyPattern ?? {}).join(", ") || "an unknown index"}, which this adapter never writes on purpose`, { operation, cause: duplicate });
|
|
326
|
+
}
|
|
327
|
+
function onId(duplicate) {
|
|
328
|
+
const keys = Object.keys(duplicate.keyPattern ?? {});
|
|
329
|
+
return keys.length === 1 && keys[0] === "_id";
|
|
330
|
+
}
|
|
331
|
+
function onKey(duplicate) {
|
|
332
|
+
return "userId" in (duplicate.keyPattern ?? {});
|
|
333
|
+
}
|
|
334
|
+
function onDeviceCode(duplicate) {
|
|
335
|
+
const keys = Object.keys(duplicate.keyPattern ?? {});
|
|
336
|
+
return keys.includes("_id") || keys.includes("userCodeHash");
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// src/dpop-replay.ts
|
|
340
|
+
function createMongoDPoPReplayCache(db, options = {}) {
|
|
341
|
+
if (typeof db?.collection !== "function") {
|
|
342
|
+
throw new TypeError(`createMongoDPoPReplayCache: pass the Db your app opened with @softistx/mongo (got ${db === null ? "null" : typeof db})`);
|
|
343
|
+
}
|
|
344
|
+
const clock = options.clock ?? systemClock;
|
|
345
|
+
const keys = db.collection(getCollection(db, oauthDpopReplay).raw.collectionName, { readPreference: "primary" });
|
|
346
|
+
return {
|
|
347
|
+
spend: (key, expiresAt) => run("spend", async () => {
|
|
348
|
+
try {
|
|
349
|
+
await keys.updateOne({ _id: key, expiresAt: { $lte: clock.now() } }, { $set: { expiresAt } }, { upsert: true });
|
|
350
|
+
return true;
|
|
351
|
+
} catch (error) {
|
|
352
|
+
if (isDuplicateKey(error))
|
|
353
|
+
return false;
|
|
354
|
+
throw error;
|
|
355
|
+
}
|
|
356
|
+
}, "dpopReplay")
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
// src/partitioned.ts
|
|
360
|
+
import { defineCollection as defineCollection8 } from "@softistx/mongo";
|
|
361
|
+
import { z as z9 } from "zod";
|
|
362
|
+
function partitionIndex(index) {
|
|
363
|
+
if (index.expireAfterSeconds !== undefined)
|
|
364
|
+
return index;
|
|
365
|
+
return { ...index, key: { partition: 1, ...index.key } };
|
|
366
|
+
}
|
|
367
|
+
function partitioned(definition, name) {
|
|
368
|
+
return defineCollection8({
|
|
369
|
+
name,
|
|
370
|
+
schema: definition.schema.extend({ partition: z9.string() }),
|
|
371
|
+
indexes: definition.indexes.map(partitionIndex)
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
var oauthPartitionedClients = partitioned(oauthClients, "oauthPartitionedClients");
|
|
375
|
+
var oauthPartitionedRequests = partitioned(oauthRequests, "oauthPartitionedRequests");
|
|
376
|
+
var oauthPartitionedCodes = partitioned(oauthCodes, "oauthPartitionedCodes");
|
|
377
|
+
var oauthPartitionedDeviceAuthorizations = partitioned(oauthDeviceAuthorizations, "oauthPartitionedDeviceAuthorizations");
|
|
378
|
+
var oauthPartitionedGrants = partitioned(oauthGrants, "oauthPartitionedGrants");
|
|
379
|
+
var oauthPartitionedAccessTokens = partitioned(oauthAccessTokens, "oauthPartitionedAccessTokens");
|
|
380
|
+
var oauthPartitionedRefreshTokens = partitioned(oauthRefreshTokens, "oauthPartitionedRefreshTokens");
|
|
381
|
+
var oauthPartitionedCollections = [
|
|
382
|
+
oauthPartitionedClients,
|
|
383
|
+
oauthPartitionedRequests,
|
|
384
|
+
oauthPartitionedCodes,
|
|
385
|
+
oauthPartitionedDeviceAuthorizations,
|
|
386
|
+
oauthPartitionedGrants,
|
|
387
|
+
oauthPartitionedAccessTokens,
|
|
388
|
+
oauthPartitionedRefreshTokens,
|
|
389
|
+
oauthSigningKeys
|
|
390
|
+
];
|
|
391
|
+
// src/purge.ts
|
|
392
|
+
import { getCollection as getCollection2 } from "@softistx/mongo";
|
|
393
|
+
var DEFAULT_KEYS_PARTITION = "default";
|
|
394
|
+
var PURGED = [
|
|
395
|
+
["accessTokens", oauthPartitionedAccessTokens],
|
|
396
|
+
["refreshTokens", oauthPartitionedRefreshTokens],
|
|
397
|
+
["codes", oauthPartitionedCodes],
|
|
398
|
+
["deviceAuthorizations", oauthPartitionedDeviceAuthorizations],
|
|
399
|
+
["requests", oauthPartitionedRequests],
|
|
400
|
+
["grants", oauthPartitionedGrants],
|
|
401
|
+
["clients", oauthPartitionedClients],
|
|
402
|
+
["signingKeys", oauthSigningKeys]
|
|
403
|
+
];
|
|
404
|
+
function optionsOf(options) {
|
|
405
|
+
const where = "purgeMongoOAuthPartition";
|
|
406
|
+
if (typeof options !== "object" || options === null) {
|
|
407
|
+
throw new TypeError(`${where}: pass { partition }`);
|
|
408
|
+
}
|
|
409
|
+
const { partition, signingKeys } = options;
|
|
410
|
+
if (typeof partition !== "string" || partition === "") {
|
|
411
|
+
throw new TypeError(`${where}: partition must be a non-empty string`);
|
|
412
|
+
}
|
|
413
|
+
if (signingKeys !== undefined && typeof signingKeys !== "boolean") {
|
|
414
|
+
throw new TypeError(`${where}: signingKeys is a boolean`);
|
|
415
|
+
}
|
|
416
|
+
if (partition === DEFAULT_KEYS_PARTITION && signingKeys === undefined) {
|
|
417
|
+
throw new TypeError(`${where}: the signing keys of the partition 'default' are also those of an unpartitioned deployment; say signingKeys: true to delete them or false to keep them`);
|
|
418
|
+
}
|
|
419
|
+
return { partition, signingKeys: signingKeys ?? true };
|
|
420
|
+
}
|
|
421
|
+
async function purgeMongoOAuthPartition(db, options) {
|
|
422
|
+
if (typeof db?.collection !== "function") {
|
|
423
|
+
throw new TypeError(`purgeMongoOAuthPartition: pass the Db your app opened with @softistx/mongo (got ${db === null ? "null" : typeof db})`);
|
|
424
|
+
}
|
|
425
|
+
const { partition, signingKeys } = optionsOf(options);
|
|
426
|
+
const deleted = {
|
|
427
|
+
clients: 0,
|
|
428
|
+
requests: 0,
|
|
429
|
+
codes: 0,
|
|
430
|
+
deviceAuthorizations: 0,
|
|
431
|
+
grants: 0,
|
|
432
|
+
accessTokens: 0,
|
|
433
|
+
refreshTokens: 0,
|
|
434
|
+
signingKeys: 0
|
|
435
|
+
};
|
|
436
|
+
await run("purgePartition", async () => {
|
|
437
|
+
for (const [key, definition] of PURGED) {
|
|
438
|
+
if (key === "signingKeys" && !signingKeys)
|
|
439
|
+
continue;
|
|
440
|
+
const { deletedCount } = await getCollection2(db, definition).raw.deleteMany({ partition });
|
|
441
|
+
deleted[key] = deletedCount;
|
|
442
|
+
}
|
|
443
|
+
});
|
|
444
|
+
return deleted;
|
|
445
|
+
}
|
|
446
|
+
// src/signing-keys/options.ts
|
|
447
|
+
import { getCollection as getCollection3 } from "@softistx/mongo";
|
|
448
|
+
|
|
449
|
+
// src/signing-keys/keyring.ts
|
|
450
|
+
var KEY_BYTES = 32;
|
|
451
|
+
function assertEncryptionKey(key, where = "createMongoSigningKeys", name = "encryptionKey") {
|
|
452
|
+
if (!(key instanceof Uint8Array)) {
|
|
453
|
+
throw new TypeError(`${where}: ${name} must be a Uint8Array of ${KEY_BYTES} bytes (got ${key === null ? "null" : typeof key})`);
|
|
454
|
+
}
|
|
455
|
+
if (key.byteLength !== KEY_BYTES) {
|
|
456
|
+
throw new TypeError(`${where}: ${name} must be ${KEY_BYTES} bytes for AES-256-GCM (got ${key.byteLength})`);
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
var sameBytes = (a, b) => a.byteLength === b.byteLength && a.every((byte, i) => byte === b[i]);
|
|
460
|
+
function parseKeyring(encryptionKey, where) {
|
|
461
|
+
if (!Array.isArray(encryptionKey)) {
|
|
462
|
+
assertEncryptionKey(encryptionKey, where);
|
|
463
|
+
return [encryptionKey];
|
|
464
|
+
}
|
|
465
|
+
if (encryptionKey.length === 0) {
|
|
466
|
+
throw new TypeError(`${where}: encryptionKey must hold at least one key (got an empty list)`);
|
|
467
|
+
}
|
|
468
|
+
const keys = [];
|
|
469
|
+
for (let index = 0;index < encryptionKey.length; index++) {
|
|
470
|
+
const key = encryptionKey[index];
|
|
471
|
+
assertEncryptionKey(key, where, `encryptionKey[${index}]`);
|
|
472
|
+
const twin = keys.findIndex((seen) => sameBytes(seen, key));
|
|
473
|
+
if (twin !== -1) {
|
|
474
|
+
throw new TypeError(`${where}: encryptionKey[${index}] is the same key as encryptionKey[${twin}]`);
|
|
475
|
+
}
|
|
476
|
+
keys.push(key);
|
|
477
|
+
}
|
|
478
|
+
return keys;
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
// src/signing-keys/options.ts
|
|
482
|
+
function parseSigningKeysArguments(db, options, where) {
|
|
483
|
+
if (typeof db?.collection !== "function") {
|
|
484
|
+
throw new TypeError(`${where}: pass the Db your app opened with @softistx/mongo (got ${db === null ? "null" : typeof db})`);
|
|
485
|
+
}
|
|
486
|
+
if (typeof options !== "object" || options === null) {
|
|
487
|
+
throw new TypeError(`${where}: pass { encryptionKey }`);
|
|
488
|
+
}
|
|
489
|
+
const keyring = parseKeyring(options.encryptionKey, where);
|
|
490
|
+
const partition = options.partition ?? "default";
|
|
491
|
+
if (typeof partition !== "string" || partition === "") {
|
|
492
|
+
throw new TypeError(`${where}: partition must be a non-empty string`);
|
|
493
|
+
}
|
|
494
|
+
const keys = db.collection(getCollection3(db, oauthSigningKeys).raw.collectionName, { readPreference: "primary" });
|
|
495
|
+
return { keyring, partition, keys };
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
// src/transaction.ts
|
|
499
|
+
import { MongoError } from "mongodb";
|
|
500
|
+
var TRANSACTION_ATTEMPTS = 7;
|
|
501
|
+
var BACKOFF_MIN_MS = 5;
|
|
502
|
+
var BACKOFF_MAX_MS = 25;
|
|
503
|
+
function backoff(attempt) {
|
|
504
|
+
const jitter = BACKOFF_MIN_MS + Math.random() * (BACKOFF_MAX_MS - BACKOFF_MIN_MS);
|
|
505
|
+
return new Promise((resolve) => setTimeout(resolve, jitter * attempt));
|
|
506
|
+
}
|
|
507
|
+
async function inTransaction(db, body) {
|
|
508
|
+
return db.client.withSession(async (session) => {
|
|
509
|
+
for (let attempt = 1;; attempt += 1) {
|
|
510
|
+
session.startTransaction();
|
|
511
|
+
try {
|
|
512
|
+
const result = await body(session);
|
|
513
|
+
await commit(session);
|
|
514
|
+
return result;
|
|
515
|
+
} catch (error) {
|
|
516
|
+
await session.abortTransaction().catch(() => {
|
|
517
|
+
return;
|
|
518
|
+
});
|
|
519
|
+
const transient = error instanceof MongoError && error.hasErrorLabel("TransientTransactionError");
|
|
520
|
+
if (!transient || attempt === TRANSACTION_ATTEMPTS)
|
|
521
|
+
throw error;
|
|
522
|
+
await backoff(attempt);
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
});
|
|
526
|
+
}
|
|
527
|
+
async function commit(session) {
|
|
528
|
+
try {
|
|
529
|
+
await session.commitTransaction();
|
|
530
|
+
} catch (error) {
|
|
531
|
+
if (error instanceof MongoError && error.hasErrorLabel("UnknownTransactionCommitResult")) {
|
|
532
|
+
await session.commitTransaction();
|
|
533
|
+
return;
|
|
534
|
+
}
|
|
535
|
+
throw error;
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
// src/signing-keys/records.ts
|
|
540
|
+
import {
|
|
541
|
+
publicMembers
|
|
542
|
+
} from "@softistx/janus-oauth";
|
|
543
|
+
var date = (value) => new Date(value.getTime());
|
|
544
|
+
var dateOrNull = (value) => value === null ? null : date(value);
|
|
545
|
+
var documentId = (partition, kid) => JSON.stringify([partition, kid]);
|
|
546
|
+
async function toSigningKeyDocument(key, partition, sealer) {
|
|
547
|
+
const sealed = await sealer.seal(key.privateJwk, partition, key.kid);
|
|
548
|
+
return {
|
|
549
|
+
_id: documentId(partition, key.kid),
|
|
550
|
+
partition,
|
|
551
|
+
kid: key.kid,
|
|
552
|
+
alg: key.alg,
|
|
553
|
+
status: key.status,
|
|
554
|
+
slot: key.status,
|
|
555
|
+
publicJwk: publicMembers(key.publicJwk),
|
|
556
|
+
sealed,
|
|
557
|
+
createdAt: date(key.createdAt),
|
|
558
|
+
activateAt: date(key.activateAt),
|
|
559
|
+
activatedAt: dateOrNull(key.activatedAt),
|
|
560
|
+
retiredAt: null,
|
|
561
|
+
publishUntil: null
|
|
562
|
+
};
|
|
563
|
+
}
|
|
564
|
+
function toPublicSigningKey(doc) {
|
|
565
|
+
return {
|
|
566
|
+
kid: doc.kid,
|
|
567
|
+
alg: doc.alg,
|
|
568
|
+
status: doc.status,
|
|
569
|
+
publicJwk: publicMembers(doc.publicJwk),
|
|
570
|
+
createdAt: date(doc.createdAt),
|
|
571
|
+
activateAt: date(doc.activateAt),
|
|
572
|
+
activatedAt: dateOrNull(doc.activatedAt),
|
|
573
|
+
retiredAt: dateOrNull(doc.retiredAt),
|
|
574
|
+
publishUntil: dateOrNull(doc.publishUntil)
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
async function toSigningKey(doc, sealer) {
|
|
578
|
+
return {
|
|
579
|
+
kid: doc.kid,
|
|
580
|
+
alg: doc.alg,
|
|
581
|
+
status: doc.status,
|
|
582
|
+
publicJwk: publicMembers(doc.publicJwk),
|
|
583
|
+
privateJwk: await sealer.open(doc.sealed, doc.partition, doc.kid),
|
|
584
|
+
createdAt: date(doc.createdAt),
|
|
585
|
+
activateAt: date(doc.activateAt),
|
|
586
|
+
activatedAt: dateOrNull(doc.activatedAt),
|
|
587
|
+
retiredAt: dateOrNull(doc.retiredAt),
|
|
588
|
+
publishUntil: dateOrNull(doc.publishUntil)
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
// src/signing-keys/promote.ts
|
|
593
|
+
function promoteSigningKey({
|
|
594
|
+
db,
|
|
595
|
+
keys,
|
|
596
|
+
partition
|
|
597
|
+
}) {
|
|
598
|
+
return {
|
|
599
|
+
promote: (kid, at, publishUntil) => run("promote", () => inTransaction(db, async (session) => {
|
|
600
|
+
const id = documentId(partition, kid);
|
|
601
|
+
const next = await keys.findOne({ _id: id, status: "next" }, { session });
|
|
602
|
+
if (next === null)
|
|
603
|
+
return false;
|
|
604
|
+
await keys.updateMany({ partition, status: "current" }, {
|
|
605
|
+
$set: {
|
|
606
|
+
status: "retired",
|
|
607
|
+
slot: null,
|
|
608
|
+
retiredAt: new Date(at.getTime()),
|
|
609
|
+
publishUntil: new Date(publishUntil.getTime())
|
|
610
|
+
}
|
|
611
|
+
}, { session });
|
|
612
|
+
const promoted = await keys.updateOne({ _id: id, status: "next" }, {
|
|
613
|
+
$set: {
|
|
614
|
+
status: "current",
|
|
615
|
+
slot: "current",
|
|
616
|
+
activatedAt: new Date(at.getTime())
|
|
617
|
+
}
|
|
618
|
+
}, { session });
|
|
619
|
+
return promoted.modifiedCount === 1;
|
|
620
|
+
}), "signingKeys")
|
|
621
|
+
};
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
// src/signing-keys/read.ts
|
|
625
|
+
function published({ keys, partition }, now, projection) {
|
|
626
|
+
return keys.find({
|
|
627
|
+
partition,
|
|
628
|
+
$or: [
|
|
629
|
+
{ status: { $in: ["current", "next"] } },
|
|
630
|
+
{ status: "retired", publishUntil: { $gt: now } }
|
|
631
|
+
]
|
|
632
|
+
}, projection === undefined ? {} : { projection }).sort({ createdAt: 1, kid: 1 }).toArray();
|
|
633
|
+
}
|
|
634
|
+
function readSigningKeys(ctx) {
|
|
635
|
+
return {
|
|
636
|
+
findKeys: (now) => run("findKeys", async () => {
|
|
637
|
+
const docs = await published(ctx, now);
|
|
638
|
+
return Promise.all(docs.map((doc) => toSigningKey(doc, ctx.sealer)));
|
|
639
|
+
}, "signingKeys"),
|
|
640
|
+
findCurrentKey: () => run("findCurrentKey", async () => {
|
|
641
|
+
const doc = await ctx.keys.findOne({
|
|
642
|
+
partition: ctx.partition,
|
|
643
|
+
status: "current"
|
|
644
|
+
});
|
|
645
|
+
return doc === null ? null : toSigningKey(doc, ctx.sealer);
|
|
646
|
+
}, "signingKeys"),
|
|
647
|
+
findPublicKeys: (now) => run("findPublicKeys", async () => {
|
|
648
|
+
const docs = await published(ctx, now, { sealed: 0 });
|
|
649
|
+
return docs.map((doc) => toPublicSigningKey(doc));
|
|
650
|
+
}, "signingKeys")
|
|
651
|
+
};
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
// src/signing-keys/seal.ts
|
|
655
|
+
var IV_BYTES = 12;
|
|
656
|
+
var encoder = new TextEncoder;
|
|
657
|
+
var decoder = new TextDecoder;
|
|
658
|
+
var toBase64Url = (bytes) => Buffer.from(bytes).toString("base64url");
|
|
659
|
+
var fromBase64Url = (text) => {
|
|
660
|
+
const buffer = Buffer.from(text, "base64url");
|
|
661
|
+
return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
|
|
662
|
+
};
|
|
663
|
+
function createSealer(keys) {
|
|
664
|
+
const raws = keys.map((key) => new Uint8Array(key));
|
|
665
|
+
const imported = raws.map(() => {
|
|
666
|
+
return;
|
|
667
|
+
});
|
|
668
|
+
const key = (index) => {
|
|
669
|
+
imported[index] ??= crypto.subtle.importKey("raw", raws[index], "AES-GCM", false, ["encrypt", "decrypt"]).catch((error) => {
|
|
670
|
+
imported[index] = undefined;
|
|
671
|
+
throw error;
|
|
672
|
+
});
|
|
673
|
+
return imported[index];
|
|
674
|
+
};
|
|
675
|
+
const aad = (partition, kid) => encoder.encode(JSON.stringify([partition, kid]));
|
|
676
|
+
const openWith = async (sealed, partition, kid) => {
|
|
677
|
+
const params = {
|
|
678
|
+
name: "AES-GCM",
|
|
679
|
+
iv: fromBase64Url(sealed.iv),
|
|
680
|
+
additionalData: aad(partition, kid)
|
|
681
|
+
};
|
|
682
|
+
const data = fromBase64Url(sealed.data);
|
|
683
|
+
let last;
|
|
684
|
+
for (let index = 0;index < raws.length; index++) {
|
|
685
|
+
const cryptoKey = await key(index);
|
|
686
|
+
let plain;
|
|
687
|
+
try {
|
|
688
|
+
plain = await crypto.subtle.decrypt(params, cryptoKey, data);
|
|
689
|
+
} catch (error) {
|
|
690
|
+
if (!(error instanceof DOMException && error.name === "OperationError"))
|
|
691
|
+
throw error;
|
|
692
|
+
last = error;
|
|
693
|
+
continue;
|
|
694
|
+
}
|
|
695
|
+
return {
|
|
696
|
+
jwk: JSON.parse(decoder.decode(plain)),
|
|
697
|
+
index
|
|
698
|
+
};
|
|
699
|
+
}
|
|
700
|
+
throw last;
|
|
701
|
+
};
|
|
702
|
+
return {
|
|
703
|
+
async seal(jwk, partition, kid) {
|
|
704
|
+
const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
|
|
705
|
+
const data = await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: aad(partition, kid) }, await key(0), encoder.encode(JSON.stringify(jwk)));
|
|
706
|
+
return { iv: toBase64Url(iv), data: toBase64Url(new Uint8Array(data)) };
|
|
707
|
+
},
|
|
708
|
+
async open(sealed, partition, kid) {
|
|
709
|
+
return (await openWith(sealed, partition, kid)).jwk;
|
|
710
|
+
},
|
|
711
|
+
openWith
|
|
712
|
+
};
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
// src/signing-keys/write.ts
|
|
716
|
+
function writeSigningKeys({
|
|
717
|
+
keys,
|
|
718
|
+
partition,
|
|
719
|
+
sealer
|
|
720
|
+
}) {
|
|
721
|
+
return {
|
|
722
|
+
insertKey: (key) => run("insertKey", async () => {
|
|
723
|
+
const doc = await toSigningKeyDocument(key, partition, sealer);
|
|
724
|
+
const duplicate = await duplicateOf(keys.insertOne(doc));
|
|
725
|
+
return duplicate === null;
|
|
726
|
+
}, "signingKeys"),
|
|
727
|
+
retire: (kid, at, publishUntil) => run("retire", async () => {
|
|
728
|
+
const result = await keys.updateOne({
|
|
729
|
+
_id: documentId(partition, kid),
|
|
730
|
+
status: { $in: ["current", "next"] }
|
|
731
|
+
}, {
|
|
732
|
+
$set: {
|
|
733
|
+
status: "retired",
|
|
734
|
+
slot: null,
|
|
735
|
+
retiredAt: new Date(at.getTime()),
|
|
736
|
+
publishUntil: new Date(publishUntil.getTime())
|
|
737
|
+
}
|
|
738
|
+
});
|
|
739
|
+
return result.modifiedCount === 1;
|
|
740
|
+
}, "signingKeys")
|
|
741
|
+
};
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
// src/signing-keys/reseal.ts
|
|
745
|
+
async function resealMongoSigningKeys(db, options) {
|
|
746
|
+
const { keyring, partition, keys } = parseSigningKeysArguments(db, options, "resealMongoSigningKeys");
|
|
747
|
+
const sealer = createSealer(keyring);
|
|
748
|
+
return run("reseal", async () => {
|
|
749
|
+
let resealed = 0;
|
|
750
|
+
let current = 0;
|
|
751
|
+
let skipped = 0;
|
|
752
|
+
for (const doc of await keys.find({ partition }).toArray()) {
|
|
753
|
+
const { jwk, index } = await sealer.openWith(doc.sealed, doc.partition, doc.kid);
|
|
754
|
+
if (index === 0) {
|
|
755
|
+
current++;
|
|
756
|
+
continue;
|
|
757
|
+
}
|
|
758
|
+
const sealed = await sealer.seal(jwk, doc.partition, doc.kid);
|
|
759
|
+
const result = await keys.updateOne({
|
|
760
|
+
_id: doc._id,
|
|
761
|
+
"sealed.iv": doc.sealed.iv,
|
|
762
|
+
"sealed.data": doc.sealed.data
|
|
763
|
+
}, { $set: { sealed } });
|
|
764
|
+
if (result.modifiedCount === 1)
|
|
765
|
+
resealed++;
|
|
766
|
+
else
|
|
767
|
+
skipped++;
|
|
768
|
+
}
|
|
769
|
+
return { resealed, current, skipped };
|
|
770
|
+
}, "signingKeys");
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
// src/signing-keys/index.ts
|
|
774
|
+
function createMongoSigningKeys(db, options) {
|
|
775
|
+
const { keyring, partition, keys } = parseSigningKeysArguments(db, options, "createMongoSigningKeys");
|
|
776
|
+
const sealer = createSealer(keyring);
|
|
777
|
+
const ctx = { db, keys, partition, sealer };
|
|
778
|
+
return {
|
|
779
|
+
...readSigningKeys(ctx),
|
|
780
|
+
...writeSigningKeys(ctx),
|
|
781
|
+
...promoteSigningKey(ctx)
|
|
782
|
+
};
|
|
783
|
+
}
|
|
784
|
+
// src/store/clients.ts
|
|
785
|
+
import { oauthPageLimit } from "@softistx/janus-oauth";
|
|
786
|
+
|
|
787
|
+
// src/record-fields.ts
|
|
788
|
+
var date2 = (value) => new Date(value.getTime());
|
|
789
|
+
var dateOrNull2 = (value) => value === null ? null : date2(value);
|
|
790
|
+
var openId = (r) => ({
|
|
791
|
+
...r.nonce === undefined ? {} : { nonce: r.nonce },
|
|
792
|
+
...r.authTime === undefined ? {} : { authTime: date2(r.authTime) },
|
|
793
|
+
...r.amr === undefined ? {} : { amr: [...r.amr] },
|
|
794
|
+
...r.acr === undefined ? {} : { acr: r.acr }
|
|
795
|
+
});
|
|
796
|
+
var authenticationHints = (r) => ({
|
|
797
|
+
...r.acrValues === undefined ? {} : { acrValues: [...r.acrValues] },
|
|
798
|
+
...r.maxAge === undefined ? {} : { maxAge: r.maxAge },
|
|
799
|
+
...r.prompt === undefined ? {} : { prompt: [...r.prompt] },
|
|
800
|
+
...r.loginHint === undefined ? {} : { loginHint: r.loginHint }
|
|
801
|
+
});
|
|
802
|
+
var jkt = (r) => r.jkt === undefined ? {} : { jkt: r.jkt };
|
|
803
|
+
var dpopJkt = (r) => r.dpopJkt === undefined ? {} : { dpopJkt: r.dpopJkt };
|
|
804
|
+
var actor = (r) => r.actor === undefined ? {} : {
|
|
805
|
+
actor: {
|
|
806
|
+
sub: r.actor.sub,
|
|
807
|
+
...r.actor.clientId === undefined ? {} : { clientId: r.actor.clientId }
|
|
808
|
+
}
|
|
809
|
+
};
|
|
810
|
+
|
|
811
|
+
// src/records/clients.ts
|
|
812
|
+
var clientAuth = (r) => ({
|
|
813
|
+
...r.tokenEndpointAuthMethod === undefined ? {} : { tokenEndpointAuthMethod: r.tokenEndpointAuthMethod },
|
|
814
|
+
...r.secretHash === undefined ? {} : { secretHash: r.secretHash }
|
|
815
|
+
});
|
|
816
|
+
var grantTypes = (r) => r.grantTypes === undefined ? {} : { grantTypes: [...r.grantTypes] };
|
|
817
|
+
var requirePar = (r) => r.requirePushedAuthorizationRequests === undefined ? {} : {
|
|
818
|
+
requirePushedAuthorizationRequests: r.requirePushedAuthorizationRequests
|
|
819
|
+
};
|
|
820
|
+
var dpopBound = (r) => r.dpopBoundAccessTokens === undefined ? {} : { dpopBoundAccessTokens: r.dpopBoundAccessTokens };
|
|
821
|
+
var detailsTypes = (r) => r.authorizationDetailsTypes === undefined ? {} : { authorizationDetailsTypes: [...r.authorizationDetailsTypes] };
|
|
822
|
+
var toClientDocument = (r) => ({
|
|
823
|
+
_id: r.id,
|
|
824
|
+
name: r.name,
|
|
825
|
+
redirectUris: [...r.redirectUris],
|
|
826
|
+
source: r.source,
|
|
827
|
+
createdAt: date2(r.createdAt),
|
|
828
|
+
expiresAt: dateOrNull2(r.expiresAt),
|
|
829
|
+
...clientAuth(r),
|
|
830
|
+
...grantTypes(r),
|
|
831
|
+
...requirePar(r),
|
|
832
|
+
...dpopBound(r),
|
|
833
|
+
...detailsTypes(r)
|
|
834
|
+
});
|
|
835
|
+
var toClient = (d) => ({
|
|
836
|
+
id: d._id,
|
|
837
|
+
name: d.name,
|
|
838
|
+
redirectUris: [...d.redirectUris],
|
|
839
|
+
source: d.source,
|
|
840
|
+
createdAt: date2(d.createdAt),
|
|
841
|
+
expiresAt: dateOrNull2(d.expiresAt),
|
|
842
|
+
...clientAuth(d),
|
|
843
|
+
...grantTypes(d),
|
|
844
|
+
...requirePar(d),
|
|
845
|
+
...dpopBound(d),
|
|
846
|
+
...detailsTypes(d)
|
|
847
|
+
});
|
|
848
|
+
// src/details-field.ts
|
|
849
|
+
import { canonicalAuthorizationDetails } from "@softistx/janus-oauth";
|
|
850
|
+
var detailsToDocument = (r) => r.authorizationDetails === undefined ? {} : {
|
|
851
|
+
authorizationDetails: canonicalAuthorizationDetails(r.authorizationDetails)
|
|
852
|
+
};
|
|
853
|
+
var detailsFromDocument = (d) => {
|
|
854
|
+
if (d.authorizationDetails === undefined)
|
|
855
|
+
return {};
|
|
856
|
+
let parsed;
|
|
857
|
+
try {
|
|
858
|
+
parsed = JSON.parse(d.authorizationDetails);
|
|
859
|
+
} catch {
|
|
860
|
+
throw corrupt();
|
|
861
|
+
}
|
|
862
|
+
if (!Array.isArray(parsed) || !parsed.every((one) => typeof one === "object" && one !== null && !Array.isArray(one))) {
|
|
863
|
+
throw corrupt();
|
|
864
|
+
}
|
|
865
|
+
return { authorizationDetails: parsed };
|
|
866
|
+
};
|
|
867
|
+
var corrupt = () => new TypeError("the Mongo OAuth store holds authorization details that are not a JSON list of objects");
|
|
868
|
+
|
|
869
|
+
// src/records/grants.ts
|
|
870
|
+
var toGrantDocument = (r) => ({
|
|
871
|
+
_id: r.id,
|
|
872
|
+
userId: r.userId,
|
|
873
|
+
clientId: r.clientId,
|
|
874
|
+
resource: r.resource,
|
|
875
|
+
scopes: [...r.scopes],
|
|
876
|
+
createdAt: date2(r.createdAt),
|
|
877
|
+
updatedAt: date2(r.updatedAt),
|
|
878
|
+
revokedAt: dateOrNull2(r.revokedAt),
|
|
879
|
+
...r.bound === undefined ? {} : { bound: { type: r.bound.type, id: r.bound.id } },
|
|
880
|
+
...detailsToDocument(r)
|
|
881
|
+
});
|
|
882
|
+
var toGrant = (d) => ({
|
|
883
|
+
id: d._id,
|
|
884
|
+
userId: d.userId,
|
|
885
|
+
clientId: d.clientId,
|
|
886
|
+
resource: d.resource,
|
|
887
|
+
scopes: [...d.scopes],
|
|
888
|
+
createdAt: date2(d.createdAt),
|
|
889
|
+
updatedAt: date2(d.updatedAt),
|
|
890
|
+
revokedAt: dateOrNull2(d.revokedAt),
|
|
891
|
+
...d.bound === undefined ? {} : { bound: { type: d.bound.type, id: d.bound.id } },
|
|
892
|
+
...detailsFromDocument(d)
|
|
893
|
+
});
|
|
894
|
+
// src/records/requests.ts
|
|
895
|
+
var toRequestDocument = (r) => ({
|
|
896
|
+
_id: r.id,
|
|
897
|
+
clientId: r.clientId,
|
|
898
|
+
redirectUri: r.redirectUri,
|
|
899
|
+
resource: r.resource,
|
|
900
|
+
scopes: [...r.scopes],
|
|
901
|
+
state: r.state,
|
|
902
|
+
...r.nonce === undefined ? {} : { nonce: r.nonce },
|
|
903
|
+
...dpopJkt(r),
|
|
904
|
+
...detailsToDocument(r),
|
|
905
|
+
...authenticationHints(r),
|
|
906
|
+
codeChallenge: r.codeChallenge,
|
|
907
|
+
codeChallengeMethod: r.codeChallengeMethod,
|
|
908
|
+
createdAt: date2(r.createdAt),
|
|
909
|
+
expiresAt: date2(r.expiresAt)
|
|
910
|
+
});
|
|
911
|
+
var toRequest = (d) => ({
|
|
912
|
+
id: d._id,
|
|
913
|
+
clientId: d.clientId,
|
|
914
|
+
redirectUri: d.redirectUri,
|
|
915
|
+
resource: d.resource,
|
|
916
|
+
scopes: [...d.scopes],
|
|
917
|
+
state: d.state,
|
|
918
|
+
...d.nonce === undefined ? {} : { nonce: d.nonce },
|
|
919
|
+
...dpopJkt(d),
|
|
920
|
+
...detailsFromDocument(d),
|
|
921
|
+
...authenticationHints(d),
|
|
922
|
+
codeChallenge: d.codeChallenge,
|
|
923
|
+
codeChallengeMethod: d.codeChallengeMethod,
|
|
924
|
+
createdAt: date2(d.createdAt),
|
|
925
|
+
expiresAt: date2(d.expiresAt)
|
|
926
|
+
});
|
|
927
|
+
var toCodeDocument = (r) => ({
|
|
928
|
+
_id: r.codeHash,
|
|
929
|
+
clientId: r.clientId,
|
|
930
|
+
userId: r.userId,
|
|
931
|
+
grantId: r.grantId,
|
|
932
|
+
redirectUri: r.redirectUri,
|
|
933
|
+
resource: r.resource,
|
|
934
|
+
scopes: [...r.scopes],
|
|
935
|
+
codeChallenge: r.codeChallenge,
|
|
936
|
+
codeChallengeMethod: r.codeChallengeMethod,
|
|
937
|
+
createdAt: date2(r.createdAt),
|
|
938
|
+
expiresAt: date2(r.expiresAt),
|
|
939
|
+
consumedAt: dateOrNull2(r.consumedAt),
|
|
940
|
+
...dpopJkt(r),
|
|
941
|
+
...detailsToDocument(r),
|
|
942
|
+
...openId(r)
|
|
943
|
+
});
|
|
944
|
+
var toCode = (d) => ({
|
|
945
|
+
codeHash: d._id,
|
|
946
|
+
clientId: d.clientId,
|
|
947
|
+
userId: d.userId,
|
|
948
|
+
grantId: d.grantId,
|
|
949
|
+
redirectUri: d.redirectUri,
|
|
950
|
+
resource: d.resource,
|
|
951
|
+
scopes: [...d.scopes],
|
|
952
|
+
codeChallenge: d.codeChallenge,
|
|
953
|
+
codeChallengeMethod: d.codeChallengeMethod,
|
|
954
|
+
createdAt: date2(d.createdAt),
|
|
955
|
+
expiresAt: date2(d.expiresAt),
|
|
956
|
+
consumedAt: dateOrNull2(d.consumedAt),
|
|
957
|
+
...dpopJkt(d),
|
|
958
|
+
...detailsFromDocument(d),
|
|
959
|
+
...openId(d)
|
|
960
|
+
});
|
|
961
|
+
// src/records/tokens.ts
|
|
962
|
+
var toAccessDocument = (r) => ({
|
|
963
|
+
_id: r.tokenHash,
|
|
964
|
+
grantId: r.grantId,
|
|
965
|
+
userId: r.userId,
|
|
966
|
+
clientId: r.clientId,
|
|
967
|
+
resource: r.resource,
|
|
968
|
+
scopes: [...r.scopes],
|
|
969
|
+
createdAt: date2(r.createdAt),
|
|
970
|
+
expiresAt: date2(r.expiresAt),
|
|
971
|
+
revokedAt: dateOrNull2(r.revokedAt),
|
|
972
|
+
...jkt(r),
|
|
973
|
+
...actor(r),
|
|
974
|
+
...detailsToDocument(r),
|
|
975
|
+
...openId(r)
|
|
976
|
+
});
|
|
977
|
+
var toAccess = (d) => ({
|
|
978
|
+
tokenHash: d._id,
|
|
979
|
+
grantId: d.grantId,
|
|
980
|
+
userId: d.userId,
|
|
981
|
+
clientId: d.clientId,
|
|
982
|
+
resource: d.resource,
|
|
983
|
+
scopes: [...d.scopes],
|
|
984
|
+
createdAt: date2(d.createdAt),
|
|
985
|
+
expiresAt: date2(d.expiresAt),
|
|
986
|
+
revokedAt: dateOrNull2(d.revokedAt),
|
|
987
|
+
...jkt(d),
|
|
988
|
+
...actor(d),
|
|
989
|
+
...detailsFromDocument(d),
|
|
990
|
+
...openId(d)
|
|
991
|
+
});
|
|
992
|
+
var toRefreshDocument = (r) => ({
|
|
993
|
+
_id: r.tokenHash,
|
|
994
|
+
grantId: r.grantId,
|
|
995
|
+
userId: r.userId,
|
|
996
|
+
clientId: r.clientId,
|
|
997
|
+
resource: r.resource,
|
|
998
|
+
scopes: [...r.scopes],
|
|
999
|
+
createdAt: date2(r.createdAt),
|
|
1000
|
+
expiresAt: date2(r.expiresAt),
|
|
1001
|
+
absoluteExpiresAt: date2(r.absoluteExpiresAt),
|
|
1002
|
+
rotatedAt: dateOrNull2(r.rotatedAt),
|
|
1003
|
+
revokedAt: dateOrNull2(r.revokedAt),
|
|
1004
|
+
...jkt(r),
|
|
1005
|
+
...detailsToDocument(r),
|
|
1006
|
+
...openId(r)
|
|
1007
|
+
});
|
|
1008
|
+
var toRefresh = (d) => ({
|
|
1009
|
+
tokenHash: d._id,
|
|
1010
|
+
grantId: d.grantId,
|
|
1011
|
+
userId: d.userId,
|
|
1012
|
+
clientId: d.clientId,
|
|
1013
|
+
resource: d.resource,
|
|
1014
|
+
scopes: [...d.scopes],
|
|
1015
|
+
createdAt: date2(d.createdAt),
|
|
1016
|
+
expiresAt: date2(d.expiresAt),
|
|
1017
|
+
absoluteExpiresAt: date2(d.absoluteExpiresAt),
|
|
1018
|
+
rotatedAt: dateOrNull2(d.rotatedAt),
|
|
1019
|
+
revokedAt: dateOrNull2(d.revokedAt),
|
|
1020
|
+
...jkt(d),
|
|
1021
|
+
...detailsFromDocument(d),
|
|
1022
|
+
...openId(d)
|
|
1023
|
+
});
|
|
1024
|
+
// src/store/scope.ts
|
|
1025
|
+
function keyOf(partition, id) {
|
|
1026
|
+
return partition === null ? id : JSON.stringify([partition, id]);
|
|
1027
|
+
}
|
|
1028
|
+
function plainOf(partition, stored) {
|
|
1029
|
+
if (partition === null)
|
|
1030
|
+
return stored;
|
|
1031
|
+
const parsed = JSON.parse(stored);
|
|
1032
|
+
if (!Array.isArray(parsed) || parsed.length !== 2 || parsed[0] !== partition || typeof parsed[1] !== "string") {
|
|
1033
|
+
throw new Error("a stored _id does not belong to this partition");
|
|
1034
|
+
}
|
|
1035
|
+
return parsed[1];
|
|
1036
|
+
}
|
|
1037
|
+
function encode(partition, document) {
|
|
1038
|
+
if (partition === null)
|
|
1039
|
+
return document;
|
|
1040
|
+
return { ...document, _id: keyOf(partition, document._id), partition };
|
|
1041
|
+
}
|
|
1042
|
+
function decode(partition, document) {
|
|
1043
|
+
if (partition === null)
|
|
1044
|
+
return document;
|
|
1045
|
+
return { ...document, _id: plainOf(partition, document._id) };
|
|
1046
|
+
}
|
|
1047
|
+
function where(partition) {
|
|
1048
|
+
return partition === null ? {} : { partition };
|
|
1049
|
+
}
|
|
1050
|
+
|
|
1051
|
+
// src/store/clients.ts
|
|
1052
|
+
function clientStore({
|
|
1053
|
+
collections,
|
|
1054
|
+
partition
|
|
1055
|
+
}) {
|
|
1056
|
+
const { clients } = collections;
|
|
1057
|
+
return {
|
|
1058
|
+
upsertClient: (client) => run("upsertClient", async () => {
|
|
1059
|
+
await clients.replaceOne({ _id: keyOf(partition, client.id) }, encode(partition, toClientDocument(client)), { upsert: true });
|
|
1060
|
+
}),
|
|
1061
|
+
findClient: (id) => run("findClient", async () => {
|
|
1062
|
+
const found = await clients.findOne({ _id: keyOf(partition, id) });
|
|
1063
|
+
return found === null ? null : toClient(decode(partition, found));
|
|
1064
|
+
}),
|
|
1065
|
+
listClients: (options) => run("listClients", async () => {
|
|
1066
|
+
const limit = oauthPageLimit(options);
|
|
1067
|
+
const cursor = options?.cursor;
|
|
1068
|
+
const found = await clients.find({
|
|
1069
|
+
...where(partition),
|
|
1070
|
+
...cursor === undefined ? {} : { _id: { $gt: keyOf(partition, cursor) } }
|
|
1071
|
+
}).sort({ _id: 1 }).limit(limit + 1).toArray();
|
|
1072
|
+
const page = found.slice(0, limit).map((document) => toClient(decode(partition, document)));
|
|
1073
|
+
const last = page.at(-1);
|
|
1074
|
+
return {
|
|
1075
|
+
items: page,
|
|
1076
|
+
nextCursor: found.length > limit && last ? last.id : null
|
|
1077
|
+
};
|
|
1078
|
+
}),
|
|
1079
|
+
deleteClient: (id) => run("deleteClient", async () => {
|
|
1080
|
+
const result = await clients.deleteOne({ _id: keyOf(partition, id) });
|
|
1081
|
+
return result.deletedCount === 1;
|
|
1082
|
+
})
|
|
1083
|
+
};
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
// src/store/codes.ts
|
|
1087
|
+
function codeStore({
|
|
1088
|
+
collections,
|
|
1089
|
+
partition
|
|
1090
|
+
}) {
|
|
1091
|
+
const { codes } = collections;
|
|
1092
|
+
return {
|
|
1093
|
+
insertOAuthCode: (code) => run("insertOAuthCode", async () => {
|
|
1094
|
+
const duplicate = await duplicateOf(codes.insertOne(encode(partition, toCodeDocument(code))));
|
|
1095
|
+
if (duplicate !== null && !onId(duplicate)) {
|
|
1096
|
+
throw unexpectedDuplicate("insertOAuthCode", duplicate);
|
|
1097
|
+
}
|
|
1098
|
+
}),
|
|
1099
|
+
consumeOAuthCode: (codeHash, now) => run("consumeOAuthCode", async () => {
|
|
1100
|
+
const spent = await codes.findOneAndUpdate({
|
|
1101
|
+
_id: keyOf(partition, codeHash),
|
|
1102
|
+
consumedAt: null,
|
|
1103
|
+
expiresAt: { $gt: now }
|
|
1104
|
+
}, { $set: { consumedAt: new Date(now.getTime()) } }, { returnDocument: "before" });
|
|
1105
|
+
if (spent !== null)
|
|
1106
|
+
return { status: "consumed", code: toCode(decode(partition, spent)) };
|
|
1107
|
+
const found = await codes.findOne({ _id: keyOf(partition, codeHash) });
|
|
1108
|
+
if (found !== null && found.consumedAt !== null) {
|
|
1109
|
+
return { status: "replayed", code: toCode(decode(partition, found)) };
|
|
1110
|
+
}
|
|
1111
|
+
return { status: "absent" };
|
|
1112
|
+
})
|
|
1113
|
+
};
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
// src/store/device.ts
|
|
1117
|
+
import { StoreFailure as StoreFailure2 } from "@softistx/janus";
|
|
1118
|
+
import {
|
|
1119
|
+
OAUTH_DEVICE_SLOW_DOWN_MS
|
|
1120
|
+
} from "@softistx/janus-oauth";
|
|
1121
|
+
|
|
1122
|
+
// src/records-device.ts
|
|
1123
|
+
var toDeviceDocument = (r) => ({
|
|
1124
|
+
_id: r.deviceCodeHash,
|
|
1125
|
+
userCodeHash: r.userCodeHash,
|
|
1126
|
+
clientId: r.clientId,
|
|
1127
|
+
resource: r.resource,
|
|
1128
|
+
scopes: [...r.scopes],
|
|
1129
|
+
intervalMs: r.intervalMs,
|
|
1130
|
+
lastPolledAt: dateOrNull2(r.lastPolledAt),
|
|
1131
|
+
status: r.status,
|
|
1132
|
+
...r.userId === undefined ? {} : { userId: r.userId },
|
|
1133
|
+
...r.grantId === undefined ? {} : { grantId: r.grantId },
|
|
1134
|
+
createdAt: date2(r.createdAt),
|
|
1135
|
+
expiresAt: date2(r.expiresAt),
|
|
1136
|
+
consumedAt: dateOrNull2(r.consumedAt),
|
|
1137
|
+
...detailsToDocument(r),
|
|
1138
|
+
...openId(r)
|
|
1139
|
+
});
|
|
1140
|
+
var toDevice = (d) => ({
|
|
1141
|
+
deviceCodeHash: d._id,
|
|
1142
|
+
userCodeHash: d.userCodeHash,
|
|
1143
|
+
clientId: d.clientId,
|
|
1144
|
+
resource: d.resource,
|
|
1145
|
+
scopes: [...d.scopes],
|
|
1146
|
+
intervalMs: d.intervalMs,
|
|
1147
|
+
lastPolledAt: dateOrNull2(d.lastPolledAt),
|
|
1148
|
+
status: d.status,
|
|
1149
|
+
...d.userId === undefined ? {} : { userId: d.userId },
|
|
1150
|
+
...d.grantId === undefined ? {} : { grantId: d.grantId },
|
|
1151
|
+
createdAt: date2(d.createdAt),
|
|
1152
|
+
expiresAt: date2(d.expiresAt),
|
|
1153
|
+
consumedAt: dateOrNull2(d.consumedAt),
|
|
1154
|
+
...detailsFromDocument(d),
|
|
1155
|
+
...openId(d)
|
|
1156
|
+
});
|
|
1157
|
+
|
|
1158
|
+
// src/store/device.ts
|
|
1159
|
+
var POLL_ROUNDS = 5;
|
|
1160
|
+
function decisionFields(decision) {
|
|
1161
|
+
if (decision.status === "denied")
|
|
1162
|
+
return { status: "denied" };
|
|
1163
|
+
return {
|
|
1164
|
+
status: "approved",
|
|
1165
|
+
userId: decision.userId,
|
|
1166
|
+
grantId: decision.grantId,
|
|
1167
|
+
scopes: [...decision.scopes],
|
|
1168
|
+
...decision.authTime === undefined ? {} : { authTime: new Date(decision.authTime.getTime()) },
|
|
1169
|
+
...decision.amr === undefined ? {} : { amr: [...decision.amr] },
|
|
1170
|
+
...decision.acr === undefined ? {} : { acr: decision.acr },
|
|
1171
|
+
...detailsToDocument(decision)
|
|
1172
|
+
};
|
|
1173
|
+
}
|
|
1174
|
+
var respected = (now) => ({
|
|
1175
|
+
$expr: {
|
|
1176
|
+
$or: [
|
|
1177
|
+
{ $eq: ["$lastPolledAt", null] },
|
|
1178
|
+
{ $lte: [{ $add: ["$lastPolledAt", "$intervalMs"] }, now] }
|
|
1179
|
+
]
|
|
1180
|
+
}
|
|
1181
|
+
});
|
|
1182
|
+
function classify(partition, found, now) {
|
|
1183
|
+
if (found === null)
|
|
1184
|
+
return { status: "absent" };
|
|
1185
|
+
if (found.consumedAt !== null) {
|
|
1186
|
+
return {
|
|
1187
|
+
status: "replayed",
|
|
1188
|
+
authorization: toDevice(decode(partition, found))
|
|
1189
|
+
};
|
|
1190
|
+
}
|
|
1191
|
+
if (found.expiresAt.getTime() <= now.getTime())
|
|
1192
|
+
return { status: "expired" };
|
|
1193
|
+
if (found.status === "denied")
|
|
1194
|
+
return { status: "denied" };
|
|
1195
|
+
return;
|
|
1196
|
+
}
|
|
1197
|
+
async function poll({ collections, partition }, deviceCodeHash, now, expect) {
|
|
1198
|
+
const { devices } = collections;
|
|
1199
|
+
const mine = {
|
|
1200
|
+
_id: keyOf(partition, deviceCodeHash),
|
|
1201
|
+
clientId: expect.clientId,
|
|
1202
|
+
...expect.resource === null ? {} : { resource: expect.resource }
|
|
1203
|
+
};
|
|
1204
|
+
const live = { ...mine, consumedAt: null, expiresAt: { $gt: now } };
|
|
1205
|
+
const stamp = new Date(now.getTime());
|
|
1206
|
+
for (let round = 0;round < POLL_ROUNDS; round += 1) {
|
|
1207
|
+
const approved = await devices.findOneAndUpdate({ ...live, status: "approved", ...respected(now) }, { $set: { consumedAt: stamp, lastPolledAt: stamp } }, { returnDocument: "before" });
|
|
1208
|
+
if (approved !== null) {
|
|
1209
|
+
return {
|
|
1210
|
+
status: "approved",
|
|
1211
|
+
authorization: toDevice(decode(partition, approved))
|
|
1212
|
+
};
|
|
1213
|
+
}
|
|
1214
|
+
const pending = await devices.findOneAndUpdate({ ...live, status: "pending", ...respected(now) }, { $set: { lastPolledAt: stamp } }, { projection: { _id: 1 } });
|
|
1215
|
+
if (pending !== null)
|
|
1216
|
+
return { status: "pending" };
|
|
1217
|
+
const slowed = await devices.findOneAndUpdate({
|
|
1218
|
+
...live,
|
|
1219
|
+
status: { $in: ["pending", "approved"] },
|
|
1220
|
+
$nor: [respected(now)]
|
|
1221
|
+
}, [
|
|
1222
|
+
{
|
|
1223
|
+
$set: {
|
|
1224
|
+
intervalMs: { $add: ["$intervalMs", OAUTH_DEVICE_SLOW_DOWN_MS] },
|
|
1225
|
+
lastPolledAt: stamp
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
], { returnDocument: "after" });
|
|
1229
|
+
if (slowed !== null) {
|
|
1230
|
+
return { status: "slow_down", intervalMs: slowed.intervalMs };
|
|
1231
|
+
}
|
|
1232
|
+
const verdict = classify(partition, await devices.findOne(mine), now);
|
|
1233
|
+
if (verdict !== undefined)
|
|
1234
|
+
return verdict;
|
|
1235
|
+
}
|
|
1236
|
+
throw new StoreFailure2("oauthStore.pollDeviceAuthorization: the store could not answer", {
|
|
1237
|
+
operation: "pollDeviceAuthorization",
|
|
1238
|
+
cause: new Error(`the poll kept losing to concurrent polls of the same device code, ${POLL_ROUNDS} rounds`)
|
|
1239
|
+
});
|
|
1240
|
+
}
|
|
1241
|
+
function deviceStore(context) {
|
|
1242
|
+
const { collections, partition } = context;
|
|
1243
|
+
const { devices } = collections;
|
|
1244
|
+
return {
|
|
1245
|
+
insertDeviceAuthorization: (authorization) => run("insertDeviceAuthorization", async () => {
|
|
1246
|
+
const duplicate = await duplicateOf(devices.insertOne(encode(partition, toDeviceDocument(authorization))));
|
|
1247
|
+
if (duplicate === null)
|
|
1248
|
+
return true;
|
|
1249
|
+
if (onDeviceCode(duplicate))
|
|
1250
|
+
return false;
|
|
1251
|
+
throw unexpectedDuplicate("insertDeviceAuthorization", duplicate);
|
|
1252
|
+
}),
|
|
1253
|
+
findDeviceAuthorization: (userCodeHash) => run("findDeviceAuthorization", async () => {
|
|
1254
|
+
const found = await devices.findOne({
|
|
1255
|
+
...where(partition),
|
|
1256
|
+
userCodeHash
|
|
1257
|
+
});
|
|
1258
|
+
return found === null ? null : toDevice(decode(partition, found));
|
|
1259
|
+
}),
|
|
1260
|
+
decideDeviceAuthorization: (userCodeHash, decision, now) => run("decideDeviceAuthorization", async () => {
|
|
1261
|
+
const decided = await devices.findOneAndUpdate({
|
|
1262
|
+
...where(partition),
|
|
1263
|
+
userCodeHash,
|
|
1264
|
+
status: "pending",
|
|
1265
|
+
expiresAt: { $gt: now }
|
|
1266
|
+
}, {
|
|
1267
|
+
$set: decisionFields(decision),
|
|
1268
|
+
...decision.status === "approved" && decision.authorizationDetails === undefined ? { $unset: { authorizationDetails: "" } } : {}
|
|
1269
|
+
}, { returnDocument: "after" });
|
|
1270
|
+
return decided === null ? null : toDevice(decode(partition, decided));
|
|
1271
|
+
}),
|
|
1272
|
+
pollDeviceAuthorization: (deviceCodeHash, now, expect) => run("pollDeviceAuthorization", () => poll(context, deviceCodeHash, now, expect))
|
|
1273
|
+
};
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
// src/store/grant-reads.ts
|
|
1277
|
+
import {
|
|
1278
|
+
oauthPageLimit as oauthPageLimit2
|
|
1279
|
+
} from "@softistx/janus-oauth";
|
|
1280
|
+
async function pageOf({ collections, partition }, filter, options) {
|
|
1281
|
+
const limit = oauthPageLimit2(options);
|
|
1282
|
+
const cursor = options?.cursor;
|
|
1283
|
+
const found = await collections.grants.find({
|
|
1284
|
+
...where(partition),
|
|
1285
|
+
...filter,
|
|
1286
|
+
...cursor === undefined ? {} : { _id: { $gt: keyOf(partition, cursor) } }
|
|
1287
|
+
}).sort({ _id: 1 }).limit(limit + 1).toArray();
|
|
1288
|
+
const page = found.slice(0, limit).map((document) => toGrant(decode(partition, document)));
|
|
1289
|
+
const last = page.at(-1);
|
|
1290
|
+
return {
|
|
1291
|
+
items: page,
|
|
1292
|
+
nextCursor: found.length > limit && last ? last.id : null
|
|
1293
|
+
};
|
|
1294
|
+
}
|
|
1295
|
+
function grantReads(ctx) {
|
|
1296
|
+
const { grants } = ctx.collections;
|
|
1297
|
+
const { partition } = ctx;
|
|
1298
|
+
return {
|
|
1299
|
+
findGrant: (id) => run("findGrant", async () => {
|
|
1300
|
+
const found = await grants.findOne({ _id: keyOf(partition, id) });
|
|
1301
|
+
return found === null ? null : toGrant(decode(partition, found));
|
|
1302
|
+
}),
|
|
1303
|
+
findUserGrant: (userId, clientId, resource) => run("findUserGrant", async () => {
|
|
1304
|
+
const found = await grants.findOne({
|
|
1305
|
+
...where(partition),
|
|
1306
|
+
userId,
|
|
1307
|
+
clientId,
|
|
1308
|
+
resource
|
|
1309
|
+
});
|
|
1310
|
+
return found === null ? null : toGrant(decode(partition, found));
|
|
1311
|
+
}),
|
|
1312
|
+
listUserGrants: (userId) => run("listUserGrants", async () => {
|
|
1313
|
+
const found = await grants.find({ ...where(partition), userId }).sort({ _id: 1 }).toArray();
|
|
1314
|
+
return found.map((document) => toGrant(decode(partition, document)));
|
|
1315
|
+
}),
|
|
1316
|
+
listClientGrants: (clientId, options) => run("listClientGrants", () => pageOf(ctx, { clientId }, options)),
|
|
1317
|
+
listBoundGrants: (bound, options) => run("listBoundGrants", () => pageOf(ctx, { "bound.type": bound.type, "bound.id": bound.id }, options))
|
|
1318
|
+
};
|
|
1319
|
+
}
|
|
1320
|
+
|
|
1321
|
+
// src/store/spend-devices.ts
|
|
1322
|
+
async function spendDevices({ collections, partition }, scope, spare) {
|
|
1323
|
+
await collections.devices.updateMany({
|
|
1324
|
+
...where(partition),
|
|
1325
|
+
...scope,
|
|
1326
|
+
status: "approved",
|
|
1327
|
+
consumedAt: null,
|
|
1328
|
+
...spare === undefined ? {} : { userCodeHash: { $ne: spare } }
|
|
1329
|
+
}, { $set: { status: "denied" } });
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
// src/store/grants.ts
|
|
1333
|
+
async function closeTokens({ collections, partition }, filter, at) {
|
|
1334
|
+
const stamp = { $set: { revokedAt: new Date(at.getTime()) } };
|
|
1335
|
+
const open = { ...where(partition), ...filter, revokedAt: null };
|
|
1336
|
+
await collections.access.updateMany(open, stamp);
|
|
1337
|
+
await collections.refresh.updateMany(open, stamp);
|
|
1338
|
+
}
|
|
1339
|
+
var unsetOf = (document) => [
|
|
1340
|
+
...document.bound === undefined ? ["bound"] : [],
|
|
1341
|
+
...document.authorizationDetails === undefined ? ["authorizationDetails"] : []
|
|
1342
|
+
];
|
|
1343
|
+
function upsertGrant({ collections, partition }, grant) {
|
|
1344
|
+
const { grants } = collections;
|
|
1345
|
+
return run("upsertGrant", async () => {
|
|
1346
|
+
const key = {
|
|
1347
|
+
...where(partition),
|
|
1348
|
+
userId: grant.userId,
|
|
1349
|
+
clientId: grant.clientId,
|
|
1350
|
+
resource: grant.resource
|
|
1351
|
+
};
|
|
1352
|
+
const document = encode(partition, toGrantDocument(grant));
|
|
1353
|
+
for (let attempt = 0;; attempt += 1) {
|
|
1354
|
+
try {
|
|
1355
|
+
const stored = await grants.findOneAndUpdate(key, {
|
|
1356
|
+
$set: {
|
|
1357
|
+
scopes: document.scopes,
|
|
1358
|
+
updatedAt: document.updatedAt,
|
|
1359
|
+
revokedAt: null,
|
|
1360
|
+
...document.bound === undefined ? {} : { bound: document.bound },
|
|
1361
|
+
...document.authorizationDetails === undefined ? {} : { authorizationDetails: document.authorizationDetails }
|
|
1362
|
+
},
|
|
1363
|
+
$setOnInsert: {
|
|
1364
|
+
_id: document._id,
|
|
1365
|
+
createdAt: document.createdAt
|
|
1366
|
+
},
|
|
1367
|
+
...unsetOf(document).length === 0 ? {} : {
|
|
1368
|
+
$unset: Object.fromEntries(unsetOf(document).map((k) => [k, ""]))
|
|
1369
|
+
}
|
|
1370
|
+
}, { upsert: true, returnDocument: "after" });
|
|
1371
|
+
if (stored === null) {
|
|
1372
|
+
throw new Error("the upsert answered no document");
|
|
1373
|
+
}
|
|
1374
|
+
return toGrant(decode(partition, stored));
|
|
1375
|
+
} catch (error) {
|
|
1376
|
+
const duplicate = await duplicateOf(Promise.reject(error));
|
|
1377
|
+
if (duplicate === null)
|
|
1378
|
+
throw error;
|
|
1379
|
+
if (attempt === 0 && onKey(duplicate))
|
|
1380
|
+
continue;
|
|
1381
|
+
throw unexpectedDuplicate("upsertGrant", duplicate);
|
|
1382
|
+
}
|
|
1383
|
+
}
|
|
1384
|
+
});
|
|
1385
|
+
}
|
|
1386
|
+
function revokeGrant(ctx, id, at, spare) {
|
|
1387
|
+
return run("revokeGrant", async () => {
|
|
1388
|
+
const result = await ctx.collections.grants.updateOne({ _id: keyOf(ctx.partition, id) }, [{ $set: { revokedAt: { $ifNull: ["$revokedAt", at] } } }]);
|
|
1389
|
+
if (result.matchedCount === 1)
|
|
1390
|
+
await closeTokens(ctx, { grantId: id }, at);
|
|
1391
|
+
await spendDevices(ctx, { grantId: id }, spare);
|
|
1392
|
+
return result.matchedCount === 1;
|
|
1393
|
+
});
|
|
1394
|
+
}
|
|
1395
|
+
function revokeUserGrants(ctx, userId, at) {
|
|
1396
|
+
return run("revokeUserGrants", async () => {
|
|
1397
|
+
const result = await ctx.collections.grants.updateMany({ ...where(ctx.partition), userId, revokedAt: null }, { $set: { revokedAt: new Date(at.getTime()) } });
|
|
1398
|
+
await closeTokens(ctx, { userId }, at);
|
|
1399
|
+
await spendDevices(ctx, { userId });
|
|
1400
|
+
return result.modifiedCount;
|
|
1401
|
+
});
|
|
1402
|
+
}
|
|
1403
|
+
function revokeClientGrants(ctx, clientId, at) {
|
|
1404
|
+
return run("revokeClientGrants", async () => {
|
|
1405
|
+
const result = await ctx.collections.grants.updateMany({ ...where(ctx.partition), clientId, revokedAt: null }, { $set: { revokedAt: new Date(at.getTime()) } });
|
|
1406
|
+
await closeTokens(ctx, { clientId }, at);
|
|
1407
|
+
await spendDevices(ctx, { clientId });
|
|
1408
|
+
return result.modifiedCount;
|
|
1409
|
+
});
|
|
1410
|
+
}
|
|
1411
|
+
function revokeGrantsByResource(ctx, selector, at, dryRun) {
|
|
1412
|
+
const { grants, access, refresh } = ctx.collections;
|
|
1413
|
+
const { partition } = ctx;
|
|
1414
|
+
const { equals, differs } = selector ?? {};
|
|
1415
|
+
if (equals === undefined === (differs === undefined) || typeof (equals ?? differs) !== "string") {
|
|
1416
|
+
return Promise.reject(new TypeError("revokeGrantsByResource: pass exactly one of { equals } or { differs }, as a string"));
|
|
1417
|
+
}
|
|
1418
|
+
return run("revokeGrantsByResource", async () => {
|
|
1419
|
+
const resource = selector.equals !== undefined ? selector.equals : { $ne: selector.differs };
|
|
1420
|
+
const open = { ...where(partition), resource, revokedAt: null };
|
|
1421
|
+
if (dryRun) {
|
|
1422
|
+
return {
|
|
1423
|
+
grants: await grants.countDocuments(open),
|
|
1424
|
+
accessTokens: await access.countDocuments(open),
|
|
1425
|
+
refreshTokens: await refresh.countDocuments(open)
|
|
1426
|
+
};
|
|
1427
|
+
}
|
|
1428
|
+
const stamp = { $set: { revokedAt: new Date(at.getTime()) } };
|
|
1429
|
+
const revokedGrants = await grants.updateMany(open, stamp);
|
|
1430
|
+
const revokedAccess = await access.updateMany(open, stamp);
|
|
1431
|
+
const revokedRefresh = await refresh.updateMany(open, stamp);
|
|
1432
|
+
await spendDevices(ctx, { resource });
|
|
1433
|
+
return {
|
|
1434
|
+
grants: revokedGrants.modifiedCount,
|
|
1435
|
+
accessTokens: revokedAccess.modifiedCount,
|
|
1436
|
+
refreshTokens: revokedRefresh.modifiedCount
|
|
1437
|
+
};
|
|
1438
|
+
});
|
|
1439
|
+
}
|
|
1440
|
+
function deleteUserGrants({ collections, partition }, userId) {
|
|
1441
|
+
const { grants, access, refresh, codes, devices } = collections;
|
|
1442
|
+
return run("deleteUserGrants", async () => {
|
|
1443
|
+
const mine = { ...where(partition), userId };
|
|
1444
|
+
await access.deleteMany(mine);
|
|
1445
|
+
await refresh.deleteMany(mine);
|
|
1446
|
+
await codes.deleteMany(mine);
|
|
1447
|
+
await devices.deleteMany(mine);
|
|
1448
|
+
const result = await grants.deleteMany(mine);
|
|
1449
|
+
return result.deletedCount;
|
|
1450
|
+
});
|
|
1451
|
+
}
|
|
1452
|
+
function grantStore(ctx) {
|
|
1453
|
+
return {
|
|
1454
|
+
upsertGrant: (grant) => upsertGrant(ctx, grant),
|
|
1455
|
+
...grantReads(ctx),
|
|
1456
|
+
revokeClientGrants: (clientId, at) => revokeClientGrants(ctx, clientId, at),
|
|
1457
|
+
revokeGrant: (id, at, options) => revokeGrant(ctx, id, at, options?.spare),
|
|
1458
|
+
revokeUserGrants: (userId, at) => revokeUserGrants(ctx, userId, at),
|
|
1459
|
+
revokeGrantsByResource: (selector, at, options) => revokeGrantsByResource(ctx, selector, at, options?.dryRun === true),
|
|
1460
|
+
deleteUserGrants: (userId) => deleteUserGrants(ctx, userId)
|
|
1461
|
+
};
|
|
1462
|
+
}
|
|
1463
|
+
|
|
1464
|
+
// src/store/open.ts
|
|
1465
|
+
import { getCollection as getCollection4 } from "@softistx/mongo";
|
|
1466
|
+
function primary(db, name) {
|
|
1467
|
+
return db.collection(name, { readPreference: "primary" });
|
|
1468
|
+
}
|
|
1469
|
+
function openCollections(db, partitioned) {
|
|
1470
|
+
const names = partitioned ? {
|
|
1471
|
+
clients: oauthPartitionedClients,
|
|
1472
|
+
requests: oauthPartitionedRequests,
|
|
1473
|
+
codes: oauthPartitionedCodes,
|
|
1474
|
+
devices: oauthPartitionedDeviceAuthorizations,
|
|
1475
|
+
grants: oauthPartitionedGrants,
|
|
1476
|
+
access: oauthPartitionedAccessTokens,
|
|
1477
|
+
refresh: oauthPartitionedRefreshTokens
|
|
1478
|
+
} : {
|
|
1479
|
+
clients: oauthClients,
|
|
1480
|
+
requests: oauthRequests,
|
|
1481
|
+
codes: oauthCodes,
|
|
1482
|
+
devices: oauthDeviceAuthorizations,
|
|
1483
|
+
grants: oauthGrants,
|
|
1484
|
+
access: oauthAccessTokens,
|
|
1485
|
+
refresh: oauthRefreshTokens
|
|
1486
|
+
};
|
|
1487
|
+
const open = (definition) => primary(db, getCollection4(db, definition).raw.collectionName);
|
|
1488
|
+
return {
|
|
1489
|
+
clients: open(names.clients),
|
|
1490
|
+
requests: open(names.requests),
|
|
1491
|
+
codes: open(names.codes),
|
|
1492
|
+
devices: open(names.devices),
|
|
1493
|
+
grants: open(names.grants),
|
|
1494
|
+
access: open(names.access),
|
|
1495
|
+
refresh: open(names.refresh)
|
|
1496
|
+
};
|
|
1497
|
+
}
|
|
1498
|
+
|
|
1499
|
+
// src/store/requests.ts
|
|
1500
|
+
function requestStore({
|
|
1501
|
+
collections,
|
|
1502
|
+
partition
|
|
1503
|
+
}) {
|
|
1504
|
+
const { requests } = collections;
|
|
1505
|
+
return {
|
|
1506
|
+
insertAuthorizationRequest: (request) => run("insertAuthorizationRequest", async () => {
|
|
1507
|
+
const duplicate = await duplicateOf(requests.insertOne(encode(partition, toRequestDocument(request))));
|
|
1508
|
+
if (duplicate !== null && !onId(duplicate)) {
|
|
1509
|
+
throw unexpectedDuplicate("insertAuthorizationRequest", duplicate);
|
|
1510
|
+
}
|
|
1511
|
+
}),
|
|
1512
|
+
findAuthorizationRequest: (id) => run("findAuthorizationRequest", async () => {
|
|
1513
|
+
const found = await requests.findOne({ _id: keyOf(partition, id) });
|
|
1514
|
+
return found === null ? null : toRequest(decode(partition, found));
|
|
1515
|
+
}),
|
|
1516
|
+
consumeAuthorizationRequest: (id, now) => run("consumeAuthorizationRequest", async () => {
|
|
1517
|
+
const taken = await requests.findOneAndDelete({
|
|
1518
|
+
_id: keyOf(partition, id)
|
|
1519
|
+
});
|
|
1520
|
+
if (taken === null)
|
|
1521
|
+
return null;
|
|
1522
|
+
return taken.expiresAt.getTime() > now.getTime() ? toRequest(decode(partition, taken)) : null;
|
|
1523
|
+
})
|
|
1524
|
+
};
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
// src/store/rotate.ts
|
|
1528
|
+
function rotateStore(context, db) {
|
|
1529
|
+
return {
|
|
1530
|
+
rotateRefreshToken: (currentHash, next, now) => run("rotateRefreshToken", () => inTransaction(db, (session) => rotate(context, session, currentHash, next, now)))
|
|
1531
|
+
};
|
|
1532
|
+
}
|
|
1533
|
+
async function rotate({ collections, partition }, session, currentHash, next, now) {
|
|
1534
|
+
const { access, refresh } = collections;
|
|
1535
|
+
const before = await refresh.findOneAndUpdate({
|
|
1536
|
+
_id: keyOf(partition, currentHash),
|
|
1537
|
+
revokedAt: null,
|
|
1538
|
+
rotatedAt: null,
|
|
1539
|
+
expiresAt: { $gt: now }
|
|
1540
|
+
}, { $set: { rotatedAt: new Date(now.getTime()) } }, { returnDocument: "before", session });
|
|
1541
|
+
if (before === null) {
|
|
1542
|
+
const found = await refresh.findOne({ _id: keyOf(partition, currentHash) }, { session });
|
|
1543
|
+
if (found === null || found.revokedAt !== null) {
|
|
1544
|
+
return { status: "absent" };
|
|
1545
|
+
}
|
|
1546
|
+
if (found.rotatedAt !== null) {
|
|
1547
|
+
return {
|
|
1548
|
+
status: "reused",
|
|
1549
|
+
previous: toRefresh(decode(partition, found))
|
|
1550
|
+
};
|
|
1551
|
+
}
|
|
1552
|
+
return { status: "absent" };
|
|
1553
|
+
}
|
|
1554
|
+
const { _id: accessId, ...accessFields } = encode(partition, toAccessDocument(next.accessToken));
|
|
1555
|
+
await access.updateOne({ _id: accessId }, { $setOnInsert: accessFields }, { upsert: true, session });
|
|
1556
|
+
const { _id: refreshId, ...refreshFields } = encode(partition, toRefreshDocument(next.refreshToken));
|
|
1557
|
+
await refresh.updateOne({ _id: refreshId }, { $setOnInsert: refreshFields }, { upsert: true, session });
|
|
1558
|
+
return { status: "rotated", previous: toRefresh(decode(partition, before)) };
|
|
1559
|
+
}
|
|
1560
|
+
|
|
1561
|
+
// src/store/tokens.ts
|
|
1562
|
+
function tokenStore({
|
|
1563
|
+
collections,
|
|
1564
|
+
partition
|
|
1565
|
+
}) {
|
|
1566
|
+
const { access, refresh } = collections;
|
|
1567
|
+
return {
|
|
1568
|
+
insertAccessToken: (token) => run("insertAccessToken", async () => {
|
|
1569
|
+
const duplicate = await duplicateOf(access.insertOne(encode(partition, toAccessDocument(token))));
|
|
1570
|
+
if (duplicate !== null && !onId(duplicate)) {
|
|
1571
|
+
throw unexpectedDuplicate("insertAccessToken", duplicate);
|
|
1572
|
+
}
|
|
1573
|
+
}),
|
|
1574
|
+
findAccessToken: (tokenHash) => run("findAccessToken", async () => {
|
|
1575
|
+
const found = await access.findOne({
|
|
1576
|
+
_id: keyOf(partition, tokenHash)
|
|
1577
|
+
});
|
|
1578
|
+
return found === null ? null : toAccess(decode(partition, found));
|
|
1579
|
+
}),
|
|
1580
|
+
revokeAccessToken: (tokenHash, at) => run("revokeAccessToken", async () => {
|
|
1581
|
+
const result = await access.updateOne({ _id: keyOf(partition, tokenHash) }, [{ $set: { revokedAt: { $ifNull: ["$revokedAt", at] } } }]);
|
|
1582
|
+
return result.matchedCount === 1;
|
|
1583
|
+
}),
|
|
1584
|
+
insertRefreshToken: (token) => run("insertRefreshToken", async () => {
|
|
1585
|
+
const duplicate = await duplicateOf(refresh.insertOne(encode(partition, toRefreshDocument(token))));
|
|
1586
|
+
if (duplicate !== null && !onId(duplicate)) {
|
|
1587
|
+
throw unexpectedDuplicate("insertRefreshToken", duplicate);
|
|
1588
|
+
}
|
|
1589
|
+
}),
|
|
1590
|
+
findRefreshToken: (tokenHash) => run("findRefreshToken", async () => {
|
|
1591
|
+
const found = await refresh.findOne({
|
|
1592
|
+
_id: keyOf(partition, tokenHash)
|
|
1593
|
+
});
|
|
1594
|
+
return found === null ? null : toRefresh(decode(partition, found));
|
|
1595
|
+
}),
|
|
1596
|
+
revokeRefreshToken: (tokenHash, at) => run("revokeRefreshToken", async () => {
|
|
1597
|
+
const result = await refresh.updateOne({ _id: keyOf(partition, tokenHash) }, [{ $set: { revokedAt: { $ifNull: ["$revokedAt", at] } } }]);
|
|
1598
|
+
return result.matchedCount === 1;
|
|
1599
|
+
})
|
|
1600
|
+
};
|
|
1601
|
+
}
|
|
1602
|
+
|
|
1603
|
+
// src/store/index.ts
|
|
1604
|
+
function createMongoOAuth(db, options = {}) {
|
|
1605
|
+
if (typeof db?.collection !== "function") {
|
|
1606
|
+
throw new TypeError(`createMongoOAuth: pass the Db your app opened with @softistx/mongo (got ${db === null ? "null" : typeof db})`);
|
|
1607
|
+
}
|
|
1608
|
+
if (typeof options !== "object" || options === null) {
|
|
1609
|
+
throw new TypeError("createMongoOAuth: options must be an object");
|
|
1610
|
+
}
|
|
1611
|
+
const partition = "partition" in options ? options.partition : null;
|
|
1612
|
+
if ("partition" in options && (typeof partition !== "string" || partition === "")) {
|
|
1613
|
+
throw new TypeError("createMongoOAuth: partition must be a non-empty string");
|
|
1614
|
+
}
|
|
1615
|
+
const context = {
|
|
1616
|
+
collections: openCollections(db, partition !== null),
|
|
1617
|
+
partition
|
|
1618
|
+
};
|
|
1619
|
+
return {
|
|
1620
|
+
...clientStore(context),
|
|
1621
|
+
...requestStore(context),
|
|
1622
|
+
...codeStore(context),
|
|
1623
|
+
...deviceStore(context),
|
|
1624
|
+
...grantStore(context),
|
|
1625
|
+
...tokenStore(context),
|
|
1626
|
+
...rotateStore(context, db)
|
|
1627
|
+
};
|
|
1628
|
+
}
|
|
1629
|
+
// src/sync.ts
|
|
1630
|
+
import {
|
|
1631
|
+
syncCollections
|
|
1632
|
+
} from "@softistx/mongo";
|
|
1633
|
+
function syncMongoOAuth(db, options) {
|
|
1634
|
+
return syncCollections(db, oauthCollections, options);
|
|
1635
|
+
}
|
|
1636
|
+
function syncMongoOAuthPartitioned(db, options) {
|
|
1637
|
+
return syncCollections(db, [...oauthPartitionedCollections, oauthDpopReplay], options);
|
|
1638
|
+
}
|
|
1639
|
+
export {
|
|
1640
|
+
CLIENT_GRACE_SECONDS,
|
|
1641
|
+
CODE_GRACE_SECONDS,
|
|
1642
|
+
DEVICE_GRACE_SECONDS,
|
|
1643
|
+
createMongoDPoPReplayCache,
|
|
1644
|
+
createMongoOAuth,
|
|
1645
|
+
createMongoSigningKeys,
|
|
1646
|
+
oauthAccessTokens,
|
|
1647
|
+
oauthClients,
|
|
1648
|
+
oauthCodes,
|
|
1649
|
+
oauthCollections,
|
|
1650
|
+
oauthDeviceAuthorizations,
|
|
1651
|
+
oauthDpopReplay,
|
|
1652
|
+
oauthGrants,
|
|
1653
|
+
oauthPartitionedAccessTokens,
|
|
1654
|
+
oauthPartitionedClients,
|
|
1655
|
+
oauthPartitionedCodes,
|
|
1656
|
+
oauthPartitionedCollections,
|
|
1657
|
+
oauthPartitionedDeviceAuthorizations,
|
|
1658
|
+
oauthPartitionedGrants,
|
|
1659
|
+
oauthPartitionedRefreshTokens,
|
|
1660
|
+
oauthPartitionedRequests,
|
|
1661
|
+
oauthRefreshTokens,
|
|
1662
|
+
oauthRequests,
|
|
1663
|
+
oauthSigningKeys,
|
|
1664
|
+
purgeMongoOAuthPartition,
|
|
1665
|
+
resealMongoSigningKeys,
|
|
1666
|
+
syncMongoOAuth,
|
|
1667
|
+
syncMongoOAuthPartitioned
|
|
1668
|
+
};
|
|
1669
|
+
|
|
1670
|
+
//# debugId=0530A846CFA3262D64756E2164756E21
|
|
1671
|
+
//# sourceMappingURL=index.js.map
|