@softistx/janus-graphql 0.0.0-stage → 0.30.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (207) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +716 -2
  3. package/dist/api-keys/index.d.ts +11 -0
  4. package/dist/api-keys/index.d.ts.map +1 -0
  5. package/dist/api-keys/resolvers/deps.d.ts +39 -0
  6. package/dist/api-keys/resolvers/deps.d.ts.map +1 -0
  7. package/dist/api-keys/resolvers/index.d.ts +39 -0
  8. package/dist/api-keys/resolvers/index.d.ts.map +1 -0
  9. package/dist/api-keys/resolvers/list.d.ts +16 -0
  10. package/dist/api-keys/resolvers/list.d.ts.map +1 -0
  11. package/dist/api-keys/resolvers/manage.d.ts +17 -0
  12. package/dist/api-keys/resolvers/manage.d.ts.map +1 -0
  13. package/dist/api-keys/sdl.d.ts +14 -0
  14. package/dist/api-keys/sdl.d.ts.map +1 -0
  15. package/dist/api-keys/shape.d.ts +38 -0
  16. package/dist/api-keys/shape.d.ts.map +1 -0
  17. package/dist/api-keys/types.d.ts +149 -0
  18. package/dist/api-keys/types.d.ts.map +1 -0
  19. package/dist/avatar/index.d.ts +32 -0
  20. package/dist/avatar/index.d.ts.map +1 -0
  21. package/dist/avatar/resolvers.d.ts +41 -0
  22. package/dist/avatar/resolvers.d.ts.map +1 -0
  23. package/dist/avatar/sdl.d.ts +16 -0
  24. package/dist/avatar/sdl.d.ts.map +1 -0
  25. package/dist/bad-input.d.ts +17 -0
  26. package/dist/bad-input.d.ts.map +1 -0
  27. package/dist/connection/connection.d.ts +36 -0
  28. package/dist/connection/connection.d.ts.map +1 -0
  29. package/dist/connection/credential.d.ts +34 -0
  30. package/dist/connection/credential.d.ts.map +1 -0
  31. package/dist/connection/types.d.ts +61 -0
  32. package/dist/connection/types.d.ts.map +1 -0
  33. package/dist/context/create.d.ts +32 -0
  34. package/dist/context/create.d.ts.map +1 -0
  35. package/dist/context/index.d.ts +9 -0
  36. package/dist/context/index.d.ts.map +1 -0
  37. package/dist/context/registry.d.ts +72 -0
  38. package/dist/context/registry.d.ts.map +1 -0
  39. package/dist/context/resolve.d.ts +20 -0
  40. package/dist/context/resolve.d.ts.map +1 -0
  41. package/dist/device.d.ts +28 -0
  42. package/dist/device.d.ts.map +1 -0
  43. package/dist/directives/apply.d.ts +51 -0
  44. package/dist/directives/apply.d.ts.map +1 -0
  45. package/dist/directives/guard.d.ts +22 -0
  46. package/dist/directives/guard.d.ts.map +1 -0
  47. package/dist/directives/permission/enforce.d.ts +24 -0
  48. package/dist/directives/permission/enforce.d.ts.map +1 -0
  49. package/dist/directives/permission/model.d.ts +35 -0
  50. package/dist/directives/permission/model.d.ts.map +1 -0
  51. package/dist/directives/permission/path.d.ts +31 -0
  52. package/dist/directives/permission/path.d.ts.map +1 -0
  53. package/dist/directives/permission/validate.d.ts +42 -0
  54. package/dist/directives/permission/validate.d.ts.map +1 -0
  55. package/dist/directives/read.d.ts +43 -0
  56. package/dist/directives/read.d.ts.map +1 -0
  57. package/dist/directives/validate.d.ts +39 -0
  58. package/dist/directives/validate.d.ts.map +1 -0
  59. package/dist/directives/words.d.ts +7 -0
  60. package/dist/directives/words.d.ts.map +1 -0
  61. package/dist/errors/denial.d.ts +6 -0
  62. package/dist/errors/denial.d.ts.map +1 -0
  63. package/dist/errors/index.d.ts +12 -0
  64. package/dist/errors/index.d.ts.map +1 -0
  65. package/dist/errors/janus-error.d.ts +20 -0
  66. package/dist/errors/janus-error.d.ts.map +1 -0
  67. package/dist/errors/mask.d.ts +69 -0
  68. package/dist/errors/mask.d.ts.map +1 -0
  69. package/dist/fresh.d.ts +44 -0
  70. package/dist/fresh.d.ts.map +1 -0
  71. package/dist/helpers.d.ts +56 -0
  72. package/dist/helpers.d.ts.map +1 -0
  73. package/dist/index.d.ts +86 -0
  74. package/dist/index.d.ts.map +1 -0
  75. package/dist/index.js +3393 -0
  76. package/dist/index.js.map +75 -0
  77. package/dist/invitations/index.d.ts +12 -0
  78. package/dist/invitations/index.d.ts.map +1 -0
  79. package/dist/invitations/resolvers/anonymous.d.ts +11 -0
  80. package/dist/invitations/resolvers/anonymous.d.ts.map +1 -0
  81. package/dist/invitations/resolvers/deps.d.ts +38 -0
  82. package/dist/invitations/resolvers/deps.d.ts.map +1 -0
  83. package/dist/invitations/resolvers/index.d.ts +37 -0
  84. package/dist/invitations/resolvers/index.d.ts.map +1 -0
  85. package/dist/invitations/resolvers/owner.d.ts +17 -0
  86. package/dist/invitations/resolvers/owner.d.ts.map +1 -0
  87. package/dist/invitations/sdl/accept.d.ts +7 -0
  88. package/dist/invitations/sdl/accept.d.ts.map +1 -0
  89. package/dist/invitations/sdl/index.d.ts +14 -0
  90. package/dist/invitations/sdl/index.d.ts.map +1 -0
  91. package/dist/invitations/sdl/owner.d.ts +8 -0
  92. package/dist/invitations/sdl/owner.d.ts.map +1 -0
  93. package/dist/invitations/shape.d.ts +63 -0
  94. package/dist/invitations/shape.d.ts.map +1 -0
  95. package/dist/invitations/types/index.d.ts +5 -0
  96. package/dist/invitations/types/index.d.ts.map +1 -0
  97. package/dist/invitations/types/options.d.ts +104 -0
  98. package/dist/invitations/types/options.d.ts.map +1 -0
  99. package/dist/invitations/types/out.d.ts +136 -0
  100. package/dist/invitations/types/out.d.ts.map +1 -0
  101. package/dist/invitations/types/surface.d.ts +18 -0
  102. package/dist/invitations/types/surface.d.ts.map +1 -0
  103. package/dist/map-code.d.ts +10 -0
  104. package/dist/map-code.d.ts.map +1 -0
  105. package/dist/mask-error.d.ts +18 -0
  106. package/dist/mask-error.d.ts.map +1 -0
  107. package/dist/memo.d.ts +16 -0
  108. package/dist/memo.d.ts.map +1 -0
  109. package/dist/options.d.ts +17 -0
  110. package/dist/options.d.ts.map +1 -0
  111. package/dist/passkeys/deps.d.ts +23 -0
  112. package/dist/passkeys/deps.d.ts.map +1 -0
  113. package/dist/passkeys/first-factor.types.d.ts +38 -0
  114. package/dist/passkeys/first-factor.types.d.ts.map +1 -0
  115. package/dist/passkeys/index.d.ts +14 -0
  116. package/dist/passkeys/index.d.ts.map +1 -0
  117. package/dist/passkeys/resolvers.d.ts +23 -0
  118. package/dist/passkeys/resolvers.d.ts.map +1 -0
  119. package/dist/passkeys/sdl.d.ts +14 -0
  120. package/dist/passkeys/sdl.d.ts.map +1 -0
  121. package/dist/passkeys/shape.d.ts +14 -0
  122. package/dist/passkeys/shape.d.ts.map +1 -0
  123. package/dist/passkeys/sign-in.resolvers.d.ts +19 -0
  124. package/dist/passkeys/sign-in.resolvers.d.ts.map +1 -0
  125. package/dist/passkeys/sign-in.sdl.d.ts +16 -0
  126. package/dist/passkeys/sign-in.sdl.d.ts.map +1 -0
  127. package/dist/passkeys/types.d.ts +193 -0
  128. package/dist/passkeys/types.d.ts.map +1 -0
  129. package/dist/plugin.d.ts +59 -0
  130. package/dist/plugin.d.ts.map +1 -0
  131. package/dist/renewal.d.ts +51 -0
  132. package/dist/renewal.d.ts.map +1 -0
  133. package/dist/report.d.ts +29 -0
  134. package/dist/report.d.ts.map +1 -0
  135. package/dist/sdl.d.ts +12 -0
  136. package/dist/sdl.d.ts.map +1 -0
  137. package/dist/second-factor/index.d.ts +12 -0
  138. package/dist/second-factor/index.d.ts.map +1 -0
  139. package/dist/second-factor/resolvers/deps.d.ts +39 -0
  140. package/dist/second-factor/resolvers/deps.d.ts.map +1 -0
  141. package/dist/second-factor/resolvers/index.d.ts +39 -0
  142. package/dist/second-factor/resolvers/index.d.ts.map +1 -0
  143. package/dist/second-factor/resolvers/sign-in.d.ts +10 -0
  144. package/dist/second-factor/resolvers/sign-in.d.ts.map +1 -0
  145. package/dist/second-factor/resolvers/status.d.ts +10 -0
  146. package/dist/second-factor/resolvers/status.d.ts.map +1 -0
  147. package/dist/second-factor/resolvers/step-up.d.ts +16 -0
  148. package/dist/second-factor/resolvers/step-up.d.ts.map +1 -0
  149. package/dist/second-factor/resolvers/writes.d.ts +19 -0
  150. package/dist/second-factor/resolvers/writes.d.ts.map +1 -0
  151. package/dist/second-factor/sdl.d.ts +14 -0
  152. package/dist/second-factor/sdl.d.ts.map +1 -0
  153. package/dist/second-factor/shape.d.ts +18 -0
  154. package/dist/second-factor/shape.d.ts.map +1 -0
  155. package/dist/second-factor/types/index.d.ts +5 -0
  156. package/dist/second-factor/types/index.d.ts.map +1 -0
  157. package/dist/second-factor/types/options.d.ts +61 -0
  158. package/dist/second-factor/types/options.d.ts.map +1 -0
  159. package/dist/second-factor/types/out.d.ts +84 -0
  160. package/dist/second-factor/types/out.d.ts.map +1 -0
  161. package/dist/second-factor/types/surface.d.ts +89 -0
  162. package/dist/second-factor/types/surface.d.ts.map +1 -0
  163. package/dist/social/index.d.ts +10 -0
  164. package/dist/social/index.d.ts.map +1 -0
  165. package/dist/social/resolvers.d.ts +25 -0
  166. package/dist/social/resolvers.d.ts.map +1 -0
  167. package/dist/social/sdl.d.ts +13 -0
  168. package/dist/social/sdl.d.ts.map +1 -0
  169. package/dist/social/shape.d.ts +11 -0
  170. package/dist/social/shape.d.ts.map +1 -0
  171. package/dist/social/types.d.ts +160 -0
  172. package/dist/social/types.d.ts.map +1 -0
  173. package/dist/surface/api.d.ts +16 -0
  174. package/dist/surface/api.d.ts.map +1 -0
  175. package/dist/surface/request.d.ts +10 -0
  176. package/dist/surface/request.d.ts.map +1 -0
  177. package/dist/surface/signed-in.d.ts +30 -0
  178. package/dist/surface/signed-in.d.ts.map +1 -0
  179. package/dist/types.d.ts +117 -0
  180. package/dist/types.d.ts.map +1 -0
  181. package/dist/wiring.d.ts +56 -0
  182. package/dist/wiring.d.ts.map +1 -0
  183. package/docs/README.md +26 -0
  184. package/docs/guide/api-keys.md +365 -0
  185. package/docs/guide/avatars.md +129 -0
  186. package/docs/guide/context.md +371 -0
  187. package/docs/guide/directives.md +371 -0
  188. package/docs/guide/errors.md +318 -0
  189. package/docs/guide/federation.md +71 -0
  190. package/docs/guide/invitations.md +269 -0
  191. package/docs/guide/passkeys.md +207 -0
  192. package/docs/guide/second-factor.md +238 -0
  193. package/docs/guide/social.md +190 -0
  194. package/docs/guide/step-up.md +208 -0
  195. package/docs/guide/subscriptions.md +255 -0
  196. package/docs/guide/telemetry.md +45 -0
  197. package/docs/roadmap.md +124 -0
  198. package/docs/troubleshooting.md +1265 -0
  199. package/graphql/janus-api-keys.graphqls +237 -0
  200. package/graphql/janus-avatar.graphqls +19 -0
  201. package/graphql/janus-invitations.graphqls +280 -0
  202. package/graphql/janus-passkey-sign-in.graphqls +40 -0
  203. package/graphql/janus-passkeys.graphqls +134 -0
  204. package/graphql/janus-second-factor.graphqls +199 -0
  205. package/graphql/janus-social.graphqls +155 -0
  206. package/graphql/janus.graphqls +44 -0
  207. package/package.json +80 -5
package/dist/index.js ADDED
@@ -0,0 +1,3393 @@
1
+ // src/api-keys/resolvers/deps.ts
2
+ import { GraphQLError as GraphQLError9 } from "graphql";
3
+
4
+ // src/memo.ts
5
+ var NOTATION = /[@#]/;
6
+ function keyOf(subject, permission, object, options) {
7
+ if (subject === null || options?.ctx !== undefined)
8
+ return null;
9
+ if (NOTATION.test(object.id) || NOTATION.test(subject.id))
10
+ return null;
11
+ const set = typeof subject.relation === "string" ? `#${subject.relation}` : "";
12
+ return `${object.type}:${object.id}#${permission}@${subject.type}:${subject.id}${set}`;
13
+ }
14
+ function memoized(access) {
15
+ const can = access.can;
16
+ const answers = new Map;
17
+ const ask = async (subject, permission, object, options) => can.call(access, subject, permission, object, options);
18
+ return (subject, permission, object, options) => {
19
+ const key = keyOf(subject, permission, object, options);
20
+ if (key === null)
21
+ return ask(subject, permission, object, options);
22
+ const known = answers.get(key);
23
+ if (known !== undefined)
24
+ return known;
25
+ const answer = ask(subject, permission, object, options);
26
+ answers.set(key, answer);
27
+ answer.then(undefined, () => answers.delete(key));
28
+ return answer;
29
+ };
30
+ }
31
+
32
+ // src/context/registry.ts
33
+ import { systemClock } from "@softistx/janus";
34
+ var checks = new WeakMap;
35
+ var clocks = new WeakMap;
36
+ var answers = new WeakMap;
37
+ var cookies = new WeakMap;
38
+ function cookieOfContext(janus) {
39
+ return cookies.get(janus);
40
+ }
41
+ function answerOf(janus) {
42
+ return answers.get(janus)?.();
43
+ }
44
+ function clockOf(janus) {
45
+ return clocks.get(janus) ?? systemClock;
46
+ }
47
+ function checkOf(janus, fresh = false) {
48
+ const built = checks.get(janus);
49
+ if (built !== undefined)
50
+ return fresh ? built.fresh : built.memo;
51
+ const access = janus.access;
52
+ return typeof access?.can === "function" ? access.can : null;
53
+ }
54
+ function janusOf(ctx, caller) {
55
+ const janus = ctx?.janus;
56
+ if (janus === undefined || typeof janus.user !== "function") {
57
+ throw new TypeError(`${caller}: ctx.janus is not set — add useJanus({ auth }) to the plugins`);
58
+ }
59
+ return janus;
60
+ }
61
+
62
+ // src/context/resolve.ts
63
+ async function resolveAuth(auth, context, caller, what = "request") {
64
+ if (typeof auth !== "function")
65
+ return auth;
66
+ const instance = await auth(context);
67
+ if (instance === null || instance === undefined) {
68
+ throw new TypeError(`${caller}: the auth resolver answered no janus() instance for this ${what} — return what janus() answered, or ${what === "request" ? "throw to refuse the request" : "throw to refuse it"}`);
69
+ }
70
+ if (typeof instance.authenticate !== "function") {
71
+ throw new TypeError(`${caller}: the auth resolver answered something that is not what janus() answered`);
72
+ }
73
+ return instance;
74
+ }
75
+ async function instanceOf(auth, context, caller, janus, what) {
76
+ const instance = await resolveAuth(auth, context, caller, what);
77
+ cookies.set(janus, instance.cookie);
78
+ return instance;
79
+ }
80
+
81
+ // src/context/create.ts
82
+ function createJanusContext(request, options) {
83
+ const {
84
+ auth,
85
+ access,
86
+ type,
87
+ clock,
88
+ apiKey,
89
+ caller = "useJanus()",
90
+ context,
91
+ what = "request"
92
+ } = options;
93
+ let answer;
94
+ let asked = false;
95
+ const authenticated = () => {
96
+ if (!asked) {
97
+ asked = true;
98
+ answer = request === undefined ? Promise.reject(new TypeError(`${caller}: the GraphQL context has no request to authenticate — build the context from an HTTP request, or accept a graphql-ws connection with janusConnection().onConnect`)) : instanceOf(auth, context, caller, janus, what).then((instance) => instance.authenticate(request, {
99
+ ...type === undefined ? {} : { type },
100
+ ...apiKey === true ? { apiKey: true } : {}
101
+ }));
102
+ }
103
+ return answer;
104
+ };
105
+ const janus = Object.freeze({
106
+ user: () => authenticated().then((current) => current?.user ?? null),
107
+ session: () => authenticated().then((current) => current?.session ?? null),
108
+ ...apiKey === true ? {
109
+ principal: () => authenticated(),
110
+ apiKey: () => authenticated().then((current) => current?.via === "apiKey" ? current.apiKey : null)
111
+ } : {},
112
+ ...access === undefined ? {} : { access }
113
+ });
114
+ if (access !== undefined) {
115
+ const can = access.can;
116
+ checks.set(janus, {
117
+ memo: memoized(access),
118
+ fresh: (...args) => can.apply(access, args)
119
+ });
120
+ }
121
+ if (clock !== undefined)
122
+ clocks.set(janus, clock);
123
+ answers.set(janus, () => asked ? answer : undefined);
124
+ return janus;
125
+ }
126
+ // src/errors/denial.ts
127
+ import { GraphQLError } from "graphql";
128
+ function denial(code, message) {
129
+ const [status, fallback] = denialOf(code);
130
+ return new GraphQLError(message ?? fallback, {
131
+ extensions: { code, http: { status } }
132
+ });
133
+ }
134
+ function denialOf(code) {
135
+ switch (code) {
136
+ case "UNAUTHENTICATED":
137
+ return [401, "Not signed in"];
138
+ case "FORBIDDEN":
139
+ return [403, "Forbidden"];
140
+ case "NOT_FOUND":
141
+ return [404, "Not found"];
142
+ }
143
+ }
144
+ // src/errors/janus-error.ts
145
+ import { JanusError, statusOf } from "@softistx/janus";
146
+ import { GraphQLError as GraphQLError2 } from "graphql";
147
+ function janusGraphQLError(error) {
148
+ const status = statusOf(error.code);
149
+ const code = codeOf(error);
150
+ return new GraphQLError2(messageOf(status), {
151
+ originalError: error,
152
+ extensions: {
153
+ code,
154
+ http: httpOf(error, status),
155
+ ...actionable(error),
156
+ ...flowOf(error)
157
+ }
158
+ });
159
+ }
160
+ function codeOf(error) {
161
+ switch (error.code) {
162
+ case "STORE_FAILED":
163
+ return "SERVICE_UNAVAILABLE";
164
+ case "CURSOR_FILTER_MISMATCH":
165
+ return "BAD_USER_INPUT";
166
+ default:
167
+ return error.code;
168
+ }
169
+ }
170
+ function messageOf(status) {
171
+ switch (status) {
172
+ case 400:
173
+ return "Invalid request";
174
+ case 401:
175
+ return "Invalid credentials";
176
+ case 403:
177
+ return "Forbidden";
178
+ case 404:
179
+ return "Not found";
180
+ case 409:
181
+ return "Conflict";
182
+ case 429:
183
+ return "Too many requests, retry later";
184
+ case 502:
185
+ return "Bad gateway";
186
+ case 503:
187
+ return "The service is unavailable, retry later";
188
+ case 500:
189
+ case 501:
190
+ return "Internal server error";
191
+ }
192
+ }
193
+ function httpOf(error, status) {
194
+ return error.retryAfter === undefined ? { status } : { status, headers: { "Retry-After": String(error.retryAfter) } };
195
+ }
196
+ function actionable(error) {
197
+ switch (error.code) {
198
+ case "USER_INVALID":
199
+ return { issues: error.issues ?? [] };
200
+ case "PASSWORD_TOO_SHORT":
201
+ return error.minLength === undefined ? {} : { minLength: error.minLength };
202
+ case "CODE_INVALID":
203
+ return {
204
+ ...error.attemptsLeft === undefined ? {} : { attemptsLeft: error.attemptsLeft },
205
+ ...error.retryAfter === undefined ? {} : { retryAfter: error.retryAfter }
206
+ };
207
+ case "CREDENTIALS_INVALID":
208
+ case "MAIL_THROTTLED":
209
+ return error.retryAfter === undefined ? {} : { retryAfter: error.retryAfter };
210
+ case "API_KEY_LIMIT":
211
+ case "INVITATION_LIMIT":
212
+ case "PASSKEY_LIMIT":
213
+ return error.maxActive === undefined ? {} : { maxActive: error.maxActive };
214
+ case "INVITATION_INVALID":
215
+ return {
216
+ ...error.field === undefined ? {} : { field: error.field },
217
+ ...isInvitationRefusal(error.reason) ? { reason: error.reason } : {}
218
+ };
219
+ case "API_KEY_INVALID":
220
+ case "PASSKEY_INVALID":
221
+ return error.field === undefined ? {} : { field: error.field };
222
+ case "INVALID_CURSOR":
223
+ case "CURSOR_FILTER_MISMATCH":
224
+ return { field: error.field ?? "after" };
225
+ default:
226
+ return {};
227
+ }
228
+ }
229
+ var INVITATION_REFUSALS = [
230
+ "unknown",
231
+ "expired",
232
+ "accepted",
233
+ "revoked"
234
+ ];
235
+ function isInvitationRefusal(reason) {
236
+ return INVITATION_REFUSALS.includes(reason);
237
+ }
238
+ function flowOf(error) {
239
+ return {
240
+ ...error.returnTo === undefined ? {} : { returnTo: error.returnTo },
241
+ ...error.flowSpent === undefined ? {} : { flowSpent: error.flowSpent }
242
+ };
243
+ }
244
+ function rethrown(error) {
245
+ throw error instanceof JanusError ? janusGraphQLError(error) : error;
246
+ }
247
+ // src/errors/mask.ts
248
+ import { GraphQLError as GraphQLError6 } from "graphql";
249
+
250
+ // src/map-code.ts
251
+ import { GraphQLError as GraphQLError3 } from "graphql";
252
+ function remapped(error, mapCode) {
253
+ const code = error.extensions?.["code"];
254
+ const mapped = typeof code === "string" ? mapCode(code, error) : undefined;
255
+ if (mapped === undefined)
256
+ return error;
257
+ const extensions = {
258
+ ...error.extensions,
259
+ code: mapped.code
260
+ };
261
+ if (mapped.status !== undefined) {
262
+ extensions["http"] = {
263
+ ...error.extensions?.["http"],
264
+ status: mapped.status
265
+ };
266
+ }
267
+ return new GraphQLError3(mapped.message ?? error.message, {
268
+ nodes: error.nodes,
269
+ source: error.source,
270
+ positions: error.positions,
271
+ path: error.path,
272
+ originalError: error.originalError ?? undefined,
273
+ extensions
274
+ });
275
+ }
276
+
277
+ // src/mask-error.ts
278
+ import { GraphQLError as GraphQLError4 } from "graphql";
279
+ function isOriginalGraphQLError(error) {
280
+ if (error instanceof GraphQLError4) {
281
+ return error.originalError == null || isOriginalGraphQLError(error.originalError);
282
+ }
283
+ return false;
284
+ }
285
+ function serialized(error) {
286
+ if (error instanceof GraphQLError4) {
287
+ return error.toJSON();
288
+ }
289
+ if (error instanceof Error) {
290
+ return { message: error.message, stack: error.stack, cause: error.cause };
291
+ }
292
+ return error;
293
+ }
294
+ function inDevelopment() {
295
+ return globalThis.process?.env?.NODE_ENV === "development";
296
+ }
297
+ function maskedError(error, message, isDev = inDevelopment()) {
298
+ if (isOriginalGraphQLError(error)) {
299
+ return error;
300
+ }
301
+ const extensions = {
302
+ code: "INTERNAL_SERVER_ERROR",
303
+ unexpected: true
304
+ };
305
+ const options = { extensions };
306
+ if (error instanceof GraphQLError4) {
307
+ Object.assign(options, {
308
+ nodes: error.nodes,
309
+ source: error.source,
310
+ positions: error.positions,
311
+ path: error.path
312
+ });
313
+ if (isDev && error.originalError) {
314
+ extensions["originalError"] = serialized(error.originalError);
315
+ }
316
+ if (error.extensions?.["http"]) {
317
+ extensions["http"] = error.extensions["http"];
318
+ }
319
+ } else if (isDev) {
320
+ extensions["originalError"] = serialized(error);
321
+ }
322
+ return new GraphQLError4(message, options);
323
+ }
324
+
325
+ // src/report.ts
326
+ import { JanusError as JanusError2, statusOf as statusOf2 } from "@softistx/janus";
327
+ import { GraphQLError as GraphQLError5 } from "graphql";
328
+ function janusErrorIn(error) {
329
+ let current = error;
330
+ while (current instanceof GraphQLError5)
331
+ current = current.originalError;
332
+ return current instanceof JanusError2 ? current : null;
333
+ }
334
+ function reporting(report) {
335
+ const seen = new WeakSet;
336
+ return (error) => {
337
+ const janusError = janusErrorIn(error);
338
+ if (janusError === null || seen.has(janusError))
339
+ return;
340
+ if (statusOf2(janusError.code) < 500)
341
+ return;
342
+ seen.add(janusError);
343
+ const warn = (failure) => process.emitWarning(`janusMaskError: report failed on ${janusError.code}: ${failure instanceof Error ? failure.name : typeof failure}`);
344
+ try {
345
+ Promise.resolve(report(janusError)).then(undefined, warn);
346
+ } catch (failure) {
347
+ warn(failure);
348
+ }
349
+ };
350
+ }
351
+ function janusErrorOf(error) {
352
+ return janusErrorIn(error) ?? undefined;
353
+ }
354
+
355
+ // src/errors/mask.ts
356
+ function janusMaskError(options = {}) {
357
+ const {
358
+ report,
359
+ fallback = maskedError,
360
+ mapCode
361
+ } = typeof options === "function" ? { fallback: options } : options;
362
+ const reported = report === undefined ? undefined : reporting(report);
363
+ const mask = masking(fallback, reported);
364
+ return mapCode === undefined ? mask : (error, message, isDevOrContext, context) => {
365
+ const masked = mask(error, message, isDevOrContext, context);
366
+ return masked instanceof GraphQLError6 ? remapped(masked, mapCode) : masked;
367
+ };
368
+ }
369
+ function masking(fallback, reported) {
370
+ return (error, message, isDevOrContext, context) => {
371
+ reported?.(error);
372
+ const original = janusErrorIn(error);
373
+ if (original !== null) {
374
+ const answer = janusGraphQLError(original);
375
+ return error instanceof GraphQLError6 ? new GraphQLError6(answer.message, {
376
+ nodes: error.nodes ?? null,
377
+ path: error.path ?? null,
378
+ originalError: original,
379
+ extensions: answer.extensions
380
+ }) : answer;
381
+ }
382
+ return typeof isDevOrContext === "boolean" || isDevOrContext === undefined ? fallback(error, message, isDevOrContext, context) : fallback(error, message, undefined, context ?? isDevOrContext);
383
+ };
384
+ }
385
+ // src/helpers.ts
386
+ async function requireUser(ctx, options = {}) {
387
+ const { type } = options;
388
+ const allowed = typeof type === "string" ? [type] : type;
389
+ if (allowed?.length === 0) {
390
+ throw new TypeError("requireUser(): type is an empty list, which no user could pass — name at least one user type, or leave type out");
391
+ }
392
+ const user = await janusOf(ctx, "requireUser()").user().then(undefined, rethrown);
393
+ if (user === null)
394
+ throw denial("UNAUTHENTICATED");
395
+ if (allowed !== undefined && !allowed.includes(user.type)) {
396
+ throw denial("FORBIDDEN");
397
+ }
398
+ return user;
399
+ }
400
+ async function can(ctx, permission, object, ...options) {
401
+ const janus = janusOf(ctx, "can()");
402
+ const check = checkOf(janus);
403
+ if (check === null) {
404
+ throw new TypeError("can(): ctx.janus.access is not set — pass { access } to useJanus()");
405
+ }
406
+ const subject = await janus.user().then(undefined, rethrown);
407
+ return check(subject, permission, object, options[0]).then(undefined, rethrown);
408
+ }
409
+
410
+ // src/api-keys/shape.ts
411
+ import { JanusError as JanusError3 } from "@softistx/janus";
412
+ import { GraphQLError as GraphQLError8 } from "graphql";
413
+
414
+ // src/bad-input.ts
415
+ import { GraphQLError as GraphQLError7 } from "graphql";
416
+ function badInput(message, field) {
417
+ return new GraphQLError7(message, {
418
+ extensions: { code: "BAD_USER_INPUT", http: { status: 400 }, field }
419
+ });
420
+ }
421
+ function limitOf(limit) {
422
+ if (limit == null)
423
+ return {};
424
+ if (!Number.isSafeInteger(limit) || limit < 1) {
425
+ throw badInput("limit must be a positive integer", "limit");
426
+ }
427
+ return { limit };
428
+ }
429
+
430
+ // src/api-keys/shape.ts
431
+ var iso = (date) => date === null ? null : date.toISOString();
432
+ function apiKeyOut(key, now) {
433
+ return {
434
+ id: key.id,
435
+ userId: key.userId,
436
+ name: key.name,
437
+ prefix: key.hint,
438
+ scopes: key.scopes,
439
+ bound: key.bound,
440
+ status: key.revokedAt !== null ? "REVOKED" : key.expiresAt.getTime() <= now ? "EXPIRED" : "ACTIVE",
441
+ createdAt: key.createdAt.toISOString(),
442
+ expiresAt: key.expiresAt.toISOString(),
443
+ lastUsedAt: iso(key.lastUsedAt),
444
+ revokedAt: iso(key.revokedAt)
445
+ };
446
+ }
447
+ var API_KEY_LIMITS = {
448
+ name: 100,
449
+ scopes: 32,
450
+ scope: 100,
451
+ boundTo: 200
452
+ };
453
+ function boundedCreate(name, scopes) {
454
+ if (name.trim().length > API_KEY_LIMITS.name) {
455
+ throw badInput(`name must be at most ${API_KEY_LIMITS.name} characters`, "name");
456
+ }
457
+ if (scopes == null)
458
+ return;
459
+ if (scopes.length > API_KEY_LIMITS.scopes) {
460
+ throw badInput(`scopes must hold at most ${API_KEY_LIMITS.scopes} scopes`, "scopes");
461
+ }
462
+ if (scopes.some((scope) => scope.length > API_KEY_LIMITS.scope)) {
463
+ throw badInput(`each scope must be at most ${API_KEY_LIMITS.scope} characters`, "scopes");
464
+ }
465
+ }
466
+ function boundToOf(boundTo) {
467
+ if (boundTo == null)
468
+ return null;
469
+ if (boundTo.length === 0 || boundTo.length > API_KEY_LIMITS.boundTo) {
470
+ throw badInput(`boundTo must be 1 to ${API_KEY_LIMITS.boundTo} characters`, "boundTo");
471
+ }
472
+ return boundTo;
473
+ }
474
+ function lifetimeOf(lifetimes, lifetimeDays) {
475
+ if (lifetimeDays == null)
476
+ return lifetimes.default;
477
+ if (!lifetimes.days.includes(lifetimeDays)) {
478
+ throw badInput(`lifetimeDays must be one of ${lifetimes.days.join(", ")}`, "lifetimeDays");
479
+ }
480
+ return lifetimeDays;
481
+ }
482
+ function checkedLifetimes(lifetimes) {
483
+ const at = "apiKeysResolvers(): lifetimes";
484
+ if (lifetimes === undefined || !Array.isArray(lifetimes.days) || lifetimes.days.length === 0) {
485
+ throw new TypeError(`${at} must list at least one lifetime in days — for example { days: [30, 90, 365], default: 90 }`);
486
+ }
487
+ for (const days of lifetimes.days) {
488
+ if (!Number.isSafeInteger(days) || days < 1) {
489
+ throw new TypeError(`${at}.days must be positive whole numbers of days`);
490
+ }
491
+ }
492
+ if (!lifetimes.days.includes(lifetimes.default)) {
493
+ throw new TypeError(`${at}.default must be one of lifetimes.days`);
494
+ }
495
+ const [first, ...rest] = lifetimes.days;
496
+ return { days: [first, ...rest], default: lifetimes.default };
497
+ }
498
+ function createRefused(error) {
499
+ if (!(error instanceof JanusError3))
500
+ throw error;
501
+ const answered = janusGraphQLError(error);
502
+ if (error.code !== "API_KEY_INVALID" || error.field !== "lifetime") {
503
+ throw answered;
504
+ }
505
+ throw new GraphQLError8(answered.message, {
506
+ extensions: { ...answered.extensions, field: "lifetimeDays" }
507
+ });
508
+ }
509
+
510
+ // src/api-keys/resolvers/deps.ts
511
+ function depsOf(options) {
512
+ const { auth, authorize } = options;
513
+ if (auth?.apiKeys === undefined) {
514
+ throw new TypeError("apiKeysResolvers(): auth has no apiKeys — give janus() `apiKeys`");
515
+ }
516
+ const hooks = ["create", "list", "revoke"];
517
+ if (hooks.some((hook) => typeof authorize?.[hook] !== "function")) {
518
+ throw new TypeError("apiKeysResolvers(): `authorize` needs `create`, `list` and `revoke` — the core authorises nobody, so say who may manage keys");
519
+ }
520
+ if (options.bound !== undefined && typeof options.bound !== "function") {
521
+ throw new TypeError("apiKeysResolvers(): `bound` must be a function of the asked id and the context");
522
+ }
523
+ return {
524
+ keys: auth.apiKeys,
525
+ lifetimes: checkedLifetimes(options.lifetimes),
526
+ authorize,
527
+ bound: options.bound
528
+ };
529
+ }
530
+ async function callerOf(deps, ctx, boundTo) {
531
+ const asked = boundToOf(boundTo);
532
+ const user = await requireUser(ctx);
533
+ const now = clockOf(janusOf(ctx, "apiKeysResolvers()")).now().getTime();
534
+ if (deps.bound === undefined) {
535
+ if (asked !== null)
536
+ throw denial("NOT_FOUND");
537
+ return { user, bound: null, now };
538
+ }
539
+ const bound = await deps.bound(asked, ctx);
540
+ if (bound === null && asked !== null)
541
+ throw denial("NOT_FOUND");
542
+ return { user, bound, now };
543
+ }
544
+ async function principalOf(ctx) {
545
+ const janus = janusOf(ctx, "createApiKey");
546
+ const answered = answerOf(janus) ?? janus.principal?.();
547
+ const principal = await answered?.then(undefined, rethrown);
548
+ if (principal == null)
549
+ throw denial("UNAUTHENTICATED");
550
+ return principal;
551
+ }
552
+ async function allowed(answer) {
553
+ if (await answer !== true)
554
+ throw denial("NOT_FOUND");
555
+ }
556
+ async function unknownKey(ask) {
557
+ try {
558
+ await ask();
559
+ } catch (error) {
560
+ if (error instanceof GraphQLError9)
561
+ throw error;
562
+ }
563
+ throw denial("NOT_FOUND");
564
+ }
565
+ var sameBound = (a, b) => a === null || b === null ? a === b : a.type === b.type && a.id === b.id;
566
+
567
+ // src/api-keys/resolvers/list.ts
568
+ var DEFAULT_LIMIT = 20;
569
+ var MAX_LIMIT = 100;
570
+ function pageOf(limit, after) {
571
+ const asked = {
572
+ ...limitOf(limit),
573
+ ...after == null ? {} : { after }
574
+ };
575
+ return {
576
+ asked,
577
+ size: Math.min(asked.limit ?? DEFAULT_LIMIT, MAX_LIMIT),
578
+ after: after ?? null
579
+ };
580
+ }
581
+ function apiKeys(deps) {
582
+ return async (_, { boundTo, limit, after }, ctx) => {
583
+ const page = pageOf(limit, after);
584
+ const { user, bound, now } = await callerOf(deps, ctx, boundTo);
585
+ await allowed(deps.authorize.list({ user, bound, every: false, page: page.asked }, ctx));
586
+ const found = await deps.keys.list(user, {
587
+ limit: page.size,
588
+ after: page.after,
589
+ ...deps.bound === undefined ? {} : { bound }
590
+ }).then(undefined, rethrown);
591
+ return {
592
+ items: found.items.map((key) => apiKeyOut(key, now)),
593
+ nextCursor: found.nextCursor
594
+ };
595
+ };
596
+ }
597
+ function boundApiKeys(deps) {
598
+ return async (_, { boundTo, limit, after }, ctx) => {
599
+ const page = pageOf(limit, after);
600
+ const { user, bound, now } = await callerOf(deps, ctx, boundTo);
601
+ if (bound === null)
602
+ throw denial("NOT_FOUND");
603
+ await allowed(deps.authorize.list({ user, bound, every: true, page: page.asked }, ctx));
604
+ const found = await deps.keys.listBound(bound, { limit: page.size, after: page.after }).then(undefined, rethrown);
605
+ return {
606
+ items: found.items.map((key) => apiKeyOut(key, now)),
607
+ nextCursor: found.nextCursor
608
+ };
609
+ };
610
+ }
611
+ function apiKeyLifetimes(deps) {
612
+ return async (_, __, ctx) => {
613
+ await requireUser(ctx);
614
+ return deps.lifetimes;
615
+ };
616
+ }
617
+
618
+ // src/renewal.ts
619
+ var contexts = new WeakMap;
620
+ var pending = new WeakMap;
621
+ function sendCookie(request, setCookie) {
622
+ const known = pending.get(request);
623
+ if (known === undefined)
624
+ pending.set(request, [setCookie]);
625
+ else
626
+ known.push(setCookie);
627
+ }
628
+ var uncached = new WeakSet;
629
+ function sendNoStore(request) {
630
+ uncached.add(request);
631
+ }
632
+ function noStoreOf(ctx) {
633
+ if (ctx?.request !== undefined)
634
+ sendNoStore(ctx.request);
635
+ }
636
+ function track(request, janus) {
637
+ const known = contexts.get(request);
638
+ if (known === undefined)
639
+ contexts.set(request, [janus]);
640
+ else
641
+ known.push(janus);
642
+ }
643
+ async function resendRenewed({ request, response }, fixed) {
644
+ if (uncached.has(request))
645
+ response.headers.set("Cache-Control", "no-store");
646
+ for (const setCookie of pending.get(request) ?? []) {
647
+ response.headers.append("Set-Cookie", setCookie);
648
+ }
649
+ const known = contexts.get(request);
650
+ if (known === undefined)
651
+ return;
652
+ for (const janus of known) {
653
+ const cookie = fixed ?? cookieOfContext(janus);
654
+ if (cookie === undefined)
655
+ continue;
656
+ const current = await answerOf(janus)?.then((answer) => answer, () => null);
657
+ if (current?.renewed === true && cookieOf(request, cookie.name) === current.token && !sets(response, cookie.name)) {
658
+ response.headers.append("Set-Cookie", cookie.serialize(current.token, current.session));
659
+ }
660
+ }
661
+ }
662
+ function cookieOf(request, name) {
663
+ const header = request.headers.get("cookie");
664
+ if (header === null)
665
+ return null;
666
+ for (const pair of header.split(";")) {
667
+ const at = pair.indexOf("=");
668
+ if (at !== -1 && pair.slice(0, at).trim() === name) {
669
+ return pair.slice(at + 1).trim();
670
+ }
671
+ }
672
+ return null;
673
+ }
674
+ function sets(response, name) {
675
+ return response.headers.getSetCookie().some((value) => value.startsWith(`${name}=`));
676
+ }
677
+
678
+ // src/api-keys/resolvers/manage.ts
679
+ function createApiKey(deps) {
680
+ return async (_, args, ctx) => {
681
+ boundedCreate(args.name, args.scopes);
682
+ const lifetimeDays = lifetimeOf(deps.lifetimes, args.lifetimeDays);
683
+ const scopes = args.scopes ?? null;
684
+ const { user, bound, now } = await callerOf(deps, ctx, args.boundTo);
685
+ await allowed(deps.authorize.create({ user, bound, input: { name: args.name, lifetimeDays, scopes } }, ctx));
686
+ const current = await principalOf(ctx);
687
+ const created = await deps.keys.create(current, {
688
+ name: args.name,
689
+ lifetime: `${lifetimeDays}d`,
690
+ ...scopes === null ? {} : { scopes },
691
+ ...bound === null ? {} : { bound }
692
+ }).then(undefined, createRefused);
693
+ noStoreOf(ctx);
694
+ return { apiKey: apiKeyOut(created.apiKey, now), secret: created.token };
695
+ };
696
+ }
697
+ async function located(deps, caller, id) {
698
+ const { user, bound } = caller;
699
+ const key = await deps.keys.get(id).then(undefined, rethrown);
700
+ if (key === null)
701
+ return null;
702
+ const binds = deps.bound !== undefined;
703
+ if (key.userId === user.id && (!binds || sameBound(key.bound, bound))) {
704
+ return { key, own: true };
705
+ }
706
+ if (bound !== null && sameBound(key.bound, bound))
707
+ return { key, own: false };
708
+ return null;
709
+ }
710
+ function revokeApiKey(deps) {
711
+ return async (_, { id, boundTo }, ctx) => {
712
+ const caller = await callerOf(deps, ctx, boundTo);
713
+ const { user, bound } = caller;
714
+ const found = await located(deps, caller, id);
715
+ if (found === null) {
716
+ return unknownKey(() => deps.authorize.revoke({ user, bound }, ctx));
717
+ }
718
+ const { key, own } = found;
719
+ await allowed(deps.authorize.revoke({ user, bound, key, own }, ctx));
720
+ await deps.keys.revoke(key.id, own ? { owner: user } : {}).then(undefined, rethrown);
721
+ const after = await deps.keys.get(key.id).then(undefined, rethrown) ?? {
722
+ ...key,
723
+ revokedAt: key.revokedAt ?? new Date(caller.now)
724
+ };
725
+ return apiKeyOut(after, caller.now);
726
+ };
727
+ }
728
+
729
+ // src/api-keys/resolvers/index.ts
730
+ function apiKeysResolvers(options) {
731
+ const deps = depsOf(options);
732
+ return {
733
+ Query: {
734
+ apiKeys: apiKeys(deps),
735
+ boundApiKeys: boundApiKeys(deps),
736
+ apiKeyLifetimes: apiKeyLifetimes(deps)
737
+ },
738
+ Mutation: {
739
+ createApiKey: createApiKey(deps),
740
+ revokeApiKey: revokeApiKey(deps)
741
+ }
742
+ };
743
+ }
744
+ // src/api-keys/sdl.ts
745
+ var apiKeysTypeDefs = `"""
746
+ A personal API key, as its holder and the bound object's owners see it. The
747
+ secret is never here: \`createApiKey\` answers it once.
748
+ """
749
+ type JanusApiKey {
750
+ """
751
+ The key's id: what \`revokeApiKey\` takes. Not the secret.
752
+ """
753
+ id: ID!
754
+ """
755
+ The id of the user who holds the key.
756
+ """
757
+ userId: ID!
758
+ """
759
+ The label its holder chose, 1 to 100 characters.
760
+ """
761
+ name: String!
762
+ """
763
+ The start of the token: its prefix and the first characters of its id
764
+ (\`sl_0192ab…\`). Enough to recognise the key, not to use it.
765
+ """
766
+ prefix: String!
767
+ """
768
+ What the key may do, as given at creation (\`mcp:read\`), or null for a key
769
+ that may do whatever its user may. Janus never enforces them: the
770
+ application does, where it serves the key's requests.
771
+ """
772
+ scopes: [String!]
773
+ """
774
+ The one object the key acts in, or null for an unbound key.
775
+ """
776
+ bound: JanusApiKeyBound
777
+ """
778
+ \`ACTIVE\`, \`REVOKED\` or \`EXPIRED\`.
779
+ """
780
+ status: JanusApiKeyStatus!
781
+ """
782
+ When the key was created, as an ISO-8601 string.
783
+ """
784
+ createdAt: String!
785
+ """
786
+ When the key stops being usable, as an ISO-8601 string.
787
+ """
788
+ expiresAt: String!
789
+ """
790
+ When the key was last used, as an ISO-8601 string; null while it was never
791
+ used. It moves at most once per throttle window.
792
+ """
793
+ lastUsedAt: String
794
+ """
795
+ When the key was revoked, as an ISO-8601 string; null while the key stands.
796
+ """
797
+ revokedAt: String
798
+ }
799
+
800
+ """
801
+ The object a key is bound to: a workspace, an account, a project… as the
802
+ application names it.
803
+ """
804
+ type JanusApiKeyBound {
805
+ """
806
+ What the object is, as the application names its kinds (\`workspace\`).
807
+ """
808
+ type: String!
809
+ """
810
+ The id of the object.
811
+ """
812
+ id: ID!
813
+ }
814
+
815
+ """
816
+ Whether a key can still be used.
817
+ """
818
+ enum JanusApiKeyStatus {
819
+ """
820
+ Usable until \`expiresAt\`.
821
+ """
822
+ ACTIVE
823
+ """
824
+ Revoked (\`revokedAt\`): refused from then on.
825
+ """
826
+ REVOKED
827
+ """
828
+ Past \`expiresAt\` without being revoked.
829
+ """
830
+ EXPIRED
831
+ }
832
+
833
+ """
834
+ A key just created: \`secret\` is the whole token, answered this once.
835
+ """
836
+ type JanusCreatedApiKey {
837
+ """
838
+ The key that was created, as \`apiKeys\` lists it.
839
+ """
840
+ apiKey: JanusApiKey!
841
+ """
842
+ The whole token (\`sl_…\`). Shown only in this answer and never stored: a
843
+ lost secret is a new key. The response is \`no-store\`.
844
+ """
845
+ secret: String!
846
+ }
847
+
848
+ """
849
+ One page of keys, oldest first. \`nextCursor\` is null on the last page; a page
850
+ may hold fewer than \`limit\` keys and still have a next one.
851
+ """
852
+ type JanusApiKeyPage {
853
+ """
854
+ The keys of this page, oldest first.
855
+ """
856
+ items: [JanusApiKey!]!
857
+ """
858
+ Pass it as \`after\` to read the next page; null on the last page.
859
+ """
860
+ nextCursor: String
861
+ }
862
+
863
+ """
864
+ The lifetimes \`createApiKey\` offers, in days, and the one it takes when
865
+ \`lifetimeDays\` is absent.
866
+ """
867
+ type JanusApiKeyLifetimes {
868
+ """
869
+ The lifetimes a new key may have, in days.
870
+ """
871
+ days: [Int!]!
872
+ """
873
+ The lifetime, in days, taken when \`lifetimeDays\` is absent.
874
+ """
875
+ default: Int!
876
+ }
877
+
878
+ extend type Query {
879
+ """
880
+ The signed-in user's own keys — standing, revoked and expired — oldest
881
+ first; when the application binds keys, only those bound to the object
882
+ \`boundTo\` names (or that the request's context names). \`limit\` is a
883
+ positive integer, 20 by default and at most 100; \`after\` is the previous
884
+ page's \`nextCursor\`. NOT_FOUND when the application's \`authorize\` refuses,
885
+ or \`boundTo\` names no object. A \`boundTo\` empty or over 200 characters is
886
+ BAD_USER_INPUT (\`field\`).
887
+ """
888
+ apiKeys(
889
+ """
890
+ The object whose keys to list; absent: the one the request's context
891
+ names, when the application binds keys.
892
+ """
893
+ boundTo: ID
894
+ """
895
+ The page size: a positive integer, 20 by default, at most 100.
896
+ """
897
+ limit: Int
898
+ """
899
+ The previous page's \`nextCursor\`; absent for the first page.
900
+ """
901
+ after: String
902
+ ): JanusApiKeyPage! @authenticated
903
+ """
904
+ Every key bound to the object \`boundTo\` names (or that the request's
905
+ context names), whoever holds it: the object owner's view. Paged and
906
+ refused as \`apiKeys\`, and NOT_FOUND when there is no object.
907
+ """
908
+ boundApiKeys(
909
+ """
910
+ The object whose keys to list; absent: the one the request's context names.
911
+ """
912
+ boundTo: ID
913
+ """
914
+ The page size: a positive integer, 20 by default, at most 100.
915
+ """
916
+ limit: Int
917
+ """
918
+ The previous page's \`nextCursor\`; absent for the first page.
919
+ """
920
+ after: String
921
+ ): JanusApiKeyPage! @authenticated
922
+ """
923
+ The lifetimes a new key may have.
924
+ """
925
+ apiKeyLifetimes: JanusApiKeyLifetimes! @authenticated
926
+ }
927
+
928
+ extend type Mutation {
929
+ """
930
+ Creates a key for the signed-in user. Needs a recent step-up. The key is
931
+ bound to the object \`boundTo\` names (or that the request's context names)
932
+ when the application binds keys, and answers its \`secret\`, the only time
933
+ it is shown. \`lifetimeDays\` is one of \`apiKeyLifetimes.days\` (its
934
+ \`default\` when absent; BAD_USER_INPUT otherwise); \`scopes\` are what the
935
+ key may do (absent: whatever its user may). STEP_UP_REQUIRED (403) unless
936
+ the session proved who it is recently, and always for a request signed by
937
+ a key: a key never creates a key. API_KEY_INVALID (400, \`field\`) for a
938
+ name or scopes the core cannot keep, API_KEY_LIMIT (409, \`maxActive\`) when
939
+ the user holds the most standing keys, NOT_FOUND when \`authorize\` refuses.
940
+ A \`name\` over 100 characters, more than 32 \`scopes\` or one over 100
941
+ characters is BAD_USER_INPUT (400, \`field\`) before \`authorize\` runs.
942
+ """
943
+ createApiKey(
944
+ """
945
+ The label for the key, 1 to 100 characters.
946
+ """
947
+ name: String!
948
+ """
949
+ One of \`apiKeyLifetimes.days\`; absent: its \`default\`.
950
+ """
951
+ lifetimeDays: Int
952
+ """
953
+ What the key may do, at most 32 of at most 100 characters each; absent:
954
+ whatever its user may.
955
+ """
956
+ scopes: [String!]
957
+ """
958
+ The object to bind the key to, at most 200 characters; absent: the one
959
+ the request's context names, when the application binds keys.
960
+ """
961
+ boundTo: ID
962
+ ): JanusCreatedApiKey! @authenticated
963
+ """
964
+ Revokes a key and answers it; revoking a revoked key is not an error. The
965
+ key is the signed-in user's own, or one bound to the object \`boundTo\`
966
+ names (or that the request's context names), as \`authorize\` allows.
967
+ NOT_FOUND for an id that names neither, whatever \`authorize\` answers, and
968
+ when \`authorize\` refuses.
969
+ """
970
+ revokeApiKey(
971
+ """
972
+ The id of the key to revoke.
973
+ """
974
+ id: ID!
975
+ """
976
+ The object the key is bound to; absent: the one the request's context
977
+ names, or none for the user's own key.
978
+ """
979
+ boundTo: ID
980
+ ): JanusApiKey! @authenticated
981
+ }
982
+ `;
983
+ // src/avatar/resolvers.ts
984
+ import { GraphQLError as GraphQLError10 } from "graphql";
985
+ function avatarResolvers(options) {
986
+ return {
987
+ JanusAvatar: {
988
+ updatedAt: (avatar) => avatar.updatedAt.toISOString(),
989
+ url: (avatar, { size }) => {
990
+ if (!Number.isSafeInteger(size) || size < 1) {
991
+ throw new GraphQLError10("size must be a positive integer", {
992
+ extensions: { code: "BAD_USER_INPUT", http: { status: 400 } }
993
+ });
994
+ }
995
+ return options.url(avatar, size);
996
+ }
997
+ }
998
+ };
999
+ }
1000
+ // src/avatar/sdl.ts
1001
+ var janusAvatarTypeDefs = `"""
1002
+ The image of an account, as the application's resolvers hand it out.
1003
+ \`updatedAt\` is an ISO-8601 string, so the type needs no scalar.
1004
+ """
1005
+ type JanusAvatar {
1006
+ """
1007
+ The id the application stored the image under; changes with every upload.
1008
+ """
1009
+ id: ID!
1010
+ """
1011
+ When the avatar was set, as an ISO-8601 string.
1012
+ """
1013
+ updatedAt: String!
1014
+ """
1015
+ The URL of the application's own route that streams the image at this
1016
+ size, behind its session and access check. Never a public URL.
1017
+ """
1018
+ url(size: Int!): String!
1019
+ }
1020
+ `;
1021
+
1022
+ // src/avatar/index.ts
1023
+ function toJanusAvatar(user) {
1024
+ return user.avatar === null ? null : { userId: user.id, id: user.avatar.id, updatedAt: user.avatar.updatedAt };
1025
+ }
1026
+ // src/options.ts
1027
+ function checkWiring(caller, { auth, access, clock }) {
1028
+ if (typeof auth !== "function" && typeof auth?.authenticate !== "function") {
1029
+ throw new TypeError(`${caller}: auth is not what janus() answered — pass { auth }`);
1030
+ }
1031
+ if (access !== undefined && typeof access?.can !== "function") {
1032
+ throw new TypeError(`${caller}: access is not what permissions() answered — pass { auth, access }`);
1033
+ }
1034
+ if (clock !== undefined && typeof clock?.now !== "function") {
1035
+ throw new TypeError(`${caller}: clock is not a Clock — pass the clock given to janus(), or leave it out for the system clock`);
1036
+ }
1037
+ }
1038
+
1039
+ // src/connection/credential.ts
1040
+ var BEARER = /^\s*bearer(?:\s|$)/i;
1041
+ function credentialOf(ctx, upgrade) {
1042
+ const params = ctx.connectionParams;
1043
+ if (params !== undefined && Object.hasOwn(params, "authorization")) {
1044
+ const { authorization } = params;
1045
+ if (typeof authorization !== "string")
1046
+ return null;
1047
+ if (BEARER.test(authorization))
1048
+ return { authorization };
1049
+ }
1050
+ const request = upgrade === undefined ? ctx.extra?.request : upgrade(ctx);
1051
+ return request ?? null;
1052
+ }
1053
+ var accepted = new WeakMap;
1054
+ function accept(ctx, credential) {
1055
+ const { extra } = ctx;
1056
+ if (typeof extra !== "object" || extra === null) {
1057
+ throw new TypeError("janusConnection(): the connection's extra is not an object — pass the context graphql-ws gave onConnect");
1058
+ }
1059
+ accepted.set(extra, credential);
1060
+ }
1061
+ function acceptedOf(context) {
1062
+ const extra = context?.extra;
1063
+ if (typeof extra !== "object" || extra === null)
1064
+ return;
1065
+ return accepted.get(extra);
1066
+ }
1067
+
1068
+ // src/connection/connection.ts
1069
+ function janusConnection(options) {
1070
+ const { auth, access, type, clock } = options;
1071
+ checkWiring("janusConnection()", { auth, access, clock });
1072
+ if (options.upgrade !== undefined && typeof options.upgrade !== "function") {
1073
+ throw new TypeError("janusConnection(): upgrade is not a function — pass (ctx) => the upgrade request, or leave it out to read ctx.extra.request");
1074
+ }
1075
+ const upgrade = options.upgrade?.bind(options);
1076
+ const wiring = {
1077
+ auth,
1078
+ access,
1079
+ type,
1080
+ clock,
1081
+ caller: "janusConnection().context"
1082
+ };
1083
+ return {
1084
+ onConnect: async (ctx) => {
1085
+ const credential = credentialOf(ctx, upgrade);
1086
+ if (credential === null)
1087
+ return false;
1088
+ const instance = await resolveAuth(auth, ctx, "janusConnection()", "connection");
1089
+ const current = await instance.authenticate(credential, type === undefined ? undefined : { type });
1090
+ if (current === null)
1091
+ return false;
1092
+ accept(ctx, credential);
1093
+ return true;
1094
+ },
1095
+ context: (ctx) => ({
1096
+ janus: createJanusContext(acceptedOf(ctx), {
1097
+ ...wiring,
1098
+ context: ctx,
1099
+ what: "connection"
1100
+ })
1101
+ })
1102
+ };
1103
+ }
1104
+ // src/device.ts
1105
+ import {
1106
+ DEVICE_COOKIE,
1107
+ deviceCookie,
1108
+ deviceFromCookieHeader
1109
+ } from "@softistx/janus";
1110
+ function checked(request, call) {
1111
+ if (typeof request?.headers?.get !== "function") {
1112
+ throw new TypeError(`${call}(): the GraphQL context has no request — the device cookie is an HTTP matter, so call it from an operation served over HTTP (Yoga), not graphql-ws`);
1113
+ }
1114
+ return request;
1115
+ }
1116
+ function deviceOf(request, options = {}) {
1117
+ return deviceFromCookieHeader(checked(request, "deviceOf").headers.get("cookie"), options);
1118
+ }
1119
+ function sendDevice(request, deviceToken, options = {}) {
1120
+ sendCookie(checked(request, "sendDevice"), deviceCookie(deviceToken, options));
1121
+ }
1122
+ // src/directives/apply.ts
1123
+ import { MapperKind, mapSchema } from "@graphql-tools/utils";
1124
+ import { defaultFieldResolver } from "graphql";
1125
+
1126
+ // src/fresh.ts
1127
+ import {
1128
+ assertFresh,
1129
+ parseDuration
1130
+ } from "@softistx/janus";
1131
+ async function freshSession(janus, maxAgeMs) {
1132
+ const subject = typeof janus.principal === "function" ? await janus.principal().then(undefined, rethrown) : await janus.session().then(undefined, rethrown);
1133
+ if (subject === null)
1134
+ throw denial("UNAUTHENTICATED");
1135
+ try {
1136
+ assertFresh(subject, maxAgeMs, clockOf(janus));
1137
+ } catch (error) {
1138
+ rethrown(error);
1139
+ }
1140
+ return "via" in subject ? subject.session : subject;
1141
+ }
1142
+ async function requireFresh(ctx, maxAge) {
1143
+ if (typeof maxAge !== "string") {
1144
+ throw new TypeError("requireFresh(): maxAge is a duration with its unit, such as '10m' — a bare number would be milliseconds, where @fresh reads seconds");
1145
+ }
1146
+ const maxAgeMs = parseDuration(maxAge, "requireFresh(): maxAge");
1147
+ return freshSession(janusOf(ctx, "requireFresh()"), maxAgeMs);
1148
+ }
1149
+
1150
+ // src/directives/permission/path.ts
1151
+ var NAME = /^[_A-Za-z][_0-9A-Za-z]*$/;
1152
+ function parsePath(text) {
1153
+ const [root, ...segments] = text.split(".");
1154
+ if (root !== "args" && root !== "parent")
1155
+ return null;
1156
+ if (segments.length === 0 || !segments.every((name) => NAME.test(name))) {
1157
+ return null;
1158
+ }
1159
+ return { text, root, segments };
1160
+ }
1161
+ function targetsOf(path, parent, args) {
1162
+ const containers = walk([path.root === "args" ? args : parent], path.segments.slice(0, -1));
1163
+ if (containers === null)
1164
+ return null;
1165
+ const last = path.segments[path.segments.length - 1];
1166
+ const held = path.root === "parent" && last === "id";
1167
+ const targets = [];
1168
+ for (const container of containers) {
1169
+ for (const value of spread(container[last])) {
1170
+ const id = idOf(value);
1171
+ if (id === null)
1172
+ return null;
1173
+ targets.push({ id, holder: held ? container : null });
1174
+ }
1175
+ }
1176
+ return path.root === "parent" && targets.length === 0 ? null : targets;
1177
+ }
1178
+ function walk(values, segments) {
1179
+ let current = values;
1180
+ for (const segment of segments) {
1181
+ const next = [];
1182
+ for (const value of current) {
1183
+ if (typeof value !== "object" || value === null)
1184
+ return null;
1185
+ next.push(...spread(value[segment]));
1186
+ }
1187
+ current = next;
1188
+ }
1189
+ return current.every((value) => typeof value === "object" && value !== null) ? current : null;
1190
+ }
1191
+ function spread(value) {
1192
+ return Array.isArray(value) ? value.flat(Number.POSITIVE_INFINITY) : [value];
1193
+ }
1194
+ function idOf(value) {
1195
+ if (typeof value === "string")
1196
+ return value;
1197
+ if (typeof value === "number" && Number.isSafeInteger(value)) {
1198
+ return String(value);
1199
+ }
1200
+ return null;
1201
+ }
1202
+
1203
+ // src/directives/permission/enforce.ts
1204
+ async function enforcePermission(permission, asking) {
1205
+ const targets = targetsOf(permission.path, asking.parent, asking.args);
1206
+ if (targets === null) {
1207
+ warnNoId(permission);
1208
+ throw denial("NOT_FOUND");
1209
+ }
1210
+ const objects = await Promise.all(targets.map((target) => objectOf(permission, target, asking.ctx))).then(undefined, rethrown);
1211
+ const found = objects.filter((object) => object !== null);
1212
+ if (found.length < objects.length)
1213
+ throw denial("NOT_FOUND");
1214
+ const answers = await Promise.all(found.map((object) => ask(permission, object, asking))).then(undefined, rethrown);
1215
+ if (answers.includes(false))
1216
+ throw denial(permission.onDeny);
1217
+ }
1218
+ async function ask(permission, object, { check, user, ctx }) {
1219
+ const options = permission.condition === null ? undefined : { ctx: await permission.condition(object, ctx) };
1220
+ return check(user, permission.name, object, options);
1221
+ }
1222
+ var UNNAMEABLE = /^$|[@#()]/;
1223
+ var isNameable = (id) => !UNNAMEABLE.test(id) && !id.includes("\x00") && id.isWellFormed();
1224
+ async function objectOf(permission, { id, holder }, ctx) {
1225
+ const { type, load } = permission;
1226
+ if (!isNameable(id))
1227
+ return null;
1228
+ if (holder !== null)
1229
+ return view(holder, type, id);
1230
+ if (load === null)
1231
+ return { type, id };
1232
+ const loaded = await load(id, ctx);
1233
+ if (loaded === null)
1234
+ return null;
1235
+ if (typeof loaded !== "object") {
1236
+ throw new TypeError(`${permission.label}: loaders.${type} answered ${typeof loaded} — answer the object, or null when there is none`);
1237
+ }
1238
+ return view(loaded, type, id);
1239
+ }
1240
+ function view(object, type, id) {
1241
+ return new Proxy(Object.create(null), {
1242
+ get: (_, key) => key === "type" ? type : key === "id" ? id : Reflect.get(object, key),
1243
+ has: (_, key) => key === "type" || Reflect.has(object, key)
1244
+ });
1245
+ }
1246
+ var warned = new WeakSet;
1247
+ function warnNoId(permission) {
1248
+ if (warned.has(permission))
1249
+ return;
1250
+ warned.add(permission);
1251
+ process.emitWarning(`${permission.label} resolved no object id from ${permission.path.text} — answered NOT_FOUND`, { code: "JANUS_GRAPHQL_NO_OBJECT_ID" });
1252
+ }
1253
+
1254
+ // src/directives/guard.ts
1255
+ async function enforce(requirement, { parent, args, ctx, fresh }) {
1256
+ const janus = janusOf(ctx, requirement.label);
1257
+ const user = await janus.user().then(undefined, rethrown);
1258
+ if (user === null)
1259
+ throw denial("UNAUTHENTICATED");
1260
+ if (requirement.types !== null && !requirement.types.has(user.type)) {
1261
+ throw denial("FORBIDDEN");
1262
+ }
1263
+ if (requirement.maxAgeMs !== null) {
1264
+ await freshSession(janus, requirement.maxAgeMs);
1265
+ }
1266
+ const [first] = requirement.permissions;
1267
+ if (first === undefined)
1268
+ return;
1269
+ const check = checkOf(janus, fresh);
1270
+ if (check === null) {
1271
+ throw new TypeError(`${first.label}: ctx.janus.access is not set — pass { access } to useJanus()`);
1272
+ }
1273
+ for (const permission of requirement.permissions) {
1274
+ await enforcePermission(permission, { check, user, parent, args, ctx });
1275
+ }
1276
+ }
1277
+ function guarded(resolve, requirement) {
1278
+ return async (source, args, ctx, info) => {
1279
+ await enforce(requirement, {
1280
+ parent: source,
1281
+ args,
1282
+ ctx,
1283
+ fresh: info.operation.operation === "subscription"
1284
+ });
1285
+ return resolve(source, args, ctx, info);
1286
+ };
1287
+ }
1288
+
1289
+ // src/directives/read.ts
1290
+ import { getDirective } from "@graphql-tools/utils";
1291
+ function locations(schema, field, fieldName, typeName) {
1292
+ const type = schema.getType(typeName);
1293
+ const faces = type.getInterfaces();
1294
+ const fields = [];
1295
+ for (const face of faces) {
1296
+ const own = face.getFields()[fieldName];
1297
+ if (own !== undefined) {
1298
+ fields.push({
1299
+ where: `${face.name}.${fieldName}`,
1300
+ onType: false,
1301
+ node: own
1302
+ });
1303
+ }
1304
+ }
1305
+ return [
1306
+ ...faces.map((face) => ({ where: face.name, onType: true, node: face })),
1307
+ { where: typeName, onType: true, node: type },
1308
+ ...fields,
1309
+ { where: `${typeName}.${fieldName}`, onType: false, node: field }
1310
+ ];
1311
+ }
1312
+ function readField(schema, field, fieldName, typeName) {
1313
+ const authenticated = [];
1314
+ const fresh = [];
1315
+ const permission = [];
1316
+ for (const { where, onType, node } of locations(schema, field, fieldName, typeName)) {
1317
+ for (const args of getDirective(schema, node, "authenticated") ?? []) {
1318
+ const types = args["type"];
1319
+ authenticated.push({ where, types: types ?? null });
1320
+ }
1321
+ for (const args of getDirective(schema, node, "fresh") ?? []) {
1322
+ fresh.push({ where, maxAge: args["maxAge"] });
1323
+ }
1324
+ for (const args of getDirective(schema, node, "permission") ?? []) {
1325
+ permission.push({
1326
+ where,
1327
+ onType,
1328
+ name: args["name"],
1329
+ type: args["type"],
1330
+ id: args["id"] ?? null,
1331
+ onDeny: args["onDeny"] === "FORBIDDEN" ? "FORBIDDEN" : "NOT_FOUND"
1332
+ });
1333
+ }
1334
+ }
1335
+ return { authenticated, fresh, permission };
1336
+ }
1337
+
1338
+ // src/directives/words.ts
1339
+ var PREFIX = "applyJanusDirectives()";
1340
+ function on(where, field) {
1341
+ return where === field ? field : `${where} (read by ${field})`;
1342
+ }
1343
+ function list(names) {
1344
+ return names.map((name) => `'${name}'`).join(", ");
1345
+ }
1346
+
1347
+ // src/directives/permission/model.ts
1348
+ function modelOf(access) {
1349
+ const model = access?.model;
1350
+ if (!Array.isArray(model?.types) || model.definition?.types === undefined) {
1351
+ return null;
1352
+ }
1353
+ return model;
1354
+ }
1355
+ function namesOf(model, type) {
1356
+ const def = model.definition.types[type];
1357
+ return [
1358
+ ...Object.keys(def?.related ?? {}),
1359
+ ...Object.keys(def?.permits ?? {})
1360
+ ];
1361
+ }
1362
+ function isFromField(value) {
1363
+ return value?.kind === "fromField";
1364
+ }
1365
+ function fieldsOf(model, type) {
1366
+ const related = model.definition.types[type]?.related ?? {};
1367
+ return Object.values(related).filter(isFromField).map((def) => def.field);
1368
+ }
1369
+ function reachesCondition(model, type, name, seen = new Set) {
1370
+ const key = `${type}.${name}`;
1371
+ if (seen.has(key))
1372
+ return false;
1373
+ seen.add(key);
1374
+ const def = model.definition.types[type];
1375
+ for (const rule of def?.permits?.[name] ?? []) {
1376
+ if (typeof rule !== "string")
1377
+ return true;
1378
+ const [relation, target] = rule.split("->");
1379
+ if (target === undefined) {
1380
+ if (reachesCondition(model, type, rule, seen))
1381
+ return true;
1382
+ continue;
1383
+ }
1384
+ for (const next of arrowTargets(def?.related?.[relation])) {
1385
+ if (reachesCondition(model, next, target, seen))
1386
+ return true;
1387
+ }
1388
+ }
1389
+ return false;
1390
+ }
1391
+ function arrowTargets(relation) {
1392
+ if (isFromField(relation)) {
1393
+ return [relation.subject];
1394
+ }
1395
+ if (!Array.isArray(relation))
1396
+ return [];
1397
+ return relation.filter((holder) => typeof holder === "string").map((holder) => holder.split("#")[0]);
1398
+ }
1399
+
1400
+ // src/directives/permission/validate.ts
1401
+ function permissionCheckOf(use, field, wiring) {
1402
+ const label = `@permission on ${on(use.where, field.name)}`;
1403
+ const refuse = (why) => new TypeError(`${PREFIX}: ${label} ${why}`);
1404
+ const model = modelOf(wiring.access);
1405
+ if (model === null) {
1406
+ throw refuse("needs the permissions() instance — pass useJanus({ auth, access }), with access what permissions() answered");
1407
+ }
1408
+ checkNames(model, use, refuse);
1409
+ const text = use.id ?? (use.onType ? "parent.id" : "args.id");
1410
+ const path = parsePath(text);
1411
+ if (path === null) {
1412
+ throw refuse(`reads its id from '${text}', which is not args.<name> or parent.<name>`);
1413
+ }
1414
+ const [first] = path.segments;
1415
+ if (path.root === "args" && !field.args.includes(first)) {
1416
+ throw refuse(`reads ${path.root}.${first}, and ${field.name} takes no argument ${first}${use.id === null && use.onType === false ? ' — name the id with id: "parent.<field>" or id: "args.<name>"' : ""}`);
1417
+ }
1418
+ return {
1419
+ label,
1420
+ name: use.name,
1421
+ type: use.type,
1422
+ onDeny: use.onDeny,
1423
+ path,
1424
+ load: loaderOf(model, use.type, path, wiring, refuse),
1425
+ condition: conditionOf(model, use, wiring, refuse)
1426
+ };
1427
+ }
1428
+ function checkNames(model, use, refuse) {
1429
+ if (!model.types.includes(use.type)) {
1430
+ throw refuse(`names the object type '${use.type}', which is not one of ${list(model.types)}`);
1431
+ }
1432
+ const names = namesOf(model, use.type);
1433
+ if (!names.includes(use.name)) {
1434
+ throw refuse(`asks '${use.name}', which ${use.type} does not declare — it declares ${list(names)}`);
1435
+ }
1436
+ }
1437
+ function loaderOf(model, type, path, wiring, refuse) {
1438
+ const load = wiring.loaders?.[type];
1439
+ if (load !== undefined && typeof load !== "function") {
1440
+ throw refuse(`finds loaders.${type}, which is not a function`);
1441
+ }
1442
+ const held = path.root === "parent" && path.segments.at(-1) === "id";
1443
+ if (held)
1444
+ return null;
1445
+ if (load !== undefined)
1446
+ return load;
1447
+ const fields = fieldsOf(model, type);
1448
+ if (fields.length > 0) {
1449
+ throw refuse(`reads the ${type}'s id from ${path.text}, and ${type} reads ${list(fields)} of the object itself (fromField) — pass useJanus({ loaders: { ${type}: (id, ctx) => … } })`);
1450
+ }
1451
+ return null;
1452
+ }
1453
+ function conditionOf(model, use, wiring, refuse) {
1454
+ if (!reachesCondition(model, use.type, use.name))
1455
+ return null;
1456
+ const condition = wiring.conditions?.[use.type];
1457
+ if (typeof condition !== "function") {
1458
+ throw refuse(`asks '${use.name}' of ${use.type}, which reaches a when() — pass useJanus({ conditions: { ${use.type}: (object, ctx) => … } })`);
1459
+ }
1460
+ return condition;
1461
+ }
1462
+
1463
+ // src/directives/validate.ts
1464
+ function requirementOf(field, directives, known, wiring) {
1465
+ const { authenticated, fresh, permission } = directives;
1466
+ const [name, first] = firstOf(directives);
1467
+ if (first === undefined)
1468
+ return null;
1469
+ return {
1470
+ where: field.name,
1471
+ label: `${name} on ${on(first.where, field.name)}`,
1472
+ types: typesOf(field.name, authenticated, known),
1473
+ maxAgeMs: maxAgeOf(field.name, fresh),
1474
+ permissions: permission.map((use) => permissionCheckOf(use, field, wiring))
1475
+ };
1476
+ }
1477
+ function typesOf(field, uses, known) {
1478
+ let types = null;
1479
+ for (const { where, types: named } of uses) {
1480
+ if (named === null)
1481
+ continue;
1482
+ if (named.length === 0) {
1483
+ throw new TypeError(`${PREFIX}: @authenticated on ${on(where, field)} names no user type — leave type: out to admit any signed-in user`);
1484
+ }
1485
+ for (const name of named) {
1486
+ if (known.types !== null && !known.types.includes(name)) {
1487
+ throw new TypeError(`${PREFIX}: @authenticated on ${on(where, field)} names the user type '${name}', which is not one of ${list(known.types)}`);
1488
+ }
1489
+ }
1490
+ types = types === null ? new Set(named) : new Set(named.filter((name) => types?.has(name)));
1491
+ }
1492
+ if (types !== null && types.size === 0) {
1493
+ throw new TypeError(`${PREFIX}: the @authenticated on ${field} and on its type or interfaces admit no user type in common`);
1494
+ }
1495
+ return types;
1496
+ }
1497
+ function firstOf({
1498
+ authenticated,
1499
+ fresh,
1500
+ permission
1501
+ }) {
1502
+ if (authenticated.length > 0)
1503
+ return ["@authenticated", authenticated[0]];
1504
+ if (fresh.length > 0)
1505
+ return ["@fresh", fresh[0]];
1506
+ return ["@permission", permission[0]];
1507
+ }
1508
+ function maxAgeOf(field, uses) {
1509
+ let seconds = null;
1510
+ for (const { where, maxAge } of uses) {
1511
+ if (!Number.isSafeInteger(maxAge) || maxAge <= 0) {
1512
+ throw new TypeError(`${PREFIX}: @fresh on ${on(where, field)} asks maxAge: ${maxAge} — write a number of seconds above zero, such as maxAge: 600 for ten minutes`);
1513
+ }
1514
+ seconds = seconds === null ? maxAge : Math.min(seconds, maxAge);
1515
+ }
1516
+ return seconds === null ? null : seconds * 1000;
1517
+ }
1518
+
1519
+ // src/directives/apply.ts
1520
+ function applyJanusDirectives(schema, options) {
1521
+ const known = knownOf(options);
1522
+ return mapSchema(schema, {
1523
+ [MapperKind.OBJECT_FIELD]: (field, fieldName, typeName) => {
1524
+ const requirement = requirementOf({
1525
+ name: `${typeName}.${fieldName}`,
1526
+ args: Object.keys(field.args ?? {})
1527
+ }, readField(schema, field, fieldName, typeName), known, options);
1528
+ if (requirement === null)
1529
+ return field;
1530
+ const resolve = field.resolve ?? defaultFieldResolver;
1531
+ if (field.subscribe === undefined) {
1532
+ return { ...field, resolve: guarded(resolve, requirement) };
1533
+ }
1534
+ const onEvent = { ...requirement, maxAgeMs: null };
1535
+ return {
1536
+ ...field,
1537
+ subscribe: guarded(field.subscribe, requirement),
1538
+ resolve: guarded(resolve, onEvent)
1539
+ };
1540
+ }
1541
+ });
1542
+ }
1543
+ function knownOf({ auth, type }) {
1544
+ if (type === undefined)
1545
+ return { types: auth.types };
1546
+ if (auth.types !== null && !auth.types.includes(type)) {
1547
+ throw new TypeError(`${PREFIX}: type '${type}' is not a user type of auth — it knows ${list(auth.types)}`);
1548
+ }
1549
+ return { types: [type] };
1550
+ }
1551
+ // src/second-factor/shape.ts
1552
+ function secondFactorChallengeOut(result, request) {
1553
+ if (request !== undefined)
1554
+ sendNoStore(request);
1555
+ return {
1556
+ challenge: result.challenge,
1557
+ expiresAt: result.expiresAt.toISOString(),
1558
+ methods: result.methods,
1559
+ passkeyOptions: result.passkeyOptions === undefined ? null : JSON.stringify(result.passkeyOptions)
1560
+ };
1561
+ }
1562
+
1563
+ // src/surface/request.ts
1564
+ function requestOf(ctx, name) {
1565
+ if (ctx?.request === undefined) {
1566
+ throw new TypeError(`${name}(): the GraphQL context has no request — build the context from an HTTP request (Yoga does)`);
1567
+ }
1568
+ return ctx.request;
1569
+ }
1570
+
1571
+ // src/surface/signed-in.ts
1572
+ function signedInAnswer({ auth, answerToken, device }, request, done) {
1573
+ if (answerToken) {
1574
+ sendNoStore(request);
1575
+ } else {
1576
+ sendCookie(request, auth.cookie.serialize(done.token, done.session));
1577
+ }
1578
+ if (device !== undefined && done.deviceToken !== null) {
1579
+ sendDevice(request, done.deviceToken, device);
1580
+ }
1581
+ return {
1582
+ user: done.user,
1583
+ token: answerToken ? done.token : null,
1584
+ userId: done.user.id,
1585
+ expiresAt: done.session.expiresAt.toISOString(),
1586
+ newDevice: done.newDevice
1587
+ };
1588
+ }
1589
+
1590
+ // src/invitations/shape.ts
1591
+ var iso2 = (date) => date === null ? null : date.toISOString();
1592
+ var invitationOut = (i) => ({
1593
+ id: i.id,
1594
+ scope: i.scope,
1595
+ email: i.email,
1596
+ name: i.name,
1597
+ role: i.role,
1598
+ locale: i.locale,
1599
+ ref: i.ref,
1600
+ type: i.type,
1601
+ status: i.status,
1602
+ invitedBy: i.invitedBy,
1603
+ createdAt: i.createdAt.toISOString(),
1604
+ updatedAt: i.updatedAt.toISOString(),
1605
+ expiresAt: i.expiresAt.toISOString(),
1606
+ acceptedBy: i.acceptedBy,
1607
+ acceptedAt: iso2(i.acceptedAt),
1608
+ revokedAt: iso2(i.revokedAt),
1609
+ revokedBy: i.revokedBy,
1610
+ resentBy: i.resentBy
1611
+ });
1612
+ var previewOut = (p, organization = null) => ({
1613
+ id: p.id,
1614
+ scope: p.scope,
1615
+ email: p.email,
1616
+ name: p.name,
1617
+ role: p.role,
1618
+ locale: p.locale,
1619
+ type: p.type,
1620
+ organization,
1621
+ expiresAt: p.expiresAt.toISOString(),
1622
+ needsPassword: p.needsPassword
1623
+ });
1624
+ var pageOut = (page, counted) => ({
1625
+ items: page.items.map(invitationOut),
1626
+ nextCursor: page.nextCursor,
1627
+ counted
1628
+ });
1629
+ function textFiltersOf(role, ref) {
1630
+ if (role === "")
1631
+ throw badInput("role must be a non-empty string", "role");
1632
+ if (ref === "")
1633
+ throw badInput("ref must be a non-empty string", "ref");
1634
+ return {
1635
+ ...role == null ? {} : { role },
1636
+ ...ref == null ? {} : { ref }
1637
+ };
1638
+ }
1639
+ function orderOf(order) {
1640
+ return order == null ? {} : { order: order === "NEWEST" ? "desc" : "asc" };
1641
+ }
1642
+ function lapsedOf(lapsed) {
1643
+ return lapsed == null ? {} : { lapsed: lapsed === "ONLY" ? "only" : "exclude" };
1644
+ }
1645
+ var INVITATION_LIMITS = {
1646
+ code: 43,
1647
+ password: 1024,
1648
+ scope: 512,
1649
+ role: 100,
1650
+ name: 100,
1651
+ email: 254,
1652
+ locale: 35,
1653
+ ref: 100
1654
+ };
1655
+ var TRIMMED = ["name", "email"];
1656
+ function boundedArgs(args) {
1657
+ for (const [field, value] of Object.entries(args)) {
1658
+ if (typeof value !== "string")
1659
+ continue;
1660
+ const max = INVITATION_LIMITS[field];
1661
+ const length = TRIMMED.includes(field) ? value.trim().length : value.length;
1662
+ if (length > max) {
1663
+ throw badInput(`${field} must be at most ${max} characters`, field);
1664
+ }
1665
+ }
1666
+ }
1667
+ var STATUSES = ["pending", "accepted", "revoked"];
1668
+ function statusOf3(status) {
1669
+ if (status == null)
1670
+ return {};
1671
+ if (!STATUSES.includes(status)) {
1672
+ throw badInput("status must be pending, accepted or revoked", "status");
1673
+ }
1674
+ return { status };
1675
+ }
1676
+
1677
+ // src/invitations/resolvers/anonymous.ts
1678
+ function invitationPreview(deps) {
1679
+ return async (_, { code }, ctx) => {
1680
+ boundedArgs({ code });
1681
+ const preview = await deps.invitations.preview(code).then(undefined, rethrown);
1682
+ noStoreOf(ctx);
1683
+ const organization = await deps.options.describeScope?.(preview.scope, ctx);
1684
+ return previewOut(preview, organization?.name ?? null);
1685
+ };
1686
+ }
1687
+ function acceptedOut(deps, request, done) {
1688
+ const { invitation } = done;
1689
+ if (done.status === "signedIn") {
1690
+ return {
1691
+ status: "signedIn",
1692
+ ...signedInAnswer(deps, request, { ...done, user: done.user }),
1693
+ invitationId: invitation.id,
1694
+ scope: invitation.scope,
1695
+ role: invitation.role
1696
+ };
1697
+ }
1698
+ if (done.status === "secondFactor") {
1699
+ return {
1700
+ status: "secondFactor",
1701
+ ...secondFactorChallengeOut(done, request),
1702
+ invitationId: invitation.id,
1703
+ scope: invitation.scope
1704
+ };
1705
+ }
1706
+ return {
1707
+ status: "signIn",
1708
+ invitationId: invitation.id,
1709
+ scope: invitation.scope,
1710
+ email: invitation.email
1711
+ };
1712
+ }
1713
+ function acceptInvitation(deps) {
1714
+ return async (_, { code, password }, ctx) => {
1715
+ boundedArgs({ code, password });
1716
+ const request = requestOf(ctx, "invitationResolvers");
1717
+ sendNoStore(request);
1718
+ const done = await deps.invitations.accept({
1719
+ code,
1720
+ ...password == null ? {} : { password },
1721
+ ...deps.device === undefined ? {} : { device: deviceOf(request, deps.device) }
1722
+ }).then(undefined, rethrown);
1723
+ return acceptedOut(deps, request, done);
1724
+ };
1725
+ }
1726
+
1727
+ // src/invitations/resolvers/deps.ts
1728
+ import { GraphQLError as GraphQLError11 } from "graphql";
1729
+ function depsOf2(options) {
1730
+ const { auth } = options;
1731
+ if (auth.invitations === undefined) {
1732
+ throw new TypeError("invitationResolvers(): auth has no invitations — give janus() `invitations`");
1733
+ }
1734
+ if (typeof options.authorize !== "function") {
1735
+ throw new TypeError("invitationResolvers(): `authorize` is required — the core authorises nobody, so say who may invite into a scope");
1736
+ }
1737
+ if (options.sendInvitation === undefined && options.answerCode !== true) {
1738
+ throw new TypeError("invitationResolvers(): give `sendInvitation` (deliver the code) or `answerCode: true` — the code would reach nobody");
1739
+ }
1740
+ return {
1741
+ auth,
1742
+ invitations: auth.invitations,
1743
+ options,
1744
+ answerCode: options.answerCode ?? false,
1745
+ answerToken: options.answerToken ?? false,
1746
+ device: options.device === true ? {} : options.device
1747
+ };
1748
+ }
1749
+ async function stored({ invitations }, scope, id) {
1750
+ return invitations.get({ id, scope }).then(undefined, rethrown);
1751
+ }
1752
+ async function owner({ options }, action, scope, ctx, about = {}) {
1753
+ const user = await requireUser(ctx, options.inviterType === undefined ? {} : { type: options.inviterType });
1754
+ const known = typeof about === "function" ? await about() : about;
1755
+ if (known === null) {
1756
+ try {
1757
+ await options.authorize(action, { user, scope }, ctx);
1758
+ } catch (error) {
1759
+ if (error instanceof GraphQLError11)
1760
+ throw error;
1761
+ }
1762
+ throw denial("NOT_FOUND");
1763
+ }
1764
+ if (await options.authorize(action, { user, scope, ...known }, ctx) !== true) {
1765
+ throw denial("NOT_FOUND");
1766
+ }
1767
+ return user;
1768
+ }
1769
+
1770
+ // src/invitations/resolvers/owner.ts
1771
+ function invitations(deps) {
1772
+ return async (_, { scope, status, role, ref, lapsed, order, limit, after }, ctx) => {
1773
+ const filter = {
1774
+ ...statusOf3(status),
1775
+ ...textFiltersOf(role, ref),
1776
+ ...lapsedOf(lapsed)
1777
+ };
1778
+ const asked = {
1779
+ ...filter,
1780
+ ...orderOf(order),
1781
+ ...limitOf(limit),
1782
+ ...after == null ? {} : { after }
1783
+ };
1784
+ await owner(deps, "list", scope, ctx, { page: asked });
1785
+ const page = await deps.invitations.list(scope, asked).then(undefined, rethrown);
1786
+ return pageOut(page, { scope, filter });
1787
+ };
1788
+ }
1789
+ function totalCount(deps) {
1790
+ return async ({ counted }) => {
1791
+ if (counted === undefined) {
1792
+ throw new Error("totalCount is answered only on pages `invitations` returns");
1793
+ }
1794
+ return deps.invitations.count(counted.scope, counted.filter).then(undefined, rethrown);
1795
+ };
1796
+ }
1797
+ async function delivered(deps, action, done, ctx) {
1798
+ await deps.options.sendInvitation?.({ action, invitation: done.invitation, code: done.code }, ctx);
1799
+ noStoreOf(ctx);
1800
+ return {
1801
+ invitation: invitationOut(done.invitation),
1802
+ code: deps.answerCode ? done.code : null
1803
+ };
1804
+ }
1805
+ function issueInvitation(deps) {
1806
+ return async (_, args, ctx) => {
1807
+ boundedArgs({
1808
+ scope: args.scope,
1809
+ email: args.email,
1810
+ name: args.name,
1811
+ role: args.role,
1812
+ locale: args.locale,
1813
+ ref: args.ref
1814
+ });
1815
+ const { type: _type, ...rest } = args;
1816
+ const input = {
1817
+ scope: args.scope,
1818
+ email: args.email,
1819
+ name: args.name,
1820
+ role: args.role,
1821
+ ...args.locale === undefined ? {} : { locale: args.locale },
1822
+ ...args.ref === undefined ? {} : { ref: args.ref },
1823
+ ...args.type === undefined ? {} : { type: args.type }
1824
+ };
1825
+ const user = await owner(deps, "issue", args.scope, ctx, { input });
1826
+ const done = await deps.invitations.issue({
1827
+ ...rest,
1828
+ ...args.type == null ? {} : { type: args.type },
1829
+ invitedBy: user
1830
+ }).then(undefined, rethrown);
1831
+ return delivered(deps, "issue", done, ctx);
1832
+ };
1833
+ }
1834
+ function resendInvitation(deps) {
1835
+ return async (_, { scope, id }, ctx) => {
1836
+ const user = await owner(deps, "resend", scope, ctx, async () => {
1837
+ const invitation = await stored(deps, scope, id);
1838
+ return invitation === null ? null : { invitation };
1839
+ });
1840
+ const done = await deps.invitations.resend({ id, scope, by: user.id }).then(undefined, rethrown);
1841
+ return delivered(deps, "resend", done, ctx);
1842
+ };
1843
+ }
1844
+ function revokeInvitation(deps) {
1845
+ return async (_, { scope, id }, ctx) => {
1846
+ const user = await owner(deps, "revoke", scope, ctx, async () => {
1847
+ const invitation = await stored(deps, scope, id);
1848
+ return invitation === null ? null : { invitation };
1849
+ });
1850
+ const revoked = await deps.invitations.revoke({ id, scope, by: user.id }).then(undefined, rethrown);
1851
+ return invitationOut(revoked);
1852
+ };
1853
+ }
1854
+
1855
+ // src/invitations/resolvers/index.ts
1856
+ function invitationResolvers(options) {
1857
+ const deps = depsOf2(options);
1858
+ return {
1859
+ Query: {
1860
+ invitations: invitations(deps),
1861
+ invitationPreview: invitationPreview(deps)
1862
+ },
1863
+ Mutation: {
1864
+ issueInvitation: issueInvitation(deps),
1865
+ resendInvitation: resendInvitation(deps),
1866
+ revokeInvitation: revokeInvitation(deps),
1867
+ acceptInvitation: acceptInvitation(deps)
1868
+ },
1869
+ JanusInvitationPage: { totalCount: totalCount(deps) },
1870
+ InvitationAcceptResult: {
1871
+ __resolveType: (result) => result.status === "signedIn" ? "InvitationSignedIn" : result.status === "secondFactor" ? "InvitationSecondFactor" : "InvitationSignIn"
1872
+ }
1873
+ };
1874
+ }
1875
+ // src/invitations/sdl/accept.ts
1876
+ var acceptTypes = `"""
1877
+ What a code names, for the page the invitee lands on: the content of the
1878
+ invitation, nothing about who sent it or how it stands.
1879
+ """
1880
+ type JanusInvitationPreview {
1881
+ id: ID!
1882
+ scope: String!
1883
+ email: String!
1884
+ name: String!
1885
+ role: String!
1886
+ locale: String
1887
+ """
1888
+ The user type the invitation is for, so the page can adapt its wording or
1889
+ flow to it.
1890
+ """
1891
+ type: String!
1892
+ """
1893
+ The name of the scope's organization (school, clinic, workspace), from the
1894
+ application's describeScope option; null when it names none or is not
1895
+ given.
1896
+ """
1897
+ organization: String
1898
+ expiresAt: String!
1899
+ """
1900
+ Whether the page should ask for a password: false for a user type with no
1901
+ password, or somebody who already has an account with a proved e-mail and a
1902
+ password.
1903
+ """
1904
+ needsPassword: Boolean!
1905
+ }
1906
+
1907
+ """
1908
+ The invitation was accepted and a session was opened: a new invitee, an
1909
+ account whose e-mail was never proved, or a proved account with no password
1910
+ yet, given one.
1911
+ """
1912
+ type InvitationSignedIn {
1913
+ """
1914
+ The session token, only with \`answerToken\`; otherwise the session
1915
+ cookie is set and this is null.
1916
+ """
1917
+ token: String
1918
+ userId: ID!
1919
+ """
1920
+ When the session ends, as an ISO-8601 string.
1921
+ """
1922
+ expiresAt: String!
1923
+ newDevice: Boolean!
1924
+ invitationId: ID!
1925
+ scope: String!
1926
+ role: String!
1927
+ }
1928
+
1929
+ """
1930
+ The invitation was accepted and a second factor is still to prove: confirm
1931
+ it with the challenge. No session is open yet. The challenge is a secret:
1932
+ never in a URL or a log.
1933
+ """
1934
+ type InvitationSecondFactor {
1935
+ challenge: String!
1936
+ """
1937
+ When the challenge lapses, as an ISO-8601 string.
1938
+ """
1939
+ expiresAt: String!
1940
+ """
1941
+ What can answer the challenge: \`totp\` always, and \`passkey\` when the
1942
+ user holds one.
1943
+ """
1944
+ methods: [String!]!
1945
+ """
1946
+ The JSON text for \`navigator.credentials.get({ publicKey })\`, present
1947
+ exactly when \`methods\` holds \`passkey\`.
1948
+ """
1949
+ passkeyOptions: String
1950
+ invitationId: ID!
1951
+ scope: String!
1952
+ }
1953
+
1954
+ """
1955
+ The address belongs to a proved user who already has a password (the password
1956
+ given is ignored), or who has none and gave none. They are NOT signed in: an
1957
+ invitation proves the inbox, not who holds the account. Send them to the
1958
+ sign-in page.
1959
+ """
1960
+ type InvitationSignIn {
1961
+ invitationId: ID!
1962
+ scope: String!
1963
+ email: String!
1964
+ }
1965
+
1966
+ union InvitationAcceptResult =
1967
+ | InvitationSignedIn
1968
+ | InvitationSecondFactor
1969
+ | InvitationSignIn`;
1970
+
1971
+ // src/invitations/sdl/owner.ts
1972
+ var ownerTypes = `"""
1973
+ An invitation into a scope (an organization, a team), as its owners see it.
1974
+ The code is never here: \`issueInvitation\` and \`resendInvitation\` answer it
1975
+ once.
1976
+ """
1977
+ type JanusInvitation {
1978
+ id: ID!
1979
+ """
1980
+ The organization (or any grouping) the invitation is into.
1981
+ """
1982
+ scope: String!
1983
+ email: String!
1984
+ name: String!
1985
+ role: String!
1986
+ locale: String
1987
+ """
1988
+ The application's opaque reference the invitation was issued with (its own
1989
+ record), or null.
1990
+ """
1991
+ ref: String
1992
+ """
1993
+ The user type the invitation is for, one of the configured types; an
1994
+ invitation stored before types existed reads as the first one.
1995
+ """
1996
+ type: String!
1997
+ """
1998
+ \`pending\`, \`accepted\` or \`revoked\`. A \`pending\` invitation past
1999
+ \`expiresAt\` is lapsed: it cannot be previewed or accepted, and
2000
+ \`resendInvitation\` gives it a new code.
2001
+ """
2002
+ status: String!
2003
+ """
2004
+ The id of the user who sent it, or null when the system issued it.
2005
+ """
2006
+ invitedBy: ID
2007
+ """
2008
+ Timestamps, as ISO-8601 strings.
2009
+ """
2010
+ createdAt: String!
2011
+ updatedAt: String!
2012
+ expiresAt: String!
2013
+ acceptedBy: ID
2014
+ acceptedAt: String
2015
+ revokedAt: String
2016
+ """
2017
+ The id of the user who revoked it, or null.
2018
+ """
2019
+ revokedBy: ID
2020
+ """
2021
+ The id of the user who last sent it again, or null.
2022
+ """
2023
+ resentBy: ID
2024
+ }
2025
+
2026
+ """
2027
+ An invitation just issued or sent again.
2028
+ """
2029
+ type JanusIssuedInvitation {
2030
+ invitation: JanusInvitation!
2031
+ """
2032
+ The code, a secret: null unless \`answerCode\` is on. It belongs in the
2033
+ invitation e-mail's link, never in a URL you log or a response a cache
2034
+ keeps (the response is \`no-store\`).
2035
+ """
2036
+ code: String
2037
+ }
2038
+
2039
+ """
2040
+ One page of a scope's invitations. \`nextCursor\` is null on the last page.
2041
+ """
2042
+ type JanusInvitationPage {
2043
+ items: [JanusInvitation!]!
2044
+ nextCursor: String
2045
+ """
2046
+ How many invitations of the scope match the filters (\`status\`, \`role\`,
2047
+ \`ref\`), whatever the paging. Counted only when selected, and answered only on a page
2048
+ \`invitations\` returned (a page of your own has no count and fails). A \`pending\`
2049
+ invitation past \`expiresAt\` still counts, as it is still listed.
2050
+ """
2051
+ totalCount: Int!
2052
+ }
2053
+
2054
+ """
2055
+ The order of a scope's invitations: by creation.
2056
+ """
2057
+ enum JanusInvitationOrder {
2058
+ OLDEST
2059
+ NEWEST
2060
+ }
2061
+
2062
+ """
2063
+ Whether lapsed invitations (pending, past their expiry) are left out of a
2064
+ list: \`EXCLUDE\` drops them and keeps every other invitation, \`ONLY\` keeps
2065
+ only them.
2066
+ """
2067
+ enum JanusInvitationLapsed {
2068
+ EXCLUDE
2069
+ ONLY
2070
+ }`;
2071
+ var ownerOperations = `extend type Query {
2072
+ """
2073
+ One scope's invitations, \`OLDEST\` first unless \`order\` says \`NEWEST\`.
2074
+ \`status\` is \`pending\`, \`accepted\` or \`revoked\` (BAD_USER_INPUT
2075
+ otherwise); \`role\` and \`ref\` keep the invitations with exactly that role
2076
+ or reference; \`lapsed\` is \`EXCLUDE\` to leave out the lapsed (pending,
2077
+ past \`expiresAt\`) or \`ONLY\` to keep just them, and \`totalCount\` follows
2078
+ it; \`limit\` is a positive integer, 20 by default and at most
2079
+ 100; \`after\` is the previous page's \`nextCursor\`, in the same order. An
2080
+ empty \`role\` or \`ref\` is BAD_USER_INPUT. Each BAD_USER_INPUT (and
2081
+ INVALID_CURSOR) names the argument in \`extensions.field\`.
2082
+ NOT_FOUND when the application's \`authorize\` refuses the scope.
2083
+ """
2084
+ invitations(
2085
+ scope: String!
2086
+ status: String
2087
+ role: String
2088
+ ref: String
2089
+ lapsed: JanusInvitationLapsed
2090
+ order: JanusInvitationOrder
2091
+ limit: Int
2092
+ after: String
2093
+ ): JanusInvitationPage! @authenticated
2094
+ """
2095
+ What \`code\` names, without spending it. INVITATION_INVALID (400, \`extensions.reason\`: unknown,
2096
+ expired, accepted or revoked) for any code that names no pending, unlapsed
2097
+ invitation. Open to anybody: the
2098
+ code is a secret (send it in the variables of a POST, never in a URL), and
2099
+ the field is not throttled here. A \`code\` longer than 43 characters is
2100
+ BAD_USER_INPUT (400, \`field: 'code'\`).
2101
+ """
2102
+ invitationPreview(code: String!): JanusInvitationPreview!
2103
+ }
2104
+
2105
+ extend type Mutation {
2106
+ """
2107
+ Invites \`email\` into \`scope\` with \`role\`; the inviter is the signed-in
2108
+ user. Issuing again for an address that has a pending invitation revokes
2109
+ it and makes a new one. INVITATION_INVALID (\`field\`) for an input that
2110
+ cannot be kept, INVITATION_LIMIT (\`maxActive\`) when the scope is full,
2111
+ NOT_FOUND when \`authorize\` refuses. \`ref\` is an opaque reference to your
2112
+ own record (1 to 100 characters), answered back and usable as a filter of
2113
+ \`invitations\`. An argument over its maximum (\`scope\` 512, \`email\` 254, \`name\`,
2114
+ \`role\` and \`ref\` 100, \`locale\` 35 characters) is BAD_USER_INPUT (400, \`field\`)
2115
+ before \`authorize\` runs. \`type\` is the user type the invitee becomes: required when
2116
+ the instance configures several user types (null or absent means the
2117
+ instance's single type), INVITATION_INVALID
2118
+ (\`field: 'type'\`) when absent then, or when it names none of them.
2119
+ """
2120
+ issueInvitation(
2121
+ scope: String!
2122
+ email: String!
2123
+ name: String!
2124
+ role: String!
2125
+ locale: String
2126
+ ref: String
2127
+ type: String
2128
+ ): JanusIssuedInvitation! @authenticated
2129
+ """
2130
+ A new code and lifetime for a pending invitation, lapsed or not; the old
2131
+ code stops working. NOT_FOUND for an id of another scope,
2132
+ INVITATION_NOT_PENDING (409) when it is accepted or revoked.
2133
+ """
2134
+ resendInvitation(scope: String!, id: ID!): JanusIssuedInvitation!
2135
+ @authenticated
2136
+ """
2137
+ Takes a pending invitation back. NOT_FOUND as \`resendInvitation\`,
2138
+ INVITATION_NOT_PENDING (409) when it is accepted or already revoked.
2139
+ """
2140
+ revokeInvitation(scope: String!, id: ID!): JanusInvitation! @authenticated
2141
+ """
2142
+ Accepts the invitation \`code\` names: the code proves the invitee's inbox.
2143
+ A new invitee, an account whose e-mail was never proved, or a proved account
2144
+ with no password yet (given one) is signed in (the session cookie, or \`token\`
2145
+ with \`answerToken\`); a proved user who already has a password (the password
2146
+ given is ignored), or who has none and gave none, is answered
2147
+ \`InvitationSignIn\` and is not. INVITATION_INVALID (400, \`extensions.reason\`: unknown, expired, accepted or revoked) for a code that names no pending
2148
+ invitation, PASSWORD_REQUIRED (400) when a password is needed and absent.
2149
+ INVITATION_REFUSED (403) when the application's \`beforeAccept\` refused, with
2150
+ nothing written. A \`code\` over 43 characters or a \`password\` over 1024 is
2151
+ BAD_USER_INPUT (400, \`field\`), the code unspent.
2152
+ Open to anybody and not throttled here.
2153
+ """
2154
+ acceptInvitation(code: String!, password: String): InvitationAcceptResult!
2155
+ }`;
2156
+
2157
+ // src/invitations/sdl/index.ts
2158
+ var janusInvitationTypeDefs = `${ownerTypes}
2159
+
2160
+ ${acceptTypes}
2161
+
2162
+ ${ownerOperations}
2163
+ `;
2164
+ // src/surface/api.ts
2165
+ function apiOf(auth, type, spec) {
2166
+ const top = auth;
2167
+ const holder = type === undefined || top[spec.key] !== undefined ? top : auth[type];
2168
+ if (!spec.complete(holder)) {
2169
+ throw new TypeError(`${spec.name}(): ${type === undefined ? spec.missing : spec.missingOf(type)}`);
2170
+ }
2171
+ return holder;
2172
+ }
2173
+
2174
+ // src/passkeys/deps.ts
2175
+ var MANAGE = {
2176
+ name: "passkeyResolvers",
2177
+ key: "passkeys",
2178
+ complete: (holder) => holder?.passkeys !== undefined,
2179
+ missing: "auth has no passkeys — give janus() `passkeys`; with several user types, name the one with `type`",
2180
+ missingOf: (type) => `auth.${type} has no passkeys — give janus() \`passkeys\`, and name a user type that exists`
2181
+ };
2182
+ var SURFACE = {
2183
+ name: "passkeyResolvers",
2184
+ key: "passkeys",
2185
+ complete: (holder) => holder?.passkeys !== undefined && holder.secondFactor?.confirmPasskey !== undefined,
2186
+ missing: "auth has no passkeys — give janus() `passkeys` and a `secondFactor`; with several user types, name the one with `type`",
2187
+ missingOf: (type) => `auth.${type} has no passkeys — give janus() \`passkeys\` and a \`secondFactor\`, and name a user type that exists`
2188
+ };
2189
+ var FIRST_FACTOR = {
2190
+ name: "passkeyResolvers",
2191
+ key: "passkeys",
2192
+ complete: (holder) => typeof holder?.passkeys?.signInOptions === "function" && typeof holder.passkeys.signIn === "function",
2193
+ missing: "firstFactor needs an auth with passkeys.firstFactor — give janus() `passkeys: { firstFactor: true }`",
2194
+ missingOf: (type) => `firstFactor needs auth.${type} with passkeys.firstFactor — give janus() \`passkeys: { firstFactor: true }\`, and name a user type that exists`
2195
+ };
2196
+ function binder(type, firstFactor) {
2197
+ const only = type === undefined ? {} : { type };
2198
+ return (auth) => ({
2199
+ auth,
2200
+ api: apiOf(auth, type, firstFactor ? MANAGE : SURFACE),
2201
+ first: firstFactor ? apiOf(auth, type, FIRST_FACTOR) : undefined,
2202
+ session: (ctx) => auth.authenticate(requestOf(ctx, "passkeyResolvers"), only).then(undefined, rethrown),
2203
+ userOf: (ctx) => requireUser(ctx, only)
2204
+ });
2205
+ }
2206
+
2207
+ // src/passkeys/shape.ts
2208
+ import { GraphQLError as GraphQLError12 } from "graphql";
2209
+ var passkeyOut = (passkey) => ({
2210
+ credentialId: passkey.credentialId,
2211
+ name: passkey.name,
2212
+ transports: passkey.transports,
2213
+ aaguid: passkey.aaguid,
2214
+ backupEligible: passkey.backupEligible,
2215
+ backedUp: passkey.backedUp,
2216
+ createdAt: passkey.createdAt.toISOString(),
2217
+ lastUsedAt: passkey.lastUsedAt?.toISOString() ?? null
2218
+ });
2219
+ function jsonOf(text, argument) {
2220
+ try {
2221
+ return JSON.parse(text);
2222
+ } catch {
2223
+ throw new GraphQLError12(`${argument} must be a JSON string`, {
2224
+ extensions: { code: "BAD_USER_INPUT", http: { status: 400 } }
2225
+ });
2226
+ }
2227
+ }
2228
+
2229
+ // src/passkeys/sign-in.resolvers.ts
2230
+ function passkeySignInOptions({
2231
+ bound
2232
+ }) {
2233
+ return async (_, __, ctx) => {
2234
+ const first = (await bound(ctx)).first;
2235
+ const made = await first.passkeys.signInOptions().then(undefined, rethrown);
2236
+ noStoreOf(ctx);
2237
+ return {
2238
+ options: JSON.stringify(made.options),
2239
+ challenge: made.challenge,
2240
+ expiresAt: made.expiresAt.toISOString()
2241
+ };
2242
+ };
2243
+ }
2244
+ function passkeySignIn({
2245
+ bound,
2246
+ answerToken,
2247
+ device
2248
+ }) {
2249
+ return async (_, { challenge, assertion }, ctx) => {
2250
+ const { auth, first: held } = await bound(ctx);
2251
+ const first = held;
2252
+ const request = requestOf(ctx, "passkeyResolvers");
2253
+ const parsed = jsonOf(assertion, "assertion");
2254
+ const done = await first.passkeys.signIn(challenge, parsed, device === undefined ? undefined : { device: deviceOf(request, device) }).then(undefined, rethrown);
2255
+ return signedInAnswer({ auth, answerToken, device }, request, done);
2256
+ };
2257
+ }
2258
+
2259
+ // src/passkeys/resolvers.ts
2260
+ function passkeyResolvers(options) {
2261
+ const { answerToken = false, firstFactor = false } = options;
2262
+ const source = options.auth;
2263
+ const type = options.type;
2264
+ const device = options.device === true ? {} : options.device;
2265
+ const bind = binder(type, firstFactor === true);
2266
+ const fixed = typeof source === "function" ? undefined : bind(source);
2267
+ const chosenBefore = new WeakMap;
2268
+ const deps = {
2269
+ answerToken,
2270
+ device,
2271
+ bound: async (ctx) => {
2272
+ if (fixed !== undefined)
2273
+ return fixed;
2274
+ const chosen = await source(ctx);
2275
+ if (chosen === null || chosen === undefined) {
2276
+ throw denial("UNAUTHENTICATED");
2277
+ }
2278
+ const instance = chosen;
2279
+ const known = chosenBefore.get(instance);
2280
+ if (known !== undefined)
2281
+ return known;
2282
+ const made = bind(instance);
2283
+ chosenBefore.set(instance, made);
2284
+ return made;
2285
+ }
2286
+ };
2287
+ const map = {
2288
+ Query: {
2289
+ passkeys: passkeys(deps),
2290
+ passkeyRegistrationOptions: passkeyRegistrationOptions(deps),
2291
+ ...firstFactor === true ? { passkeySignInOptions: passkeySignInOptions(deps) } : {}
2292
+ },
2293
+ Mutation: {
2294
+ registerPasskey: registerPasskey(deps),
2295
+ renamePasskey: renamePasskey(deps),
2296
+ removePasskey: removePasskey(deps),
2297
+ confirmSecondFactorPasskey: confirmSecondFactorPasskey(deps),
2298
+ ...firstFactor === true ? { passkeySignIn: passkeySignIn(deps) } : {}
2299
+ }
2300
+ };
2301
+ return map;
2302
+ }
2303
+ function passkeys({ bound }) {
2304
+ return async (_, __, ctx) => {
2305
+ const { api, userOf } = await bound(ctx);
2306
+ const user = await userOf(ctx);
2307
+ const held = await api.passkeys.list(user).then(undefined, rethrown);
2308
+ return held.map(passkeyOut);
2309
+ };
2310
+ }
2311
+ function passkeyRegistrationOptions({
2312
+ bound
2313
+ }) {
2314
+ return async (_, __, ctx) => {
2315
+ const { api, userOf } = await bound(ctx);
2316
+ const user = await userOf(ctx);
2317
+ const made = await api.passkeys.registrationOptions(user).then(undefined, rethrown);
2318
+ noStoreOf(ctx);
2319
+ return {
2320
+ options: JSON.stringify(made.options),
2321
+ challenge: made.challenge,
2322
+ expiresAt: made.expiresAt.toISOString()
2323
+ };
2324
+ };
2325
+ }
2326
+ function registerPasskey({ bound }) {
2327
+ return async (_, { challenge, response, name }, ctx) => {
2328
+ const { api, session } = await bound(ctx);
2329
+ const current = await session(ctx);
2330
+ if (current === null)
2331
+ throw denial("UNAUTHENTICATED");
2332
+ const parsed = jsonOf(response, "response");
2333
+ return passkeyOut(await api.passkeys.register(current, { challenge, response: parsed, name }).then(undefined, rethrown));
2334
+ };
2335
+ }
2336
+ function renamePasskey({ bound }) {
2337
+ return async (_, { credentialId, name }, ctx) => {
2338
+ const { api, userOf } = await bound(ctx);
2339
+ const user = await userOf(ctx);
2340
+ return api.passkeys.rename(user, credentialId, name).then(undefined, rethrown);
2341
+ };
2342
+ }
2343
+ function removePasskey({ bound }) {
2344
+ return async (_, { credentialId }, ctx) => {
2345
+ const { api, session } = await bound(ctx);
2346
+ const current = await session(ctx);
2347
+ if (current === null)
2348
+ throw denial("UNAUTHENTICATED");
2349
+ return api.passkeys.remove(current, credentialId).then(undefined, rethrown);
2350
+ };
2351
+ }
2352
+ function confirmSecondFactorPasskey({
2353
+ bound,
2354
+ answerToken,
2355
+ device
2356
+ }) {
2357
+ return async (_, { challenge, assertion }, ctx) => {
2358
+ const { auth, api } = await bound(ctx);
2359
+ const request = requestOf(ctx, "passkeyResolvers");
2360
+ const parsed = jsonOf(assertion, "assertion");
2361
+ if (api.secondFactor?.confirmPasskey === undefined) {
2362
+ throw new TypeError("passkeyResolvers: confirmSecondFactorPasskey needs janus() `secondFactor`.");
2363
+ }
2364
+ const done = await api.secondFactor.confirmPasskey(challenge, parsed, device === undefined ? undefined : { device: deviceOf(request, device) }).then(undefined, rethrown);
2365
+ return signedInAnswer({ auth, answerToken, device }, request, done);
2366
+ };
2367
+ }
2368
+ // src/passkeys/sdl.ts
2369
+ var janusPasskeyTypeDefs = `"""
2370
+ One passkey a user registered. Never carries the public key or the counter.
2371
+ """
2372
+ type JanusPasskey {
2373
+ """
2374
+ The authenticator's credential id, base64url. Pass it back to
2375
+ \`renamePasskey\` and \`removePasskey\`.
2376
+ """
2377
+ credentialId: ID!
2378
+ """
2379
+ The name the user gave it.
2380
+ """
2381
+ name: String!
2382
+ """
2383
+ What the authenticator reported at registration (\`internal\`, \`usb\`).
2384
+ """
2385
+ transports: [String!]!
2386
+ """
2387
+ The authenticator model, for an icon or a label.
2388
+ """
2389
+ aaguid: String!
2390
+ """
2391
+ Whether the credential may be synced across the user's devices.
2392
+ """
2393
+ backupEligible: Boolean!
2394
+ """
2395
+ Whether it is synced now.
2396
+ """
2397
+ backedUp: Boolean!
2398
+ """
2399
+ When it was registered, as an ISO-8601 string.
2400
+ """
2401
+ createdAt: String!
2402
+ """
2403
+ When it last answered a challenge, as an ISO-8601 string, or null.
2404
+ """
2405
+ lastUsedAt: String
2406
+ }
2407
+
2408
+ """
2409
+ A registration begun: give \`options\` to the browser and keep \`challenge\`
2410
+ until \`registerPasskey\`.
2411
+ """
2412
+ type JanusPasskeyRegistration {
2413
+ """
2414
+ The JSON text for \`navigator.credentials.create({ publicKey })\`, as the
2415
+ verifier shaped it.
2416
+ """
2417
+ options: String!
2418
+ """
2419
+ The secret \`registerPasskey\` spends, once. Never in a URL or a log.
2420
+ """
2421
+ challenge: String!
2422
+ """
2423
+ When the challenge lapses, as an ISO-8601 string.
2424
+ """
2425
+ expiresAt: String!
2426
+ }
2427
+
2428
+ """
2429
+ A passkey sign-in completed: the session cookie is set on the response, or,
2430
+ with \`passkeyResolvers({ answerToken: true })\`, the session token is
2431
+ answered in \`token\` and no cookie is set. Extend this type with a \`user\`
2432
+ field of your own: its parent carries the signed-in user.
2433
+ """
2434
+ type PasskeySignedIn {
2435
+ """
2436
+ The session token, answered only when \`passkeyResolvers\` has
2437
+ \`answerToken: true\`; null otherwise. A secret like a session cookie:
2438
+ never in a URL or a log.
2439
+ """
2440
+ token: String
2441
+ """
2442
+ The signed-in user's id.
2443
+ """
2444
+ userId: ID!
2445
+ """
2446
+ When the session expires, as an ISO-8601 string.
2447
+ """
2448
+ expiresAt: String!
2449
+ """
2450
+ Whether the session was opened from a device the user had not used.
2451
+ """
2452
+ newDevice: Boolean!
2453
+ }
2454
+
2455
+ extend type Query {
2456
+ """
2457
+ The signed-in user's passkeys, oldest first.
2458
+ """
2459
+ passkeys: [JanusPasskey!]! @authenticated
2460
+ """
2461
+ Makes a registration challenge and the options the browser needs. Only a
2462
+ user with an active TOTP can register a passkey
2463
+ (SECOND_FACTOR_NOT_ENROLLED otherwise).
2464
+ """
2465
+ passkeyRegistrationOptions: JanusPasskeyRegistration! @authenticated
2466
+ }
2467
+
2468
+ extend type Mutation {
2469
+ """
2470
+ Finishes a registration with what \`navigator.credentials.create\`
2471
+ answered, as a JSON string, and a name of 1 to 100 characters. Needs a
2472
+ session that proved who it is recently (STEP_UP_REQUIRED). The challenge
2473
+ is spent even when the response does not verify (PASSKEY_INVALID): ask for
2474
+ new options.
2475
+ """
2476
+ registerPasskey(
2477
+ challenge: String!
2478
+ response: String!
2479
+ name: String!
2480
+ ): JanusPasskey! @authenticated
2481
+ """
2482
+ Renames one of the user's passkeys. False when it is not theirs or not
2483
+ there.
2484
+ """
2485
+ renamePasskey(credentialId: ID!, name: String!): Boolean! @authenticated
2486
+ """
2487
+ Removes one of the user's passkeys. True when this call removed it. Needs
2488
+ a session that proved who it is recently (STEP_UP_REQUIRED).
2489
+ """
2490
+ removePasskey(credentialId: ID!): Boolean! @authenticated
2491
+ """
2492
+ Redeems a sign-in's second-factor challenge with what
2493
+ \`navigator.credentials.get\` answered, as a JSON string. Five attempts per
2494
+ challenge, shared with the TOTP code (CODE_INVALID with attemptsLeft). Sets
2495
+ the session cookie, or answers \`token\` with \`answerToken\`, and the
2496
+ device cookie.
2497
+ """
2498
+ confirmSecondFactorPasskey(
2499
+ challenge: String!
2500
+ assertion: String!
2501
+ ): PasskeySignedIn!
2502
+ }
2503
+ `;
2504
+ // src/passkeys/sign-in.sdl.ts
2505
+ var janusPasskeySignInTypeDefs = `"""
2506
+ A passkey sign-in begun: give \`options\` to the browser and keep \`challenge\`
2507
+ until \`passkeySignIn\`.
2508
+ """
2509
+ type JanusPasskeySignInChallenge {
2510
+ """
2511
+ The JSON text for \`navigator.credentials.get({ publicKey })\`, with no
2512
+ credential named: the browser offers the discoverable passkeys it holds.
2513
+ """
2514
+ options: String!
2515
+ """
2516
+ The secret \`passkeySignIn\` spends, once. Never in a URL or a log.
2517
+ """
2518
+ challenge: String!
2519
+ """
2520
+ When the challenge lapses, as an ISO-8601 string.
2521
+ """
2522
+ expiresAt: String!
2523
+ }
2524
+
2525
+ extend type Query {
2526
+ """
2527
+ Makes a sign-in challenge and the options the browser needs. Anyone may
2528
+ ask: rate-limit it where requests enter, as each call stores one
2529
+ short-lived token. The response is never cached.
2530
+ """
2531
+ passkeySignInOptions: JanusPasskeySignInChallenge!
2532
+ }
2533
+
2534
+ extend type Mutation {
2535
+ """
2536
+ Signs in with a passkey alone, with what \`navigator.credentials.get\`
2537
+ answered, as a JSON string: no password and no code. One attempt per
2538
+ challenge: a refusal is CREDENTIALS_INVALID, 401, and asks for new options;
2539
+ a missing, spent or lapsed challenge is TOKEN_UNKNOWN, TOKEN_SPENT or
2540
+ TOKEN_EXPIRED. Sets the session cookie, or answers \`token\` with
2541
+ \`answerToken\`, and the device cookie.
2542
+ """
2543
+ passkeySignIn(challenge: String!, assertion: String!): PasskeySignedIn!
2544
+ }
2545
+ `;
2546
+ // src/plugin.ts
2547
+ function useJanus(options) {
2548
+ const { auth, access, type, clock, apiKey, loaders, conditions } = options;
2549
+ const types = typeof auth === "function" ? options.types ?? null : auth.types;
2550
+ checkWiring("useJanus()", { auth, access, clock });
2551
+ const applied = new WeakSet;
2552
+ return {
2553
+ onContextBuilding: ({ context, extendContext }) => {
2554
+ const { request } = context;
2555
+ const janus = createJanusContext(request ?? acceptedOf(context), {
2556
+ auth,
2557
+ context,
2558
+ access,
2559
+ type,
2560
+ clock,
2561
+ apiKey
2562
+ });
2563
+ if (typeof request === "object" && request !== null) {
2564
+ track(request, janus);
2565
+ }
2566
+ extendContext({ janus });
2567
+ },
2568
+ onSchemaChange: ({ schema, replaceSchema }) => {
2569
+ if (applied.has(schema))
2570
+ return;
2571
+ const next = applyJanusDirectives(schema, {
2572
+ auth: { types },
2573
+ ...type === undefined ? {} : { type },
2574
+ access,
2575
+ loaders,
2576
+ conditions
2577
+ });
2578
+ applied.add(next);
2579
+ replaceSchema(next);
2580
+ },
2581
+ onResponse: (payload) => resendRenewed(payload, typeof auth === "function" ? undefined : auth.cookie)
2582
+ };
2583
+ }
2584
+ // src/sdl.ts
2585
+ var janusTypeDefs = `"""
2586
+ Only a signed-in user reaches this field, or every field of this type or
2587
+ interface. With \`type\`, only a user of one of these user types: any other is
2588
+ answered FORBIDDEN.
2589
+ """
2590
+ directive @authenticated(
2591
+ type: [String!]
2592
+ ) on OBJECT | INTERFACE | FIELD_DEFINITION
2593
+
2594
+ """
2595
+ Only a session that proved who it is less than \`maxAge\` seconds ago reaches
2596
+ this field, or every field of this type or interface: signed in, or confirmed
2597
+ since by a step-up. Anonymous is answered UNAUTHENTICATED, an older session
2598
+ STEP_UP_REQUIRED. Where several apply, the smallest \`maxAge\` holds.
2599
+ """
2600
+ directive @fresh(maxAge: Int!) on OBJECT | INTERFACE | FIELD_DEFINITION
2601
+
2602
+ """
2603
+ What a denied \`@permission\` answers.
2604
+ """
2605
+ enum JanusPermissionDenial {
2606
+ """
2607
+ 404: the object is not told to exist. The default.
2608
+ """
2609
+ NOT_FOUND
2610
+ """
2611
+ 403: the object exists, and this user may not do this to it.
2612
+ """
2613
+ FORBIDDEN
2614
+ }
2615
+
2616
+ """
2617
+ Only a user holding permission \`name\` on the object of \`type\` whose id \`id\`
2618
+ reads reaches this field, or every field of this type or interface. \`id\` is
2619
+ \`args.<path>\` or \`parent.<path>\`: \`args.id\` on a field and \`parent.id\` on a
2620
+ type or an interface when absent. A list of ids requires the permission on
2621
+ every one. Repeated, every one must hold, in the order written.
2622
+ """
2623
+ directive @permission(
2624
+ name: String!
2625
+ type: String!
2626
+ id: String
2627
+ onDeny: JanusPermissionDenial! = NOT_FOUND
2628
+ ) repeatable on OBJECT | INTERFACE | FIELD_DEFINITION
2629
+ `;
2630
+ // src/second-factor/resolvers/deps.ts
2631
+ import { parseDuration as parseDuration2 } from "@softistx/janus";
2632
+ function depsOf3(options) {
2633
+ const type = options.type;
2634
+ const only = type === undefined ? {} : { type };
2635
+ const { freshWithin } = options;
2636
+ if (freshWithin !== undefined && typeof freshWithin !== "string") {
2637
+ throw new TypeError("secondFactorResolvers(): freshWithin is a duration with its unit, such as '10m'");
2638
+ }
2639
+ const bind = (auth) => ({
2640
+ auth,
2641
+ api: apiOf(auth, type, SURFACE2),
2642
+ answerToken: options.answerToken ?? false,
2643
+ device: options.device === true ? {} : options.device,
2644
+ freshWithin,
2645
+ freshMs: freshWithin === undefined ? undefined : parseDuration2(freshWithin, "secondFactorResolvers(): freshWithin"),
2646
+ options,
2647
+ session: (ctx) => auth.authenticate(requestOf(ctx, "secondFactorResolvers"), only).then(undefined, rethrown),
2648
+ userOf: (ctx) => requireUser(ctx, type === undefined ? {} : { type })
2649
+ });
2650
+ const source = options.auth;
2651
+ const fixed = typeof source === "function" ? undefined : bind(source);
2652
+ const chosenBefore = new WeakMap;
2653
+ return async (ctx) => {
2654
+ if (fixed !== undefined)
2655
+ return fixed;
2656
+ const chosen = await source(ctx);
2657
+ if (chosen === null || chosen === undefined) {
2658
+ throw denial("UNAUTHENTICATED");
2659
+ }
2660
+ const instance = chosen;
2661
+ const known = chosenBefore.get(instance);
2662
+ if (known !== undefined)
2663
+ return known;
2664
+ const made = bind(instance);
2665
+ chosenBefore.set(instance, made);
2666
+ return made;
2667
+ };
2668
+ }
2669
+ var SURFACE2 = {
2670
+ name: "secondFactorResolvers",
2671
+ key: "secondFactor",
2672
+ complete: (holder) => holder?.secondFactor !== undefined,
2673
+ missing: "auth has no secondFactor surface — pass what janus() answered; with several user types, name the one with `type`",
2674
+ missingOf: (type) => `auth.${type} has no secondFactor — give janus() \`secondFactor\`, and name a user type that exists`
2675
+ };
2676
+ async function sessionOrDeny(deps, ctx) {
2677
+ const current = await deps.session(ctx);
2678
+ if (current === null)
2679
+ throw denial("UNAUTHENTICATED");
2680
+ return current;
2681
+ }
2682
+ async function writer(deps, action, ctx) {
2683
+ const { user } = await sessionOrDeny(deps, ctx);
2684
+ if (deps.freshWithin !== undefined) {
2685
+ await requireFresh(ctx, deps.freshWithin);
2686
+ }
2687
+ await deps.options.guard?.(action, user, ctx);
2688
+ return user;
2689
+ }
2690
+
2691
+ // src/second-factor/resolvers/sign-in.ts
2692
+ function signedIn(deps, request, done, recoveryCodesLeft) {
2693
+ return { ...signedInAnswer(deps, request, done), recoveryCodesLeft };
2694
+ }
2695
+ function confirmSecondFactor(source) {
2696
+ return async (_, { challenge, code }, ctx) => {
2697
+ const deps = await source(ctx);
2698
+ const request = requestOf(ctx, "secondFactorResolvers");
2699
+ const done = await deps.api.secondFactor.confirm(challenge, code, deps.device === undefined ? undefined : { device: deviceOf(request, deps.device) }).then(undefined, rethrown);
2700
+ return signedIn(deps, request, done, null);
2701
+ };
2702
+ }
2703
+ function recoverSecondFactor(source) {
2704
+ return async (_, { challenge, recoveryCode }, ctx) => {
2705
+ const deps = await source(ctx);
2706
+ const request = requestOf(ctx, "secondFactorResolvers");
2707
+ const done = await deps.api.secondFactor.recover(challenge, recoveryCode, deps.device === undefined ? undefined : { device: deviceOf(request, deps.device) }).then(undefined, rethrown);
2708
+ return signedIn(deps, request, done, done.recoveryCodesLeft);
2709
+ };
2710
+ }
2711
+
2712
+ // src/second-factor/resolvers/status.ts
2713
+ function status(source) {
2714
+ return async (_, __, ctx) => {
2715
+ const { api, userOf } = await source(ctx);
2716
+ const user = await userOf(ctx);
2717
+ if (user.hasSecondFactor !== true) {
2718
+ return { enabled: false, recoveryCodesLeft: null };
2719
+ }
2720
+ const left = await api.secondFactor.recoveryCodesLeft(user).then(undefined, rethrown);
2721
+ return { enabled: true, recoveryCodesLeft: left };
2722
+ };
2723
+ }
2724
+ function sessionConfirmedUntil(source) {
2725
+ return async (_, __, ctx) => {
2726
+ const { session, freshMs } = await source(ctx);
2727
+ if (freshMs === undefined)
2728
+ return null;
2729
+ const current = await session(ctx);
2730
+ if (current === null)
2731
+ return null;
2732
+ return new Date(current.session.authenticatedAt.getTime() + freshMs).toISOString();
2733
+ };
2734
+ }
2735
+
2736
+ // src/second-factor/resolvers/step-up.ts
2737
+ function stepUpOf(api, caller) {
2738
+ if (api.stepUp === undefined) {
2739
+ throw new TypeError(`secondFactorResolvers(): ${caller} needs a step-up — a user type with an e-mail has \`stepUp\``);
2740
+ }
2741
+ return api.stepUp;
2742
+ }
2743
+ function requestStepUp(source) {
2744
+ return async (_, __, ctx) => {
2745
+ const deps = await source(ctx);
2746
+ const { user } = await sessionOrDeny(deps, ctx);
2747
+ const stepUp = stepUpOf(deps.api, "requestStepUp");
2748
+ const { sendStepUpCode } = deps.options;
2749
+ if (user.hasSecondFactor !== true && sendStepUpCode === undefined) {
2750
+ throw new TypeError("secondFactorResolvers(): a step-up by e-mail needs `sendStepUpCode` — give it, or require a second factor of every user");
2751
+ }
2752
+ const issued = await stepUp.request(user).then(undefined, rethrown);
2753
+ if (issued.via === "email")
2754
+ await sendStepUpCode?.(issued, ctx);
2755
+ sendNoStore(requestOf(ctx, "secondFactorResolvers"));
2756
+ return {
2757
+ via: issued.via,
2758
+ challenge: issued.challenge,
2759
+ expiresAt: issued.expiresAt.toISOString()
2760
+ };
2761
+ };
2762
+ }
2763
+ function confirmStepUp(source) {
2764
+ return async (_, { challenge, code }, ctx) => {
2765
+ const deps = await source(ctx);
2766
+ await sessionOrDeny(deps, ctx);
2767
+ const session = await stepUpOf(deps.api, "confirmStepUp").confirm(requestOf(ctx, "secondFactorResolvers"), challenge, code).then(undefined, rethrown);
2768
+ const at = session.authenticatedAt;
2769
+ return {
2770
+ confirmedAt: at.toISOString(),
2771
+ confirmedUntil: deps.freshMs === undefined ? null : new Date(at.getTime() + deps.freshMs).toISOString()
2772
+ };
2773
+ };
2774
+ }
2775
+
2776
+ // src/second-factor/resolvers/writes.ts
2777
+ import { SecondFactorError } from "@softistx/janus";
2778
+ function enrollSecondFactor(source) {
2779
+ return async (_, __, ctx) => {
2780
+ const deps = await source(ctx);
2781
+ const user = await writer(deps, "enroll", ctx);
2782
+ sendNoStore(requestOf(ctx, "secondFactorResolvers"));
2783
+ const { secret, uri } = await deps.api.secondFactor.enroll(user).then(undefined, rethrown);
2784
+ return { secret, uri };
2785
+ };
2786
+ }
2787
+ function activateSecondFactor(source) {
2788
+ return async (_, { code }, ctx) => {
2789
+ const deps = await source(ctx);
2790
+ const user = await writer(deps, "activate", ctx);
2791
+ sendNoStore(requestOf(ctx, "secondFactorResolvers"));
2792
+ const { recoveryCodes } = await deps.api.secondFactor.activate(user, code).then(undefined, rethrown);
2793
+ return { recoveryCodes: [...recoveryCodes] };
2794
+ };
2795
+ }
2796
+ function regenerateRecoveryCodes(source) {
2797
+ return async (_, { code }, ctx) => {
2798
+ const deps = await source(ctx);
2799
+ const user = await writer(deps, "regenerateRecoveryCodes", ctx);
2800
+ sendNoStore(requestOf(ctx, "secondFactorResolvers"));
2801
+ const { recoveryCodes } = await deps.api.secondFactor.regenerateRecoveryCodes(user, code).then(undefined, rethrown);
2802
+ return { recoveryCodes: [...recoveryCodes] };
2803
+ };
2804
+ }
2805
+ var notEnrolled = () => janusGraphQLError(new SecondFactorError("SECOND_FACTOR_NOT_ENROLLED", "disableSecondFactor: the user has no active second factor"));
2806
+ function disableSecondFactor(source) {
2807
+ return async (_, { code }, ctx) => {
2808
+ const deps = await source(ctx);
2809
+ const user = await writer(deps, "disable", ctx);
2810
+ if (user.hasSecondFactor !== true)
2811
+ throw notEnrolled();
2812
+ const stepUp = stepUpOf(deps.api, "disableSecondFactor");
2813
+ const issued = await stepUp.request(user).then(undefined, rethrown);
2814
+ if (issued.via !== "secondFactor")
2815
+ throw notEnrolled();
2816
+ await stepUp.confirm(requestOf(ctx, "secondFactorResolvers"), issued.challenge, code).then(undefined, rethrown);
2817
+ await deps.api.secondFactor.disable(user).then(undefined, rethrown);
2818
+ return true;
2819
+ };
2820
+ }
2821
+
2822
+ // src/second-factor/resolvers/index.ts
2823
+ function secondFactorResolvers(options) {
2824
+ const source = depsOf3(options);
2825
+ return {
2826
+ Query: {
2827
+ secondFactor: status(source),
2828
+ sessionConfirmedUntil: sessionConfirmedUntil(source)
2829
+ },
2830
+ Mutation: {
2831
+ confirmSecondFactor: confirmSecondFactor(source),
2832
+ recoverSecondFactor: recoverSecondFactor(source),
2833
+ enrollSecondFactor: enrollSecondFactor(source),
2834
+ activateSecondFactor: activateSecondFactor(source),
2835
+ regenerateRecoveryCodes: regenerateRecoveryCodes(source),
2836
+ disableSecondFactor: disableSecondFactor(source),
2837
+ requestStepUp: requestStepUp(source),
2838
+ confirmStepUp: confirmStepUp(source)
2839
+ }
2840
+ };
2841
+ }
2842
+ function secondFactorViewerFields(options) {
2843
+ const source = depsOf3(options);
2844
+ return {
2845
+ secondFactor: status(source),
2846
+ sessionConfirmedUntil: sessionConfirmedUntil(source)
2847
+ };
2848
+ }
2849
+ // src/second-factor/sdl.ts
2850
+ var janusSecondFactorTypeDefs = `"""
2851
+ Whether the signed-in user's TOTP second factor is active.
2852
+ """
2853
+ type JanusSecondFactorStatus {
2854
+ """
2855
+ True once the factor is active: a sign-in then asks for a code. A factor
2856
+ that was started and never activated is not enabled.
2857
+ """
2858
+ enabled: Boolean!
2859
+ """
2860
+ The recovery codes not yet used. Null without an active factor, 0 when
2861
+ all are spent (regenerate them).
2862
+ """
2863
+ recoveryCodesLeft: Int
2864
+ }
2865
+
2866
+ """
2867
+ A factor started, not yet active: load \`secret\` or \`uri\` into the
2868
+ authenticator app, then give its first code to \`activateSecondFactor\`.
2869
+ Never cached, never logged.
2870
+ """
2871
+ type JanusSecondFactorEnrolment {
2872
+ """
2873
+ The TOTP secret in base32, for a user who types it in.
2874
+ """
2875
+ secret: String!
2876
+ """
2877
+ The \`otpauth://\` URI to render as a QR code.
2878
+ """
2879
+ uri: String!
2880
+ }
2881
+
2882
+ """
2883
+ Ten recovery codes, from \`activateSecondFactor\` or
2884
+ \`regenerateRecoveryCodes\`. Shown once: no call answers them again.
2885
+ """
2886
+ type JanusRecoveryCodes {
2887
+ recoveryCodes: [String!]!
2888
+ }
2889
+
2890
+ """
2891
+ A sign-in that needs a second factor: no session is open yet. Build it in
2892
+ your own sign-in resolver from the core's \`secondFactor\` answer with
2893
+ \`secondFactorChallengeOut\`, then answer it with \`confirmSecondFactor\` or
2894
+ \`recoverSecondFactor\`. The challenge is a secret like a session token: never
2895
+ in a URL or a log.
2896
+ """
2897
+ type JanusSecondFactorChallenge {
2898
+ challenge: String!
2899
+ """
2900
+ When the challenge lapses, as an ISO-8601 string.
2901
+ """
2902
+ expiresAt: String!
2903
+ """
2904
+ What can answer it: \`totp\` always, and \`passkey\` when the user holds one.
2905
+ """
2906
+ methods: [String!]!
2907
+ """
2908
+ The JSON text for \`navigator.credentials.get({ publicKey })\`, present
2909
+ exactly when \`methods\` holds \`passkey\`.
2910
+ """
2911
+ passkeyOptions: String
2912
+ }
2913
+
2914
+ """
2915
+ A second-factor sign-in completed: the session cookie is set on the response,
2916
+ or, with \`secondFactorResolvers({ answerToken: true })\`, the session token is
2917
+ answered in \`token\` and no cookie is set. Extend this type with a \`user\`
2918
+ field of your own: its parent carries the signed-in user.
2919
+ """
2920
+ type SecondFactorSignedIn {
2921
+ """
2922
+ The session token, answered only with \`answerToken: true\`; null
2923
+ otherwise. A secret like a session cookie: never in a URL or a log.
2924
+ """
2925
+ token: String
2926
+ """
2927
+ The signed-in user's id.
2928
+ """
2929
+ userId: ID!
2930
+ """
2931
+ When the session expires, as an ISO-8601 string.
2932
+ """
2933
+ expiresAt: String!
2934
+ """
2935
+ Whether the session was opened from a device the user had not used.
2936
+ """
2937
+ newDevice: Boolean!
2938
+ """
2939
+ The recovery codes left after \`recoverSecondFactor\` spent one; null after
2940
+ \`confirmSecondFactor\`.
2941
+ """
2942
+ recoveryCodesLeft: Int
2943
+ }
2944
+
2945
+ """
2946
+ A step-up under way: keep \`challenge\` (never in a URL) and give it to
2947
+ \`confirmStepUp\` with the code.
2948
+ """
2949
+ type JanusStepUpChallenge {
2950
+ """
2951
+ How the code is delivered: \`email\` (a code sent to the user's address by
2952
+ your \`sendStepUpCode\`) or \`secondFactor\` (the code of the user's
2953
+ authenticator app; nothing is sent).
2954
+ """
2955
+ via: String!
2956
+ challenge: String!
2957
+ """
2958
+ When the challenge lapses, as an ISO-8601 string.
2959
+ """
2960
+ expiresAt: String!
2961
+ }
2962
+
2963
+ """
2964
+ A step-up confirmed: the request's session proved who it is just now.
2965
+ """
2966
+ type JanusStepUpConfirmed {
2967
+ """
2968
+ When the session last proved who it is, as an ISO-8601 string.
2969
+ """
2970
+ confirmedAt: String!
2971
+ """
2972
+ Until when it counts as fresh (\`confirmedAt\` plus \`freshWithin\`), as an
2973
+ ISO-8601 string. Null when \`secondFactorResolvers\` was given no
2974
+ \`freshWithin\`.
2975
+ """
2976
+ confirmedUntil: String
2977
+ }
2978
+
2979
+ extend type Query {
2980
+ """
2981
+ The signed-in user's second factor: whether it is active, and the
2982
+ recovery codes left. Put the same resolver on your \`Viewer.secondFactor\`
2983
+ with \`secondFactorViewerFields\`.
2984
+ """
2985
+ secondFactor: JanusSecondFactorStatus! @authenticated
2986
+ """
2987
+ Until when the request's session counts as freshly confirmed: its
2988
+ sign-in or last step-up plus \`freshWithin\`. In the past once it no longer
2989
+ does; null without \`freshWithin\` or without a session.
2990
+ """
2991
+ sessionConfirmedUntil: String
2992
+ }
2993
+
2994
+ extend type Mutation {
2995
+ """
2996
+ Redeems a sign-in's challenge with the code of the authenticator app.
2997
+ Five attempts per challenge (CODE_INVALID with attemptsLeft). Sets the
2998
+ session cookie, or answers \`token\` with \`answerToken\`, and the device
2999
+ cookie.
3000
+ """
3001
+ confirmSecondFactor(challenge: String!, code: String!): SecondFactorSignedIn!
3002
+ """
3003
+ Redeems a sign-in's challenge with a recovery code instead, for a lost
3004
+ phone. The code is spent and \`recoveryCodesLeft\` answers what remains.
3005
+ Refused as \`confirmSecondFactor\`.
3006
+ """
3007
+ recoverSecondFactor(
3008
+ challenge: String!
3009
+ recoveryCode: String!
3010
+ ): SecondFactorSignedIn!
3011
+ """
3012
+ Starts a factor and answers the secret and the URI to show as a QR code.
3013
+ SECOND_FACTOR_ACTIVE when one is active. With \`freshWithin\`, needs a
3014
+ fresh session (STEP_UP_REQUIRED).
3015
+ """
3016
+ enrollSecondFactor: JanusSecondFactorEnrolment! @authenticated
3017
+ """
3018
+ Checks the app's first code and makes the factor active; answers the ten
3019
+ recovery codes, once. CODE_INVALID, SECOND_FACTOR_NOT_ENROLLED. With
3020
+ \`freshWithin\`, needs a fresh session.
3021
+ """
3022
+ activateSecondFactor(code: String!): JanusRecoveryCodes! @authenticated
3023
+ """
3024
+ Replaces all the recovery codes with ten new ones, on a current code of
3025
+ the app. Counted five per user per 15 minutes (CODE_INVALID with
3026
+ attemptsLeft, or reason \`throttled\` and \`retryAfter\`). With
3027
+ \`freshWithin\`, needs a fresh session.
3028
+ """
3029
+ regenerateRecoveryCodes(code: String!): JanusRecoveryCodes! @authenticated
3030
+ """
3031
+ Turns the factor off, on a current code of the app, checked by a step-up
3032
+ of the request's session. SECOND_FACTOR_NOT_ENROLLED without an active
3033
+ factor. With \`freshWithin\`, needs a fresh session.
3034
+ """
3035
+ disableSecondFactor(code: String!): Boolean! @authenticated
3036
+ """
3037
+ Starts a step-up for the request's session: the app's code when the user
3038
+ has an active second factor, else a code sent by \`sendStepUpCode\`.
3039
+ """
3040
+ requestStepUp: JanusStepUpChallenge! @authenticated
3041
+ """
3042
+ Confirms the step-up with its challenge and code: the request's session
3043
+ proved who it is just now. CODE_INVALID with attemptsLeft, TOKEN_UNKNOWN,
3044
+ TOKEN_SPENT, TOKEN_EXPIRED.
3045
+ """
3046
+ confirmStepUp(challenge: String!, code: String!): JanusStepUpConfirmed!
3047
+ @authenticated
3048
+ }
3049
+ `;
3050
+ // src/social/shape.ts
3051
+ import { GraphQLError as GraphQLError13 } from "graphql";
3052
+ var linkOut = (link) => ({
3053
+ provider: link.provider,
3054
+ accountId: link.accountId,
3055
+ email: link.email,
3056
+ linkedAt: link.linkedAt.toISOString()
3057
+ });
3058
+ var flowOut = (start) => ({
3059
+ url: start.url,
3060
+ flow: start.flow,
3061
+ expiresAt: start.expiresAt.toISOString()
3062
+ });
3063
+ function callbackOf(callbackUrl) {
3064
+ try {
3065
+ return new URL(callbackUrl, "http://callback.invalid").searchParams;
3066
+ } catch {
3067
+ throw new GraphQLError13("callbackUrl must be a URL", {
3068
+ extensions: { code: "BAD_USER_INPUT", http: { status: 400 } }
3069
+ });
3070
+ }
3071
+ }
3072
+
3073
+ // src/social/resolvers.ts
3074
+ function socialResolvers(options) {
3075
+ const { type, answerToken = false } = options;
3076
+ const source = options.auth;
3077
+ const only = type === undefined ? {} : { type };
3078
+ const bind = (auth) => ({
3079
+ auth,
3080
+ session: (ctx) => auth.authenticate(requestOf(ctx, "socialResolvers"), only).then(undefined, rethrown),
3081
+ userOf: (ctx) => requireUser(ctx, type === undefined ? {} : { type })
3082
+ });
3083
+ const fixed = typeof source === "function" ? undefined : bind(source);
3084
+ const chosenBefore = new WeakMap;
3085
+ const deps = {
3086
+ answerToken,
3087
+ only,
3088
+ bound: async (ctx = {}) => {
3089
+ if (fixed !== undefined)
3090
+ return fixed;
3091
+ const chosen = await source(ctx);
3092
+ if (chosen === null || chosen === undefined || chosen.social === undefined) {
3093
+ throw denial("UNAUTHENTICATED");
3094
+ }
3095
+ const instance = chosen;
3096
+ const known = chosenBefore.get(instance);
3097
+ if (known !== undefined)
3098
+ return known;
3099
+ const made = bind(instance);
3100
+ chosenBefore.set(instance, made);
3101
+ return made;
3102
+ }
3103
+ };
3104
+ return {
3105
+ Query: { socialLinks: socialLinks(deps) },
3106
+ Mutation: {
3107
+ socialSignInStart: socialSignInStart(deps),
3108
+ socialSignInComplete: socialSignInComplete(deps),
3109
+ linkSocial: linkSocial(deps),
3110
+ unlinkSocial: unlinkSocial(deps)
3111
+ },
3112
+ SocialSignInResult: {
3113
+ __resolveType: (result) => result.status === "signedIn" ? "SocialSignedIn" : result.status === "secondFactor" ? "SocialSecondFactor" : "SocialLinked"
3114
+ }
3115
+ };
3116
+ }
3117
+ function socialLinks({ bound }) {
3118
+ return async (_, __, ctx) => {
3119
+ const { auth, userOf } = await bound(ctx);
3120
+ const user = await userOf(ctx);
3121
+ const links = await auth.social.list(user).then(undefined, rethrown);
3122
+ return links.map(linkOut);
3123
+ };
3124
+ }
3125
+ function socialSignInStart({
3126
+ bound,
3127
+ only
3128
+ }) {
3129
+ return async (_, { provider, returnTo }, ctx) => {
3130
+ const { auth } = await bound(ctx);
3131
+ const start = await auth.social.start({
3132
+ provider,
3133
+ ...returnTo == null ? {} : { returnTo },
3134
+ ...only
3135
+ }).then(undefined, rethrown);
3136
+ noStoreOf(ctx);
3137
+ return flowOut(start);
3138
+ };
3139
+ }
3140
+ function socialSignInComplete({
3141
+ bound,
3142
+ answerToken
3143
+ }) {
3144
+ return async (_, { callbackUrl, flow }, ctx) => {
3145
+ const { auth, session } = await bound(ctx);
3146
+ const request = requestOf(ctx, "socialResolvers");
3147
+ const callback = callbackOf(callbackUrl);
3148
+ const current = await session(ctx);
3149
+ const done = await auth.social.complete({ callback, flow, current }).then(undefined, rethrown);
3150
+ return completedOut(done, { auth, answerToken }, request);
3151
+ };
3152
+ }
3153
+ function linkSocial({ bound }) {
3154
+ return async (_, { provider, returnTo }, ctx) => {
3155
+ const { auth, session } = await bound(ctx);
3156
+ const request = requestOf(ctx, "socialResolvers");
3157
+ const current = await session(ctx);
3158
+ if (current === null)
3159
+ throw denial("UNAUTHENTICATED");
3160
+ const start = await auth.social.link(current, {
3161
+ provider,
3162
+ ...returnTo == null ? {} : { returnTo }
3163
+ }).then(undefined, rethrown);
3164
+ sendNoStore(request);
3165
+ return flowOut(start);
3166
+ };
3167
+ }
3168
+ function unlinkSocial({ bound }) {
3169
+ return async (_, { provider, accountId }, ctx) => {
3170
+ const { auth, userOf } = await bound(ctx);
3171
+ const user = await userOf(ctx);
3172
+ return auth.social.unlink(user, { provider, accountId }).then(undefined, rethrown);
3173
+ };
3174
+ }
3175
+ function completedOut(done, { auth, answerToken }, request) {
3176
+ if (done.status === "signedIn") {
3177
+ return {
3178
+ status: "signedIn",
3179
+ ...signedInAnswer({ auth, answerToken, device: undefined }, request, done),
3180
+ created: done.created,
3181
+ linked: done.linked,
3182
+ returnTo: done.returnTo
3183
+ };
3184
+ }
3185
+ if (done.status === "secondFactor") {
3186
+ sendNoStore(request);
3187
+ return {
3188
+ status: "secondFactor",
3189
+ challenge: done.challenge,
3190
+ expiresAt: done.expiresAt.toISOString(),
3191
+ methods: done.methods,
3192
+ passkeyOptions: done.passkeyOptions === undefined ? null : JSON.stringify(done.passkeyOptions),
3193
+ returnTo: done.returnTo
3194
+ };
3195
+ }
3196
+ return {
3197
+ status: "linked",
3198
+ link: linkOut(done.link),
3199
+ returnTo: done.returnTo
3200
+ };
3201
+ }
3202
+ // src/social/sdl.ts
3203
+ var janusSocialTypeDefs = `"""
3204
+ One social account linked to a user: the provider's name in the
3205
+ application, and the provider's own identifier of the account.
3206
+ """
3207
+ type JanusSocialLink {
3208
+ """
3209
+ The application's name for the provider (\`google\`).
3210
+ """
3211
+ provider: String!
3212
+ """
3213
+ The provider's identifier of the account. Pass it back to \`unlinkSocial\`;
3214
+ keep it out of logs and analytics.
3215
+ """
3216
+ accountId: ID!
3217
+ """
3218
+ The e-mail the provider reported when the account was linked, if any.
3219
+ """
3220
+ email: String
3221
+ """
3222
+ When the account was linked, as an ISO-8601 string.
3223
+ """
3224
+ linkedAt: String!
3225
+ }
3226
+
3227
+ """
3228
+ A social flow begun: send the visitor to \`url\`, and keep \`flow\` until the
3229
+ callback.
3230
+ """
3231
+ type SocialFlowStart {
3232
+ """
3233
+ The provider's authorization URL.
3234
+ """
3235
+ url: String!
3236
+ """
3237
+ A secret like a session token: the BFF keeps it in its own HttpOnly
3238
+ SameSite=Lax cookie and hands it back to \`socialSignInComplete\`. Never in
3239
+ a URL or a log.
3240
+ """
3241
+ flow: String!
3242
+ """
3243
+ When the flow lapses, as an ISO-8601 string.
3244
+ """
3245
+ expiresAt: String!
3246
+ }
3247
+
3248
+ """
3249
+ A social sign-in completed: the session cookie is set on the response, or,
3250
+ with \`socialResolvers({ answerToken: true })\`, the session token is answered
3251
+ in \`token\` and no cookie is set. Extend this type with a \`user\` field of
3252
+ your own: its parent carries the signed-in user.
3253
+ """
3254
+ type SocialSignedIn {
3255
+ """
3256
+ The session token, answered only when \`socialResolvers\` has \`answerToken:
3257
+ true\` (the session cookie is then not set); null otherwise. A secret like
3258
+ a session cookie: the BFF keeps it in its own HttpOnly cookie and sends
3259
+ it back as \`Authorization: Bearer\`. Never in a URL or a log.
3260
+ """
3261
+ token: String
3262
+ """
3263
+ The signed-in user's id.
3264
+ """
3265
+ userId: ID!
3266
+ """
3267
+ When the session expires, as an ISO-8601 string.
3268
+ """
3269
+ expiresAt: String!
3270
+ """
3271
+ Whether a user was made for this account.
3272
+ """
3273
+ created: Boolean!
3274
+ """
3275
+ Whether this call linked the account to an existing user.
3276
+ """
3277
+ linked: Boolean!
3278
+ """
3279
+ Whether the session was opened from a device the user had not used.
3280
+ """
3281
+ newDevice: Boolean!
3282
+ """
3283
+ The path the flow was started with, or null.
3284
+ """
3285
+ returnTo: String
3286
+ }
3287
+
3288
+ """
3289
+ The user has an active second factor: confirm it with the challenge. No
3290
+ session is open yet.
3291
+ """
3292
+ type SocialSecondFactor {
3293
+ challenge: String!
3294
+ """
3295
+ When the challenge lapses, as an ISO-8601 string.
3296
+ """
3297
+ expiresAt: String!
3298
+ """
3299
+ What can answer the challenge: \`totp\` always, and \`passkey\` when the
3300
+ user holds one. Show only these.
3301
+ """
3302
+ methods: [String!]!
3303
+ """
3304
+ The JSON text for \`navigator.credentials.get({ publicKey })\`, present
3305
+ exactly when \`methods\` holds \`passkey\`. Answer it with
3306
+ \`confirmSecondFactorPasskey\` (\`janusPasskeyTypeDefs\`). A \`totp\` code
3307
+ goes to \`confirmSecondFactor\` (\`janusSecondFactorTypeDefs\`).
3308
+ """
3309
+ passkeyOptions: String
3310
+ returnTo: String
3311
+ }
3312
+
3313
+ """
3314
+ A link flow completed: the signed-in user now has the account. Not a
3315
+ sign-in, so no session is set.
3316
+ """
3317
+ type SocialLinked {
3318
+ link: JanusSocialLink!
3319
+ returnTo: String
3320
+ }
3321
+
3322
+ union SocialSignInResult = SocialSignedIn | SocialSecondFactor | SocialLinked
3323
+
3324
+ extend type Query {
3325
+ """
3326
+ The signed-in user's linked social accounts, oldest first.
3327
+ """
3328
+ socialLinks: [JanusSocialLink!]! @authenticated
3329
+ }
3330
+
3331
+ extend type Mutation {
3332
+ """
3333
+ Begins a sign-in with \`provider\`. \`returnTo\` is a path of this site.
3334
+ Answers the URL to send the visitor to and the flow to keep until the
3335
+ callback.
3336
+ """
3337
+ socialSignInStart(provider: String!, returnTo: String): SocialFlowStart!
3338
+ """
3339
+ Completes the flow with the provider's callback URL and the \`flow\` that
3340
+ \`socialSignInStart\` or \`linkSocial\` answered. A sign-in sets the session
3341
+ cookie, or answers \`token\` with \`answerToken\`.
3342
+ """
3343
+ socialSignInComplete(callbackUrl: String!, flow: String!): SocialSignInResult!
3344
+ """
3345
+ Begins linking an account to the signed-in user, behind a fresh proof.
3346
+ """
3347
+ linkSocial(provider: String!, returnTo: String): SocialFlowStart!
3348
+ @authenticated
3349
+ @fresh(maxAge: 600)
3350
+ """
3351
+ Removes one of the user's links. True when this call removed it.
3352
+ LAST_SIGN_IN_METHOD when it is the user's only way to sign in.
3353
+ """
3354
+ unlinkSocial(provider: String!, accountId: ID!): Boolean!
3355
+ @authenticated
3356
+ @fresh(maxAge: 600)
3357
+ }
3358
+ `;
3359
+ export {
3360
+ DEVICE_COOKIE,
3361
+ apiKeysResolvers,
3362
+ apiKeysTypeDefs,
3363
+ applyJanusDirectives,
3364
+ avatarResolvers,
3365
+ can,
3366
+ denial,
3367
+ deviceOf,
3368
+ invitationResolvers,
3369
+ janusAvatarTypeDefs,
3370
+ janusConnection,
3371
+ janusErrorOf,
3372
+ janusGraphQLError,
3373
+ janusInvitationTypeDefs,
3374
+ janusMaskError,
3375
+ janusPasskeySignInTypeDefs,
3376
+ janusPasskeyTypeDefs,
3377
+ janusSecondFactorTypeDefs,
3378
+ janusSocialTypeDefs,
3379
+ janusTypeDefs,
3380
+ passkeyResolvers,
3381
+ requireFresh,
3382
+ requireUser,
3383
+ secondFactorChallengeOut,
3384
+ secondFactorResolvers,
3385
+ secondFactorViewerFields,
3386
+ sendDevice,
3387
+ socialResolvers,
3388
+ toJanusAvatar,
3389
+ useJanus
3390
+ };
3391
+
3392
+ //# debugId=4F73C78DFB89A63664756E2164756E21
3393
+ //# sourceMappingURL=index.js.map