@softistx/janus-graphql 0.0.0-stage → 0.30.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +716 -2
- package/dist/api-keys/index.d.ts +11 -0
- package/dist/api-keys/index.d.ts.map +1 -0
- package/dist/api-keys/resolvers/deps.d.ts +39 -0
- package/dist/api-keys/resolvers/deps.d.ts.map +1 -0
- package/dist/api-keys/resolvers/index.d.ts +39 -0
- package/dist/api-keys/resolvers/index.d.ts.map +1 -0
- package/dist/api-keys/resolvers/list.d.ts +16 -0
- package/dist/api-keys/resolvers/list.d.ts.map +1 -0
- package/dist/api-keys/resolvers/manage.d.ts +17 -0
- package/dist/api-keys/resolvers/manage.d.ts.map +1 -0
- package/dist/api-keys/sdl.d.ts +14 -0
- package/dist/api-keys/sdl.d.ts.map +1 -0
- package/dist/api-keys/shape.d.ts +38 -0
- package/dist/api-keys/shape.d.ts.map +1 -0
- package/dist/api-keys/types.d.ts +149 -0
- package/dist/api-keys/types.d.ts.map +1 -0
- package/dist/avatar/index.d.ts +32 -0
- package/dist/avatar/index.d.ts.map +1 -0
- package/dist/avatar/resolvers.d.ts +41 -0
- package/dist/avatar/resolvers.d.ts.map +1 -0
- package/dist/avatar/sdl.d.ts +16 -0
- package/dist/avatar/sdl.d.ts.map +1 -0
- package/dist/bad-input.d.ts +17 -0
- package/dist/bad-input.d.ts.map +1 -0
- package/dist/connection/connection.d.ts +36 -0
- package/dist/connection/connection.d.ts.map +1 -0
- package/dist/connection/credential.d.ts +34 -0
- package/dist/connection/credential.d.ts.map +1 -0
- package/dist/connection/types.d.ts +61 -0
- package/dist/connection/types.d.ts.map +1 -0
- package/dist/context/create.d.ts +32 -0
- package/dist/context/create.d.ts.map +1 -0
- package/dist/context/index.d.ts +9 -0
- package/dist/context/index.d.ts.map +1 -0
- package/dist/context/registry.d.ts +72 -0
- package/dist/context/registry.d.ts.map +1 -0
- package/dist/context/resolve.d.ts +20 -0
- package/dist/context/resolve.d.ts.map +1 -0
- package/dist/device.d.ts +28 -0
- package/dist/device.d.ts.map +1 -0
- package/dist/directives/apply.d.ts +51 -0
- package/dist/directives/apply.d.ts.map +1 -0
- package/dist/directives/guard.d.ts +22 -0
- package/dist/directives/guard.d.ts.map +1 -0
- package/dist/directives/permission/enforce.d.ts +24 -0
- package/dist/directives/permission/enforce.d.ts.map +1 -0
- package/dist/directives/permission/model.d.ts +35 -0
- package/dist/directives/permission/model.d.ts.map +1 -0
- package/dist/directives/permission/path.d.ts +31 -0
- package/dist/directives/permission/path.d.ts.map +1 -0
- package/dist/directives/permission/validate.d.ts +42 -0
- package/dist/directives/permission/validate.d.ts.map +1 -0
- package/dist/directives/read.d.ts +43 -0
- package/dist/directives/read.d.ts.map +1 -0
- package/dist/directives/validate.d.ts +39 -0
- package/dist/directives/validate.d.ts.map +1 -0
- package/dist/directives/words.d.ts +7 -0
- package/dist/directives/words.d.ts.map +1 -0
- package/dist/errors/denial.d.ts +6 -0
- package/dist/errors/denial.d.ts.map +1 -0
- package/dist/errors/index.d.ts +12 -0
- package/dist/errors/index.d.ts.map +1 -0
- package/dist/errors/janus-error.d.ts +20 -0
- package/dist/errors/janus-error.d.ts.map +1 -0
- package/dist/errors/mask.d.ts +69 -0
- package/dist/errors/mask.d.ts.map +1 -0
- package/dist/fresh.d.ts +44 -0
- package/dist/fresh.d.ts.map +1 -0
- package/dist/helpers.d.ts +56 -0
- package/dist/helpers.d.ts.map +1 -0
- package/dist/index.d.ts +86 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3393 -0
- package/dist/index.js.map +75 -0
- package/dist/invitations/index.d.ts +12 -0
- package/dist/invitations/index.d.ts.map +1 -0
- package/dist/invitations/resolvers/anonymous.d.ts +11 -0
- package/dist/invitations/resolvers/anonymous.d.ts.map +1 -0
- package/dist/invitations/resolvers/deps.d.ts +38 -0
- package/dist/invitations/resolvers/deps.d.ts.map +1 -0
- package/dist/invitations/resolvers/index.d.ts +37 -0
- package/dist/invitations/resolvers/index.d.ts.map +1 -0
- package/dist/invitations/resolvers/owner.d.ts +17 -0
- package/dist/invitations/resolvers/owner.d.ts.map +1 -0
- package/dist/invitations/sdl/accept.d.ts +7 -0
- package/dist/invitations/sdl/accept.d.ts.map +1 -0
- package/dist/invitations/sdl/index.d.ts +14 -0
- package/dist/invitations/sdl/index.d.ts.map +1 -0
- package/dist/invitations/sdl/owner.d.ts +8 -0
- package/dist/invitations/sdl/owner.d.ts.map +1 -0
- package/dist/invitations/shape.d.ts +63 -0
- package/dist/invitations/shape.d.ts.map +1 -0
- package/dist/invitations/types/index.d.ts +5 -0
- package/dist/invitations/types/index.d.ts.map +1 -0
- package/dist/invitations/types/options.d.ts +104 -0
- package/dist/invitations/types/options.d.ts.map +1 -0
- package/dist/invitations/types/out.d.ts +136 -0
- package/dist/invitations/types/out.d.ts.map +1 -0
- package/dist/invitations/types/surface.d.ts +18 -0
- package/dist/invitations/types/surface.d.ts.map +1 -0
- package/dist/map-code.d.ts +10 -0
- package/dist/map-code.d.ts.map +1 -0
- package/dist/mask-error.d.ts +18 -0
- package/dist/mask-error.d.ts.map +1 -0
- package/dist/memo.d.ts +16 -0
- package/dist/memo.d.ts.map +1 -0
- package/dist/options.d.ts +17 -0
- package/dist/options.d.ts.map +1 -0
- package/dist/passkeys/deps.d.ts +23 -0
- package/dist/passkeys/deps.d.ts.map +1 -0
- package/dist/passkeys/first-factor.types.d.ts +38 -0
- package/dist/passkeys/first-factor.types.d.ts.map +1 -0
- package/dist/passkeys/index.d.ts +14 -0
- package/dist/passkeys/index.d.ts.map +1 -0
- package/dist/passkeys/resolvers.d.ts +23 -0
- package/dist/passkeys/resolvers.d.ts.map +1 -0
- package/dist/passkeys/sdl.d.ts +14 -0
- package/dist/passkeys/sdl.d.ts.map +1 -0
- package/dist/passkeys/shape.d.ts +14 -0
- package/dist/passkeys/shape.d.ts.map +1 -0
- package/dist/passkeys/sign-in.resolvers.d.ts +19 -0
- package/dist/passkeys/sign-in.resolvers.d.ts.map +1 -0
- package/dist/passkeys/sign-in.sdl.d.ts +16 -0
- package/dist/passkeys/sign-in.sdl.d.ts.map +1 -0
- package/dist/passkeys/types.d.ts +193 -0
- package/dist/passkeys/types.d.ts.map +1 -0
- package/dist/plugin.d.ts +59 -0
- package/dist/plugin.d.ts.map +1 -0
- package/dist/renewal.d.ts +51 -0
- package/dist/renewal.d.ts.map +1 -0
- package/dist/report.d.ts +29 -0
- package/dist/report.d.ts.map +1 -0
- package/dist/sdl.d.ts +12 -0
- package/dist/sdl.d.ts.map +1 -0
- package/dist/second-factor/index.d.ts +12 -0
- package/dist/second-factor/index.d.ts.map +1 -0
- package/dist/second-factor/resolvers/deps.d.ts +39 -0
- package/dist/second-factor/resolvers/deps.d.ts.map +1 -0
- package/dist/second-factor/resolvers/index.d.ts +39 -0
- package/dist/second-factor/resolvers/index.d.ts.map +1 -0
- package/dist/second-factor/resolvers/sign-in.d.ts +10 -0
- package/dist/second-factor/resolvers/sign-in.d.ts.map +1 -0
- package/dist/second-factor/resolvers/status.d.ts +10 -0
- package/dist/second-factor/resolvers/status.d.ts.map +1 -0
- package/dist/second-factor/resolvers/step-up.d.ts +16 -0
- package/dist/second-factor/resolvers/step-up.d.ts.map +1 -0
- package/dist/second-factor/resolvers/writes.d.ts +19 -0
- package/dist/second-factor/resolvers/writes.d.ts.map +1 -0
- package/dist/second-factor/sdl.d.ts +14 -0
- package/dist/second-factor/sdl.d.ts.map +1 -0
- package/dist/second-factor/shape.d.ts +18 -0
- package/dist/second-factor/shape.d.ts.map +1 -0
- package/dist/second-factor/types/index.d.ts +5 -0
- package/dist/second-factor/types/index.d.ts.map +1 -0
- package/dist/second-factor/types/options.d.ts +61 -0
- package/dist/second-factor/types/options.d.ts.map +1 -0
- package/dist/second-factor/types/out.d.ts +84 -0
- package/dist/second-factor/types/out.d.ts.map +1 -0
- package/dist/second-factor/types/surface.d.ts +89 -0
- package/dist/second-factor/types/surface.d.ts.map +1 -0
- package/dist/social/index.d.ts +10 -0
- package/dist/social/index.d.ts.map +1 -0
- package/dist/social/resolvers.d.ts +25 -0
- package/dist/social/resolvers.d.ts.map +1 -0
- package/dist/social/sdl.d.ts +13 -0
- package/dist/social/sdl.d.ts.map +1 -0
- package/dist/social/shape.d.ts +11 -0
- package/dist/social/shape.d.ts.map +1 -0
- package/dist/social/types.d.ts +160 -0
- package/dist/social/types.d.ts.map +1 -0
- package/dist/surface/api.d.ts +16 -0
- package/dist/surface/api.d.ts.map +1 -0
- package/dist/surface/request.d.ts +10 -0
- package/dist/surface/request.d.ts.map +1 -0
- package/dist/surface/signed-in.d.ts +30 -0
- package/dist/surface/signed-in.d.ts.map +1 -0
- package/dist/types.d.ts +117 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/wiring.d.ts +56 -0
- package/dist/wiring.d.ts.map +1 -0
- package/docs/README.md +26 -0
- package/docs/guide/api-keys.md +365 -0
- package/docs/guide/avatars.md +129 -0
- package/docs/guide/context.md +371 -0
- package/docs/guide/directives.md +371 -0
- package/docs/guide/errors.md +318 -0
- package/docs/guide/federation.md +71 -0
- package/docs/guide/invitations.md +269 -0
- package/docs/guide/passkeys.md +207 -0
- package/docs/guide/second-factor.md +238 -0
- package/docs/guide/social.md +190 -0
- package/docs/guide/step-up.md +208 -0
- package/docs/guide/subscriptions.md +255 -0
- package/docs/guide/telemetry.md +45 -0
- package/docs/roadmap.md +124 -0
- package/docs/troubleshooting.md +1265 -0
- package/graphql/janus-api-keys.graphqls +237 -0
- package/graphql/janus-avatar.graphqls +19 -0
- package/graphql/janus-invitations.graphqls +280 -0
- package/graphql/janus-passkey-sign-in.graphqls +40 -0
- package/graphql/janus-passkeys.graphqls +134 -0
- package/graphql/janus-second-factor.graphqls +199 -0
- package/graphql/janus-social.graphqls +155 -0
- package/graphql/janus.graphqls +44 -0
- package/package.json +80 -5
package/README.md
CHANGED
|
@@ -1,3 +1,717 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @softistx/janus-graphql
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[`@softistx/janus`](https://github.com/softistx/nxgt-janus/tree/develop/packages/janus) in a GraphQL
|
|
4
|
+
server: the signed-in user on the context, authenticated only when a field
|
|
5
|
+
asks, fields and types guarded by `@authenticated`, `@fresh` and
|
|
6
|
+
`@permission`, the
|
|
7
|
+
same guards on subscriptions over graphql-ws, and every error answered with
|
|
8
|
+
the status it deserves — an outage as 503, never as 401, 403 or 404.
|
|
9
|
+
|
|
10
|
+
An [envelop](https://the-guild.dev/graphql/envelop) plugin, so it runs in
|
|
11
|
+
[GraphQL Yoga](https://the-guild.dev/graphql/yoga-server) and any server built
|
|
12
|
+
on envelop.
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
import { janusMaskError, janusTypeDefs, type JanusContext, useJanus } from '@softistx/janus-graphql';
|
|
16
|
+
import { createSchema, createYoga, type YogaInitialContext } from 'graphql-yoga';
|
|
17
|
+
import { access } from './access'; // what permissions() answered
|
|
18
|
+
import { auth } from './auth'; // what janus() answered
|
|
19
|
+
|
|
20
|
+
type Context = YogaInitialContext & JanusContext<typeof auth, typeof access>;
|
|
21
|
+
|
|
22
|
+
const typeDefs = /* GraphQL */ `
|
|
23
|
+
type Query {
|
|
24
|
+
me: User @authenticated
|
|
25
|
+
ward(id: ID!): Ward @permission(name: "enter", type: "ward")
|
|
26
|
+
}
|
|
27
|
+
type User { id: ID!, email: String }
|
|
28
|
+
type Ward { id: ID!, name: String, roster: [String!] @authenticated(type: ["staff"]) }
|
|
29
|
+
`;
|
|
30
|
+
|
|
31
|
+
export const yoga = createYoga({
|
|
32
|
+
schema: createSchema({
|
|
33
|
+
typeDefs: [janusTypeDefs, typeDefs],
|
|
34
|
+
resolvers: {
|
|
35
|
+
Query: {
|
|
36
|
+
me: async (_: unknown, __: unknown, ctx: Context) => ctx.janus.user(), // never null here
|
|
37
|
+
ward: (_: unknown, { id }: { id: string }) => wards.find(id), // only for a user who may enter it
|
|
38
|
+
},
|
|
39
|
+
},
|
|
40
|
+
}),
|
|
41
|
+
plugins: [useJanus({ auth, access })],
|
|
42
|
+
maskedErrors: { maskError: janusMaskError() }, // STORE_FAILED → 503, not "Unexpected error."
|
|
43
|
+
});
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
> **0.x.** A minor version may still change the surface; the changelog says how.
|
|
47
|
+
|
|
48
|
+
## Install
|
|
49
|
+
|
|
50
|
+
Public on npmjs:
|
|
51
|
+
|
|
52
|
+
```sh
|
|
53
|
+
bun add @softistx/janus-graphql @softistx/janus graphql @graphql-tools/utils @envelop/core
|
|
54
|
+
bun add -d typescript # 6 or 7
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Every peer is required but `graphql-ws`:
|
|
58
|
+
|
|
59
|
+
| Peer | Range | Why |
|
|
60
|
+
| --- | --- | --- |
|
|
61
|
+
| `@softistx/janus` | the minor released beside it — `peerDependencies` states the range | A **peer**, never a dependency: this package defines no error class, so the `JanusError` a resolver throws is the one you import |
|
|
62
|
+
| `graphql` | `^16.9.0 \|\| ^17.0.0` | The schema and `GraphQLError` are yours; a second copy of `graphql` fails every schema |
|
|
63
|
+
| `@graphql-tools/utils` | `>=10.0.0 <14` | `mapSchema` and `getDirective`, which apply the directives |
|
|
64
|
+
| `@envelop/core` | `^5.0.0 \|\| ^6.0.0` | Types only — the `Plugin` `useJanus()` answers. Yoga already brings it |
|
|
65
|
+
| `typescript` | `^6.0.3 \|\| ^7.0.0` | As for `@softistx/janus` |
|
|
66
|
+
| `graphql-ws` | `^6.0.0`, **optional** | Only for subscriptions over a WebSocket, with `janusConnection()`. Nothing here imports it. For `graphql` 17, a `graphql-ws` whose peer range includes it — 6.3.0 does |
|
|
67
|
+
|
|
68
|
+
The floors are tested, not claimed: the package's specs and its typecheck run
|
|
69
|
+
on `graphql` 16.9.0, `@graphql-tools/utils` 10.0.0, `@envelop/core` 5.0.0
|
|
70
|
+
and `graphql-ws` 6.0.0 as well, together, with a single copy of `graphql`,
|
|
71
|
+
in the Floors job, on every CI run.
|
|
72
|
+
|
|
73
|
+
Like `@softistx/janus`, it expects `"moduleResolution": "bundler"`: the
|
|
74
|
+
declarations import without extensions, so `nodenext` is not supported.
|
|
75
|
+
|
|
76
|
+
The SDL ships twice: `janusTypeDefs`, a string for `createSchema`, and
|
|
77
|
+
`graphql/janus.graphqls` in the package, for a code generator or an editor
|
|
78
|
+
that reads files — `node_modules/@softistx/janus-graphql/graphql/janus.graphqls`.
|
|
79
|
+
|
|
80
|
+
## API
|
|
81
|
+
|
|
82
|
+
| Export | What it is |
|
|
83
|
+
| --- | --- |
|
|
84
|
+
| `useJanus({ auth, types?, access?, type?, clock?, apiKey?, loaders?, conditions? })` | The envelop plugin. `auth` is what `janus()` answered, or a function `(ctx) => instance` that picks the instance per request ([several issuers](#one-server-several-issuers)); `types` names the user types the directives may use when it is a function. Adds `ctx.janus` to every request's context, and applies the directives to every schema the server is given, once. `type` treats a user of any other type as anonymous. `clock` is what `@fresh` and `requireFresh()` read — the one given to `janus()`, when it is not the system's. `loaders` and `conditions` are what `@permission` needs beside `access`. `apiKey: true` also accepts an API key: `ctx.janus` gains `principal()` and `apiKey()`, `session()` is `null` for a key, `@fresh` refuses one (`STEP_UP_REQUIRED`); off, a key is anonymous. Under Yoga, a session `authenticate` renewed is sent again as `Set-Cookie` on the response, to a request that presented it as the cookie |
|
|
85
|
+
| `ctx.janus.user()`, `ctx.janus.session()` | Who the request belongs to, and the session it presented — `null` for an anonymous request. `auth.authenticate(request)` runs the first time either is asked, once per request, and never when neither is |
|
|
86
|
+
| `ctx.janus.principal()`, `ctx.janus.apiKey()` | With `useJanus({ apiKey: true })` only: the session or API key principal (narrow on `via`), and the key. See [the context guide](docs/guide/context.md) |
|
|
87
|
+
| `ctx.janus.access` | The `permissions()` instance given to `useJanus()`. Absent from the type — and from the context — without one |
|
|
88
|
+
| `janusTypeDefs` | The SDL: `@authenticated`, `@fresh`, `@permission` and the `JanusPermissionDenial` enum — prefixed, so it never collides with a type of your schema. The same text as `graphql/janus.graphqls` |
|
|
89
|
+
| `@authenticated(type: [String!])` | On a field, a type or an interface. A signed-in user, of one of the `type`s when it names some. Anonymous: `UNAUTHENTICATED`. Another type: `FORBIDDEN`. Every one that applies — the field's, its type's, its interfaces' — must hold |
|
|
90
|
+
| `@fresh(maxAge: Int!)` | On a field, a type or an interface. A session that proved who it is less than `maxAge` **seconds** ago — signed in, or confirmed since by `auth.stepUp.confirm`. Anonymous: `UNAUTHENTICATED`. Older, or an API key under `apiKey: true`: `STEP_UP_REQUIRED`, 403. Checked after `@authenticated`, before `@permission`; the smallest `maxAge` that applies holds; on a subscription field, checked when it subscribes |
|
|
91
|
+
| `@permission(name, type, id, onDeny)` | On a field, a type or an interface. A user holding permission `name` on the object of `type` whose id `id` reads — `args.<path>` or `parent.<path>`; `args.id` on a field, `parent.id` on a type. A list requires it on every id. Repeated, every one must hold, in order. Denied: `NOT_FOUND`, or `FORBIDDEN` with `onDeny: FORBIDDEN` |
|
|
92
|
+
| `loaders: { [type]: (id, ctx) => object \| null }` | The object `@permission` checks for an id alone — from `args`, or a parent field other than `id` — required for a type with a `fromField`, whose fields `access.can` reads. `null` answers `NOT_FOUND` |
|
|
93
|
+
| `conditions: { [type]: (object, ctx) => ctx }` | The `ctx` `@permission` passes to `access.can` for a permission that reaches a `when()` |
|
|
94
|
+
| `applyJanusDirectives(schema, { auth, type?, access?, loaders?, conditions? })` | The schema transform alone — what `useJanus()` runs — to check a schema in a test or a build script. Throws a `TypeError` naming the field for a directive no request could pass. Its guards read `ctx.janus`, which only `useJanus()` builds |
|
|
95
|
+
| `requireUser(ctx, { type? })` | The signed-in user, narrowed to `type` — one or a non-empty list — or a denial: `UNAUTHENTICATED`, `FORBIDDEN` |
|
|
96
|
+
| `requireFresh(ctx, maxAge)` | The request's session, once it proved who it is less than `maxAge` ago — a duration with its unit, `'10m'`, never a bare number — or a denial: `UNAUTHENTICATED`, `STEP_UP_REQUIRED` |
|
|
97
|
+
| `can(ctx, permission, object, options?)` | `access.can` for the request's user, typed as `access.can` is. Anonymous answers `false`. Shares the request's checks with `@permission`: one question, one check per request |
|
|
98
|
+
| `janusConnection({ auth, access?, type?, clock?, upgrade? })` | Subscriptions over graphql-ws (`auth` may be a function of the connection's context, as in `useJanus()`): `onConnect` for its `useServer()`, which accepts a connection whose `connectionParams.authorization` — else whose upgrade request's headers or cookie — authenticates, as a user of `type` when given, and refuses any other `4403`; an outage rejects, closed `4500`. Each operation's `ctx.janus` then authenticates from that credential, so the directives hold unchanged. `context` builds `{ janus }` for a server without Yoga; `upgrade` reads the upgrade request where the transport's `extra` does not carry it — Bun |
|
|
99
|
+
| `janusAvatarTypeDefs` | Opt-in SDL: `type JanusAvatar { id: ID!, updatedAt: String!, url(size: Int!): String! }` — `updatedAt` an ISO-8601 string, so no scalar is needed. The same text as `graphql/janus-avatar.graphqls`. Put `avatar: JanusAvatar` on your own types |
|
|
100
|
+
| `toJanusAvatar(user)` | The parent of an `avatar: JanusAvatar` field: `null` when `user.avatar` is `null`, else the user's id, the avatar's id and its date. Checks nothing about who asks |
|
|
101
|
+
| `avatarResolvers({ url })` | The resolvers of `JanusAvatar`: `updatedAt` as an ISO-8601 string, and `url(size:)` from your `url(avatar, size)`, where `avatar` is the `AvatarParent` (`userId`, `id`, `updatedAt`). A `size` below 1 is `BAD_USER_INPUT`, 400, before `url` is called |
|
|
102
|
+
| `janusSocialTypeDefs` | Opt-in SDL (`graphql/janus-social.graphqls`): `socialSignInStart`, `socialSignInComplete`, `linkSocial`, `unlinkSocial` and `socialLinks`, with `SocialFlowStart`, `JanusSocialLink` and the result union `SocialSignInResult`. It `extend`s `Query` and `Mutation` and needs `janusTypeDefs` |
|
|
103
|
+
| `socialResolvers({ auth, type?, answerToken? })` | The resolvers of that SDL (`Query`, `Mutation`, `SocialSignInResult`; merge them with yours). `auth` is the instance or a function of the context answering it, asked on every field (`null`, `undefined` or an instance with no `social` is `UNAUTHENTICATED`, 401). `socialSignInStart` answers `{ url, flow, expiresAt }` (as `linkSocial` does, both with `Cache-Control: no-store`) and sets no cookie: the BFF keeps `flow` and hands it to `socialSignInComplete(callbackUrl, flow)`, which sets the session cookie through `useJanus()`'s `onResponse`, or, with `answerToken: true`, sets no cookie and answers the session token in `SocialSignedIn.token` (with `Cache-Control: no-store`) for a BFF that forwards it as `Authorization: Bearer`. A refusal carries `returnTo` and `flowSpent` in `extensions`; `PROVIDER_ERROR` is 502 |
|
|
104
|
+
| `janusPasskeyTypeDefs` | Opt-in SDL (`graphql/janus-passkeys.graphqls`): `passkeys` and `passkeyRegistrationOptions` on `Query`; `registerPasskey`, `renamePasskey`, `removePasskey` and `confirmSecondFactorPasskey` on `Mutation`, with `JanusPasskey`, `JanusPasskeyRegistration` and `PasskeySignedIn`. WebAuthn options, responses and assertions are JSON `String`s. It `extend`s `Query` and `Mutation` and needs `janusTypeDefs` |
|
|
105
|
+
| `janusPasskeySignInTypeDefs` | Opt-in SDL (`graphql/janus-passkey-sign-in.graphqls`) for `janus({ passkeys: { firstFactor: true } })`: `passkeySignInOptions` on `Query` (type `JanusPasskeySignInChallenge`) and `passkeySignIn` on `Mutation`, which answers `PasskeySignedIn`. It `extend`s `Query` and `Mutation` and needs `janusTypeDefs` and `janusPasskeyTypeDefs` |
|
|
106
|
+
| `passkeyResolvers({ auth, type?, firstFactor?, answerToken?, device? })` | The resolvers of that SDL (`Query`, `Mutation`; merge them with yours). `auth` is the instance or a function of the context answering it (`null` is `UNAUTHENTICATED`; a missing surface is then a `TypeError` on the request). `firstFactor: true` adds `passkeySignInOptions` and `passkeySignIn`, with the cookie, `answerToken` and `device` of `confirmSecondFactorPasskey`. Throws a `TypeError` at wiring when `janus()` has no `passkeys`. `confirmSecondFactorPasskey` redeems a sign-in's challenge and sets the session cookie, or, with `answerToken: true`, answers `token` instead (with `Cache-Control: no-store`); `device: true` (or the device cookie's options) tracks the device and needs `janus({ devices })`. `registerPasskey` and `removePasskey` rely on the core's freshness (`STEP_UP_REQUIRED`). `SocialSecondFactor` carries `methods` and `passkeyOptions` for the page |
|
|
107
|
+
| `janusSecondFactorTypeDefs` | Opt-in SDL (`graphql/janus-second-factor.graphqls`): `secondFactor` and `sessionConfirmedUntil` on `Query`; `confirmSecondFactor`, `recoverSecondFactor`, `enrollSecondFactor`, `activateSecondFactor`, `regenerateRecoveryCodes`, `disableSecondFactor`, `requestStepUp` and `confirmStepUp` on `Mutation`, with `JanusSecondFactorStatus`, `JanusSecondFactorEnrolment`, `JanusRecoveryCodes`, `JanusSecondFactorChallenge`, `SecondFactorSignedIn`, `JanusStepUpChallenge` and `JanusStepUpConfirmed`. Timestamps are ISO-8601 `String`s. It `extend`s `Query` and `Mutation` and needs `janusTypeDefs` |
|
|
108
|
+
| `secondFactorResolvers({ auth, type?, answerToken?, device?, freshWithin?, guard?, sendStepUpCode? })` | The resolvers of that SDL (`Query`, `Mutation`; merge them with yours). Throws a `TypeError` at wiring when `auth` (or `auth[type]`) has no `secondFactor` surface. `auth` may be a function of the context answering the instance that serves the request (`SecondFactorAuthSource`), as for `passkeyResolvers()`: no instance is `UNAUTHENTICATED`, and one with no `secondFactor` a `TypeError` on that request. `confirmSecondFactor` and `recoverSecondFactor` redeem a sign-in's challenge and set the session cookie, or, with `answerToken: true`, answer `token` (with `Cache-Control: no-store`); `device` as for passkeys. Your policy is an option: `freshWithin` (`'10m'`) makes the four writes refuse a stale session (`STEP_UP_REQUIRED`) and `sessionConfirmedUntil` answer its end; `guard(action, user, ctx)` runs before each write and throws to refuse; `sendStepUpCode(issued, ctx)` sends the e-mailed code of a step-up for a user with no factor |
|
|
109
|
+
| `secondFactorViewerFields(options)` | The two fields — `secondFactor { enabled recoveryCodesLeft }` and `sessionConfirmedUntil` — for your own `Viewer` type: `resolvers: { Viewer: secondFactorViewerFields({ auth }) }` |
|
|
110
|
+
| `secondFactorChallengeOut(result, request?)` | The core's `status: 'secondFactor'` sign-in answer as a `JanusSecondFactorChallenge`, for your own sign-in resolver. Pass `ctx.request` and the response carries `Cache-Control: no-store`, as the challenge is single-use; without it, mark the response yourself |
|
|
111
|
+
| `janusInvitationTypeDefs` | Opt-in SDL (`graphql/janus-invitations.graphqls`): `invitations` and `invitationPreview` on `Query`; `issueInvitation`, `resendInvitation`, `revokeInvitation` and `acceptInvitation` on `Mutation`, with `JanusInvitation`, `JanusIssuedInvitation`, `JanusInvitationPage`, `JanusInvitationPreview` and the result union `InvitationAcceptResult` (`InvitationSignedIn`, `InvitationSecondFactor`, `InvitationSignIn`). Timestamps are ISO-8601 `String`s; `invitedBy` is `null` for an invitation the system issued. `invitations(scope, status?, role?, ref?, order?, limit?, after?)` filters and orders (`JanusInvitationOrder`: `OLDEST`, the default, or `NEWEST`), `JanusInvitationPage.totalCount` counts the matches lazily, and `JanusInvitation` answers `ref` and `type`, as does `JanusInvitationPreview`, which also answers `organization`; `issueInvitation` takes `ref` and `type`. It `extend`s `Query` and `Mutation` and needs `janusTypeDefs` |
|
|
112
|
+
| `invitationResolvers({ auth, authorize, sendInvitation?, answerCode?, answerToken?, device?, inviterType?, describeScope? })` | The resolvers of that SDL (`Query`, `Mutation`, `InvitationAcceptResult`; merge them with yours). Throws a `TypeError` at wiring when `janus()` has no `invitations`, `authorize` is missing, or neither `sendInvitation` nor `answerCode: true` says where the code goes. The four owner fields need a signed-in user (an API key's owner too, with `useJanus({ apiKey: true })`) and `authorize(action, { user, scope, input?, invitation?, page? }, ctx)` (`subject` is the exported `InvitationSubject`) — `'issue' \| 'resend' \| 'revoke' \| 'list'` — to answer `true`, else `NOT_FOUND`; `input` is the issue input (`issue`), `invitation` the stored invitation (`resend`, `revoke`: an id that names none in the scope is `NOT_FOUND` whatever `authorize` answers: it is asked without `invitation`; its answer and any error but a `GraphQLError` are ignored), `page` the list arguments (`list`: `status`, `role`, `ref`, `order` as `'asc' \| 'desc'`, `limit`, `after`). `issueInvitation` and `resendInvitation` hand the code to `sendInvitation({ action, invitation, code }, ctx)` and answer `code: null` (the code with `answerCode: true`), always `Cache-Control: no-store`. `describeScope(scope, ctx)` answers `{ name }` or `null` and fills the preview's `organization` (null when not given). `invitationPreview` and `acceptInvitation` are open to whoever holds the code: a new invitee, an account whose e-mail was never proved, or a proved account with no password yet (given one) gets the session cookie (or `token` with `answerToken: true`, the device cookie with `device`); a proved user who already has a password (the one given is ignored), or who has none and gave none, gets `InvitationSignIn` and no session |
|
|
113
|
+
| `apiKeysTypeDefs` | Opt-in SDL (`graphql/janus-api-keys.graphqls`): `apiKeys`, `boundApiKeys` and `apiKeyLifetimes` on `Query`; `createApiKey` and `revokeApiKey` on `Mutation`, with `JanusApiKey` (`status`: `ACTIVE`, `REVOKED` or `EXPIRED`; `expiresAt`, `lastUsedAt`, `bound`), `JanusCreatedApiKey` (the `secret`, answered once, `no-store`), `JanusApiKeyPage` and `JanusApiKeyLifetimes`. It `extend`s `Query` and `Mutation` and needs `janusTypeDefs` |
|
|
114
|
+
| `apiKeysResolvers({ auth, lifetimes, authorize: { create, list, revoke }, bound? })` | The resolvers of that SDL (`Query`, `Mutation`; merge them with yours). `lifetimes` is `{ days: [30, 90, 365], default: 90 }`, each one of the lifetimes `janus({ apiKeys })` configures. `authorize` is the only guard: each hook answers `true`, else `NOT_FOUND`; a thrown `GraphQLError` is answered as it is (`subject`: `ApiKeyCreateSubject`, `ApiKeyListSubject`, `ApiKeyRevokeSubject`, each with `user` and `bound`; an unknown key id on revoke is asked without `key`). `bound(boundTo, ctx)` names the object a key is bound to (it needs the store's `bound` capability); without it, or answering `null` for an asked `boundTo`, that is `NOT_FOUND`. `createApiKey` is the core's: `STEP_UP_REQUIRED` for a stale session and always for a request signed by a key, and the e-mail must be verified. Arguments are bounded (`name` 100, 32 `scopes` of 100, `boundTo` 200): `BAD_USER_INPUT`, `extensions.field`. Throws a `TypeError` at wiring when `auth` has no `apiKeys`, `authorize` lacks a hook, `bound` is not a function, or `lifetimes` is empty or its default is not in `days`. Needs `@softistx/janus` with `apiKeys.get` and the `bound` option of `apiKeys.list` |
|
|
115
|
+
| `ApiKeysResolversOptions`, `ApiKeysAuth`, `ApiKeysAuthorize`, `ApiKeyLifetimes`, `ApiKeySubjectBase`, `ApiKeyCreateSubject`, `ApiKeyListSubject`, `ApiKeyRevokeSubject`, `ApiKeysResolvers` | The types of the API key resolvers |
|
|
116
|
+
| `janusMaskError({ report?, fallback?, mapCode? })` | Yoga's `maskedErrors.maskError`: a `JanusError` a resolver let through answered with its code and status; anything else to `fallback`, which defaults to what Yoga's own `maskError` does (a failure with no `data`, such as a context factory that throws, stays HTTP 500; `isDev` shows the original error), so passing Yoga's `maskError` is not needed. `report` is called once with every `JanusError` answered 5xx — a directive's and a helper's too — and cannot change the answer. `mapCode(code, error)` answers `{ code, message?, status? }` to put your own code on any `GraphQLError` the mask returns (`UNAUTHENTICATED`, `FORBIDDEN`, `NOT_FOUND`…), or `undefined` to keep it; nodes, path and `originalError` are kept. `janusMaskError(fallback)`, the fallback alone, still works. The result fits Yoga's `maskError`, envelop 5's `useMaskedErrors` (`isDev` third) and envelop 6's (`context` third): `JanusMaskError` |
|
|
117
|
+
| `janusErrorOf(error)` | The `JanusError` behind a resolver's error (itself, or under a chain of `GraphQLError`s' `originalError`), or `undefined`: map a refusal (`INVITATION_NOT_PENDING`, `NOT_FOUND`…) per operation |
|
|
118
|
+
| `janusGraphQLError(error)` | A `JanusError` as the `GraphQLError` the client reads: its code, its status, and only what the client can act on |
|
|
119
|
+
| `denial(code, message?)` | A denial of your own: `UNAUTHENTICATED` 401, `FORBIDDEN` 403, `NOT_FOUND` 404. For a stale session, call `requireFresh()`, whose `STEP_UP_REQUIRED` is `@softistx/janus`'s |
|
|
120
|
+
| `AuthSource<A, Ctx?>`, `AuthContext` | The type of `auth` in `useJanus()` and `janusConnection()` (an instance, or a function of the request's context answering one) and the context `useJanus()`'s function receives: `{ request?: Request }` plus the rest of Yoga's context |
|
|
121
|
+
| `JanusContext<typeof auth, typeof access?, Type?, ApiKey?>` | What `useJanus()` adds to the context, for your resolvers' `ctx` |
|
|
122
|
+
| `deviceOf(request, options?)` and `sendDevice(request, deviceToken, options?)` | The device cookie of a sign-in mutation ([guide](docs/guide/context.md#a-sign-in-mutation-and-the-device-cookie)), as in `@softistx/janus-hono`: `deviceOf(ctx.request)` is the token the `janus-device` cookie holds, or `null` (an empty value counts as none) — what `signIn` takes as `device`; `sendDevice(ctx.request, result.deviceToken)` sets it on the response through `useJanus()`, in any resolver, beside a renewed session cookie. `DEVICE_COOKIE` is the default name; `DeviceCookieOptions` (`name?`, `domain?`, `path?`, `sameSite?`, `secure?`, `maxAge?`) are the strict defaults — `Path=/`, `SameSite=Lax`, `Secure`, `HttpOnly`, four hundred days — and the same object goes to both. Throws a `RangeError` for a `maxAge` outside 0 to 34560000 and a `TypeError` for a name, `__Host-`/`__Secure-` prefix or attribute a browser would refuse ([troubleshooting](docs/troubleshooting.md#rangeerror-devicecookie-maxage-must-be-a-number-of-seconds-from-0-to-34560000-400-days-got-)). |
|
|
123
|
+
| `JanusOptions`, `JanusOnContext`, `JanusConnectionOptions`, `JanusConnection`, `ConnectionContext`, `JanusDirectivesOptions`, `Loaders`, `Conditions`, `LoadedObject`, `RequireUserOptions`, `Auth`, `UserOfAuth`, `DenialCode`, `MaskError`, `JanusMaskError`, `JanusMaskErrorOptions`, `AvatarOwner`, `AvatarParent`, `AvatarResolvers`, `AvatarResolversOptions`, `SocialAuth`, `SocialAuthSource`, `SocialResolvers`, `SocialResolversOptions`, `PasskeyAuth`, `PasskeyAuthSource`, `PasskeyFirstFactorSurface`, `PasskeyFirstFactorTypeApi`, `PasskeySurface`, `PasskeyResolvers`, `PasskeyResolversOptions`, `PasskeyTypeApi`, `SecondFactorAuth`, `SecondFactorAuthSource`, `SecondFactorSurface`, `SecondFactorResolvers`, `SecondFactorResolversOptions`, `SecondFactorViewerFields`, `SecondFactorTypeApi`, `InvitationAuth`, `InvitationResolvers`, `InvitationResolversOptions`, `InvitationAction`, `SecondFactorAction`, `ChallengeIn`, `ChallengeOut`, `DeviceCookieOptions` | The types of the arguments and answers above |
|
|
124
|
+
|
|
125
|
+
## Directives
|
|
126
|
+
|
|
127
|
+
```graphql
|
|
128
|
+
type Query {
|
|
129
|
+
me: User @authenticated # any signed-in user
|
|
130
|
+
record(id: ID!): Record @permission(name: "view", type: "record") # args.id
|
|
131
|
+
records(ids: [ID!]!): [Record!]!
|
|
132
|
+
@permission(name: "view", type: "record", id: "args.ids") # every id
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
type Record @permission(name: "view", type: "record") { # parent.id: the record itself
|
|
136
|
+
title: String
|
|
137
|
+
billing: Billing @permission(name: "manage", type: "record", onDeny: FORBIDDEN)
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
type Mutation {
|
|
141
|
+
changeEmail(email: String!): User @fresh(maxAge: 600) # signed in or stepped up < 10 min ago
|
|
142
|
+
}
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
```ts
|
|
146
|
+
useJanus({
|
|
147
|
+
auth,
|
|
148
|
+
access,
|
|
149
|
+
loaders: { record: (id, ctx) => records.find(id) }, // record has a fromField: an id alone is not enough
|
|
150
|
+
conditions: { record: (record, ctx: Context) => ({ onShift: ctx.shift.open }) }, // the ctx of a when() record's permissions reach
|
|
151
|
+
});
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
Each runs before the resolver, which a refused request never reaches.
|
|
155
|
+
`@fresh(maxAge)` takes **seconds**, and answers an older session
|
|
156
|
+
`STEP_UP_REQUIRED`: the client then calls your two step-up mutations,
|
|
157
|
+
which run `auth.stepUp.request` and `confirm` — shown in
|
|
158
|
+
[the step-up guide](docs/guide/step-up.md) — and sends the request again.
|
|
159
|
+
Every `@authenticated` is checked first, then `@fresh`, then each
|
|
160
|
+
`@permission`, so a stale session asks no permission check.
|
|
161
|
+
`@permission` implies a signed-in user, and asks `access.can` with the parent
|
|
162
|
+
itself when the id is `parent.id`, with what `loaders[type]` answers for an
|
|
163
|
+
id of a type with a `fromField`, and with `{ type, id }` otherwise. Every
|
|
164
|
+
directive that applies must hold — the field's, its type's, its
|
|
165
|
+
interfaces' — asked outermost first, so a type's `NOT_FOUND` answers before
|
|
166
|
+
a field's `FORBIDDEN` could tell the object exists. The same question asked
|
|
167
|
+
twice in a request, by two fields or by a directive and `can()`, is one
|
|
168
|
+
check. What no request could pass — an object type or a permission the
|
|
169
|
+
model does not declare, a malformed `id:`, an argument the field does not
|
|
170
|
+
take, a missing loader or condition, a `maxAge` not above zero — is a
|
|
171
|
+
`TypeError` at start-up naming the field. Detail: [the directives guide](docs/guide/directives.md).
|
|
172
|
+
|
|
173
|
+
## Avatars
|
|
174
|
+
|
|
175
|
+
```graphql
|
|
176
|
+
type Viewer {
|
|
177
|
+
avatar: JanusAvatar @permission(name: "viewAvatar", type: "user", id: "parent.id")
|
|
178
|
+
}
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
import {
|
|
183
|
+
avatarResolvers,
|
|
184
|
+
janusAvatarTypeDefs,
|
|
185
|
+
janusTypeDefs,
|
|
186
|
+
requireUser,
|
|
187
|
+
toJanusAvatar,
|
|
188
|
+
} from '@softistx/janus-graphql';
|
|
189
|
+
import { createSchema } from 'graphql-yoga';
|
|
190
|
+
|
|
191
|
+
const typeDefs = /* GraphQL */ `
|
|
192
|
+
type Viewer {
|
|
193
|
+
avatar: JanusAvatar @permission(name: "viewAvatar", type: "user", id: "parent.id")
|
|
194
|
+
}
|
|
195
|
+
type Query {
|
|
196
|
+
viewer: Viewer @authenticated
|
|
197
|
+
}
|
|
198
|
+
`;
|
|
199
|
+
|
|
200
|
+
createSchema({
|
|
201
|
+
typeDefs: [janusTypeDefs, janusAvatarTypeDefs, typeDefs],
|
|
202
|
+
resolvers: {
|
|
203
|
+
...avatarResolvers({ url: ({ userId, id }, size) => `/avatars/${userId}/${size}?v=${encodeURIComponent(id)}` }),
|
|
204
|
+
Query: { viewer: (_, __, ctx) => requireUser(ctx) },
|
|
205
|
+
Viewer: { avatar: (user) => toJanusAvatar(user) },
|
|
206
|
+
},
|
|
207
|
+
});
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
`url(size:)` is the path of **your own route**, which checks the session and
|
|
211
|
+
the access rule before it streams the image; janus keeps only the avatar's id.
|
|
212
|
+
Detail: [the avatars guide](docs/guide/avatars.md).
|
|
213
|
+
|
|
214
|
+
## One server, several issuers
|
|
215
|
+
|
|
216
|
+
`auth` may be a function of the request's context instead of one instance,
|
|
217
|
+
so a single Yoga server serves several `janus()` instances — each with its
|
|
218
|
+
own stores, cookie and user types — and picks the one per request:
|
|
219
|
+
|
|
220
|
+
```ts
|
|
221
|
+
const issuers = { 'a.example': authA, 'b.example': authB };
|
|
222
|
+
|
|
223
|
+
useJanus({
|
|
224
|
+
// ctx.request over HTTP; null (or a throw) refuses the request
|
|
225
|
+
auth: (ctx) => issuers[new URL(ctx.request?.url ?? 'http://x').host],
|
|
226
|
+
types: ['patient', 'staff'], // the user types the directives may name
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
janusConnection({
|
|
230
|
+
// graphql-ws: the connection's ctx — read the upgrade request in ctx.extra.request
|
|
231
|
+
auth: (ctx) => issuers[hostOf(ctx)], // hostOf: your own reading of the upgrade request, ctx.extra.request on ws
|
|
232
|
+
});
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
The function may be async. It runs once per request, the first time
|
|
236
|
+
`ctx.janus.user()` or `session()` asks, so a query that reads neither never
|
|
237
|
+
calls it. A session of one issuer is not seen through another: each
|
|
238
|
+
instance authenticates against its own store. A plain instance works as
|
|
239
|
+
before. The details are in [the context guide](docs/guide/context.md#several-issuers-one-server).
|
|
240
|
+
|
|
241
|
+
## Social sign-in
|
|
242
|
+
|
|
243
|
+
Opt-in, beside the avatar type. The BFF keeps the flow in its own cookie:
|
|
244
|
+
|
|
245
|
+
```ts
|
|
246
|
+
import { janusSocialTypeDefs, janusTypeDefs, socialResolvers } from '@softistx/janus-graphql';
|
|
247
|
+
import { createSchema } from 'graphql-yoga';
|
|
248
|
+
|
|
249
|
+
createSchema({
|
|
250
|
+
typeDefs: [janusTypeDefs, janusSocialTypeDefs, typeDefs], // typeDefs declares Query and Mutation
|
|
251
|
+
resolvers: { ...socialResolvers({ auth }), SocialSignedIn: { user: (signedIn: { user: unknown }) => signedIn.user } },
|
|
252
|
+
});
|
|
253
|
+
// mutation { socialSignInStart(provider: "google", returnTo: "/home") { url flow expiresAt } }
|
|
254
|
+
// mutation { socialSignInComplete(callbackUrl: "https://app/cb?code=…&state=…", flow: "…") { … } }
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
A BFF that keeps the session in its own cookie and forwards it as
|
|
258
|
+
`Authorization: Bearer` passes `socialResolvers({ auth, answerToken: true })`:
|
|
259
|
+
`SocialSignedIn.token` then answers the session token, with `Cache-Control: no-store`, and no cookie is set.
|
|
260
|
+
|
|
261
|
+
`linkSocial` and `unlinkSocial` are `@authenticated @fresh(maxAge: 600)`. Detail:
|
|
262
|
+
[the social guide](docs/guide/social.md).
|
|
263
|
+
|
|
264
|
+
## Passkeys
|
|
265
|
+
|
|
266
|
+
Opt-in, for users who hold passkeys as a second factor (`janus({ passkeys })`):
|
|
267
|
+
|
|
268
|
+
```ts
|
|
269
|
+
import { janusPasskeyTypeDefs, janusTypeDefs, passkeyResolvers } from '@softistx/janus-graphql';
|
|
270
|
+
|
|
271
|
+
createSchema({
|
|
272
|
+
typeDefs: [janusTypeDefs, janusPasskeyTypeDefs, typeDefs], // typeDefs declares Query and Mutation
|
|
273
|
+
resolvers: { ...passkeyResolvers({ auth }), PasskeySignedIn: { user: (signedIn: { user: unknown }) => signedIn.user } },
|
|
274
|
+
});
|
|
275
|
+
// { passkeyRegistrationOptions { options challenge expiresAt } }
|
|
276
|
+
// mutation { registerPasskey(challenge: "…", response: "<JSON>", name: "Laptop") { credentialId } }
|
|
277
|
+
// mutation { confirmSecondFactorPasskey(challenge: "…", assertion: "<JSON>") { userId expiresAt } }
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
The browser's JSON travels as strings. Detail: [the passkeys guide](docs/guide/passkeys.md).
|
|
281
|
+
|
|
282
|
+
### Passkey as the first factor
|
|
283
|
+
|
|
284
|
+
With `janus({ passkeys: { firstFactor: true } })` a visitor signs in with a passkey alone; the instance needs no `secondFactor`. Add `janusPasskeySignInTypeDefs` (beside `janusPasskeyTypeDefs`) and `firstFactor: true`:
|
|
285
|
+
|
|
286
|
+
```ts
|
|
287
|
+
createSchema({
|
|
288
|
+
typeDefs: [janusTypeDefs, janusPasskeyTypeDefs, janusPasskeySignInTypeDefs, typeDefs],
|
|
289
|
+
resolvers: { ...passkeyResolvers({ auth, firstFactor: true }), PasskeySignedIn: { user: (signedIn: { user: unknown }) => signedIn.user } },
|
|
290
|
+
});
|
|
291
|
+
// { passkeySignInOptions { options challenge expiresAt } }
|
|
292
|
+
// mutation { passkeySignIn(challenge: "…", assertion: "<JSON>") { userId expiresAt newDevice } }
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
### One auth instance per request
|
|
296
|
+
|
|
297
|
+
`auth` may be a function of the GraphQL context, as it is for `useJanus()`, to serve several tenants from one schema. Give both the same function:
|
|
298
|
+
|
|
299
|
+
```ts
|
|
300
|
+
const authFor = (ctx: { host: string }) => instances.get(ctx.host); // null: UNAUTHENTICATED
|
|
301
|
+
passkeyResolvers({ auth: authFor, firstFactor: true });
|
|
302
|
+
useJanus({ auth: authFor, types: ['user'] });
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
## Second factor (TOTP)
|
|
306
|
+
|
|
307
|
+
Opt-in, for users who may hold an authenticator app (`janus({ secondFactor })`):
|
|
308
|
+
|
|
309
|
+
```ts
|
|
310
|
+
import {
|
|
311
|
+
janusSecondFactorTypeDefs,
|
|
312
|
+
janusTypeDefs,
|
|
313
|
+
secondFactorResolvers,
|
|
314
|
+
secondFactorViewerFields,
|
|
315
|
+
} from '@softistx/janus-graphql';
|
|
316
|
+
|
|
317
|
+
const options = { auth, freshWithin: '10m' } as const; // your policy: the freshness window
|
|
318
|
+
createSchema({
|
|
319
|
+
typeDefs: [janusTypeDefs, janusSecondFactorTypeDefs, typeDefs], // typeDefs declares Query, Mutation and Viewer
|
|
320
|
+
resolvers: {
|
|
321
|
+
...secondFactorResolvers(options),
|
|
322
|
+
Viewer: secondFactorViewerFields(options), // Viewer.secondFactor, Viewer.sessionConfirmedUntil
|
|
323
|
+
SecondFactorSignedIn: { user: (signedIn: { user: unknown }) => signedIn.user },
|
|
324
|
+
},
|
|
325
|
+
});
|
|
326
|
+
// mutation { enrollSecondFactor { secret uri } }
|
|
327
|
+
// mutation { activateSecondFactor(code: "123456") { recoveryCodes } }
|
|
328
|
+
// mutation { confirmSecondFactor(challenge: "…", code: "654321") { userId expiresAt } }
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
Detail, with the sign-in and the step-up: [the second-factor guide](docs/guide/second-factor.md).
|
|
332
|
+
|
|
333
|
+
## Invitations
|
|
334
|
+
|
|
335
|
+
Opt-in, for people invited into a scope (an organization, a team) with `janus({ invitations })`. You say who may invite and where the code goes:
|
|
336
|
+
|
|
337
|
+
```ts
|
|
338
|
+
import { invitationResolvers, janusInvitationTypeDefs, janusTypeDefs, can } from '@softistx/janus-graphql';
|
|
339
|
+
|
|
340
|
+
createSchema({
|
|
341
|
+
typeDefs: [janusTypeDefs, janusInvitationTypeDefs, typeDefs], // typeDefs declares Query and Mutation
|
|
342
|
+
resolvers: {
|
|
343
|
+
...invitationResolvers({
|
|
344
|
+
auth,
|
|
345
|
+
authorize: (action, { scope }, ctx: Context) => can(ctx, 'invite', { type: 'organization', id: scope }), // the hooks are methods: type `ctx` as your context
|
|
346
|
+
sendInvitation: ({ invitation, code }) => mailer.sendInvitation(invitation, `https://app.test/join#${code}`),
|
|
347
|
+
}),
|
|
348
|
+
},
|
|
349
|
+
});
|
|
350
|
+
// mutation { issueInvitation(scope: "acme", email: "grace@example.test", name: "Grace", role: "member") { invitation { id status } } }
|
|
351
|
+
// mutation { issueInvitation(scope: "acme", email: "grace@example.test", name: "Grace", role: "member", ref: "crm-1", type: "staff") { invitation { id ref type } } }
|
|
352
|
+
// query { invitations(scope: "acme", role: "member", ref: "crm-1", order: NEWEST, limit: 20) { items { id email ref type } nextCursor totalCount } }
|
|
353
|
+
// query { invitations(scope: "acme", lapsed: EXCLUDE) { items { id email } totalCount } } # leave lapsed (pending, past expiry) out; ONLY keeps just them; needs @softistx/janus 0.49+
|
|
354
|
+
// query { invitationPreview(code: "…") { scope email name role type organization needsPassword } }
|
|
355
|
+
// mutation { acceptInvitation(code: "…", password: "…") { __typename … on InvitationSignedIn { userId scope role } } }
|
|
356
|
+
```
|
|
357
|
+
|
|
358
|
+
A new invitee's `acceptInvitation` sets the session cookie; a proved user who already has a password (or has none and gave none) is answered `InvitationSignIn` and sent to the sign-in page. `extend type InvitationSignedIn { user: Viewer! }` plus an `InvitationSignedIn: { user }` resolver is optional. Detail: [the invitations guide](docs/guide/invitations.md).
|
|
359
|
+
|
|
360
|
+
## API keys
|
|
361
|
+
|
|
362
|
+
Opt-in, for personal API keys with `janus({ apiKeys })`, optionally bound to an object (a workspace). You say who may create, list and revoke:
|
|
363
|
+
|
|
364
|
+
```ts
|
|
365
|
+
import { apiKeysResolvers, apiKeysTypeDefs, janusTypeDefs, can } from '@softistx/janus-graphql';
|
|
366
|
+
|
|
367
|
+
// Context: YogaInitialContext & JanusContext<typeof auth, typeof access>, as in the quick start.
|
|
368
|
+
// The hooks are methods: type `ctx` as your context and `can(ctx, …)` reads it.
|
|
369
|
+
|
|
370
|
+
createSchema({
|
|
371
|
+
typeDefs: [janusTypeDefs, apiKeysTypeDefs, typeDefs], // typeDefs declares Query and Mutation
|
|
372
|
+
resolvers: {
|
|
373
|
+
...apiKeysResolvers({
|
|
374
|
+
auth, // janus({ …, apiKeys: { store, prefix, lifetimes: ['30d', '90d', '365d'], maxActive } })
|
|
375
|
+
lifetimes: { days: [30, 90, 365], default: 90 },
|
|
376
|
+
bound: (asked) => (asked === null ? null : { type: 'workspace', id: asked }),
|
|
377
|
+
authorize: {
|
|
378
|
+
create: ({ bound }, ctx: Context) => bound !== null && can(ctx, 'member', bound),
|
|
379
|
+
list: ({ bound, every }, ctx: Context) => bound !== null && can(ctx, every ? 'owner' : 'member', bound),
|
|
380
|
+
revoke: ({ bound, own }, ctx: Context) => own === true || (bound !== null && can(ctx, 'owner', bound)),
|
|
381
|
+
},
|
|
382
|
+
}),
|
|
383
|
+
},
|
|
384
|
+
});
|
|
385
|
+
// mutation { createApiKey(name: "CI", lifetimeDays: 90, scopes: ["deploy:read"], boundTo: "acme") { secret apiKey { id prefix status expiresAt } } }
|
|
386
|
+
// query { apiKeys(boundTo: "acme", limit: 20) { items { id name status lastUsedAt } nextCursor } }
|
|
387
|
+
// query { boundApiKeys(boundTo: "acme") { items { id userId name status } nextCursor } }
|
|
388
|
+
// mutation { revokeApiKey(id: "…", boundTo: "acme") { id status } }
|
|
389
|
+
```
|
|
390
|
+
|
|
391
|
+
The `secret` is answered once, `Cache-Control: no-store`. `createApiKey` asks for a session that proved who it is recently (`STEP_UP_REQUIRED`) and never works from a request signed by a key. Detail: [the API keys guide](docs/guide/api-keys.md).
|
|
392
|
+
|
|
393
|
+
## Subscriptions over graphql-ws
|
|
394
|
+
|
|
395
|
+
Yoga's recommended graphql-ws setup, with `onConnect` added:
|
|
396
|
+
|
|
397
|
+
```ts
|
|
398
|
+
import { janusConnection } from '@softistx/janus-graphql';
|
|
399
|
+
import { useServer } from 'graphql-ws/use/ws';
|
|
400
|
+
|
|
401
|
+
useServer(
|
|
402
|
+
{
|
|
403
|
+
onConnect: janusConnection({ auth }).onConnect, // no valid session: closed 4403
|
|
404
|
+
execute: (args: any) => args.rootValue.execute(args),
|
|
405
|
+
subscribe: (args: any) => args.rootValue.subscribe(args),
|
|
406
|
+
onSubscribe: async (ctx, _id, params) => {
|
|
407
|
+
const { schema, execute, subscribe, contextFactory, parse, validate } =
|
|
408
|
+
yoga.getEnveloped({ ...ctx, req: ctx.extra.request, socket: ctx.extra.socket, params });
|
|
409
|
+
const args = {
|
|
410
|
+
schema,
|
|
411
|
+
operationName: params.operationName,
|
|
412
|
+
document: parse(params.query),
|
|
413
|
+
variableValues: params.variables,
|
|
414
|
+
contextValue: await contextFactory(), // useJanus() finds the connection by ctx.extra
|
|
415
|
+
rootValue: { execute, subscribe },
|
|
416
|
+
};
|
|
417
|
+
const errors = validate(args.schema, args.document);
|
|
418
|
+
return errors.length ? errors : args;
|
|
419
|
+
},
|
|
420
|
+
},
|
|
421
|
+
wsServer,
|
|
422
|
+
);
|
|
423
|
+
```
|
|
424
|
+
|
|
425
|
+
A browser's session cookie travels on the upgrade request; any other client
|
|
426
|
+
sends `connectionParams: { authorization: 'Bearer <token>' }`, which is
|
|
427
|
+
read first. Each operation is authenticated again from that credential
|
|
428
|
+
when it subscribes: `@authenticated` and `@fresh` are checked then, and
|
|
429
|
+
`@permission` on every event. A session revoked mid-stream is refused at
|
|
430
|
+
the next subscribe, not at the next event. Detail, Bun, and a server
|
|
431
|
+
without Yoga: [the subscriptions guide](docs/guide/subscriptions.md).
|
|
432
|
+
|
|
433
|
+
## Errors
|
|
434
|
+
|
|
435
|
+
This package defines **no error class**. A denial is a `GraphQLError`, and
|
|
436
|
+
every one carries a `code` and the HTTP status Yoga answers with:
|
|
437
|
+
|
|
438
|
+
```json
|
|
439
|
+
{ "errors": [{ "message": "Not signed in", "path": ["me"], "extensions": { "code": "UNAUTHENTICATED" } }] }
|
|
440
|
+
```
|
|
441
|
+
|
|
442
|
+
| Code | Status | When |
|
|
443
|
+
| --- | --- | --- |
|
|
444
|
+
| `UNAUTHENTICATED` | 401 | An anonymous request reached a guarded field, `requireUser()` or `requireFresh()` |
|
|
445
|
+
| `FORBIDDEN` | 403 | A user of a type the directive or `requireUser()` does not name; a `@permission(onDeny: FORBIDDEN)` denied |
|
|
446
|
+
| `STEP_UP_REQUIRED` | 403 | A session older than `@fresh(maxAge)` or `requireFresh()` allows: ask for a step-up, then send the request again |
|
|
447
|
+
| `NOT_FOUND` | 404 | A `@permission` denied — its default — or a loader answered `null`; `denial('NOT_FOUND')` |
|
|
448
|
+
| `SERVICE_UNAVAILABLE` | 503 | A store could not answer — `STORE_FAILED`. **Never a denial** |
|
|
449
|
+
| `BAD_USER_INPUT` | 400 | an API key argument over its maximum, a `createApiKey(lifetimeDays:)` outside `lifetimes.days`, an `apiKeys` or `boundApiKeys` `limit` that is not a positive integer (`extensions.field`); `invitations(after:)` with a cursor issued for another list — the core's `CURSOR_FILTER_MISMATCH`, remapped; an invitation string argument over its maximum (`password` 1024, `code` 43, `email` 254, `name`, `role` and `ref` 100, …), with `extensions.field` |
|
|
450
|
+
| any other `JanusErrorCode` | its [`statusOf`](https://github.com/softistx/nxgt-janus/blob/develop/packages/janus/docs/guide/errors.md) | A `JanusError` a resolver let through: `CREDENTIALS_INVALID` 401, `MAIL_THROTTLED` 429, `LOGIN_TAKEN` 409, … |
|
|
451
|
+
|
|
452
|
+
The status sits in `extensions.http.status`, which Yoga reads to answer the
|
|
453
|
+
HTTP response and strips from the body. `USER_INVALID` adds `issues`,
|
|
454
|
+
`PASSWORD_TOO_SHORT` `minLength`, `CODE_INVALID` `attemptsLeft` (and `retryAfter` once the user's app-code window is spent), `API_KEY_LIMIT` and `INVITATION_LIMIT` `maxActive`, `API_KEY_INVALID` and `INVITATION_INVALID` `field` (and, for an invitation code, `reason`: `unknown`, `expired`, `accepted` or `revoked`), and a
|
|
455
|
+
throttled `CREDENTIALS_INVALID`, `MAIL_THROTTLED` or window-spent `CODE_INVALID` `retryAfter` — with a `Retry-After` header in
|
|
456
|
+
`extensions.http.headers`, which Yoga answers with; nothing
|
|
457
|
+
else — never any other `reason`, nor `login`, a hash prefix or a cause. The message is a
|
|
458
|
+
fixed one per status, never the core's: read `code`. Detail, and the status of a
|
|
459
|
+
response with several errors: [the errors guide](docs/guide/errors.md).
|
|
460
|
+
|
|
461
|
+
The message carries nothing of the store's, and a directive answers an
|
|
462
|
+
outage itself, before any resolver of yours could log it. `report` sees
|
|
463
|
+
every `JanusError` answered 5xx, once, whichever path it took:
|
|
464
|
+
|
|
465
|
+
```ts
|
|
466
|
+
createYoga({
|
|
467
|
+
schema,
|
|
468
|
+
plugins: [useJanus({ auth, access })],
|
|
469
|
+
maskedErrors: {
|
|
470
|
+
maskError: janusMaskError({
|
|
471
|
+
report: (error) => logger.error({ code: error.code, cause: error.cause }), // slot, operation: which call failed
|
|
472
|
+
}),
|
|
473
|
+
},
|
|
474
|
+
});
|
|
475
|
+
```
|
|
476
|
+
|
|
477
|
+
## Traps
|
|
478
|
+
|
|
479
|
+
- **`magicLink: { enabled: false }` reaches the client as `extensions.code:
|
|
480
|
+
"MAGIC_LINK_DISABLED"`, status 404.** The error mapping follows the core's
|
|
481
|
+
`statusOf`; this package defines no magic-link field. Expose
|
|
482
|
+
`auth.magicLink.enabled` yourself (a `Boolean` field) to hide the button.
|
|
483
|
+
- **Versions up to 0.30.0 treat the optional peers as required.** Their package document lacks `peerDependenciesMeta` ([details](docs/troubleshooting.md#optional-peers-are-installed-as-required)), so Bun installs `graphql-ws` even when you do not use it. `bun install --omit=peer` skips it, but it also skips the required peers: add those back with `bun add @softistx/janus @envelop/core @graphql-tools/utils graphql typescript`, plus `graphql-ws` only for subscriptions.
|
|
484
|
+
- **Without `janusMaskError()`, a `JanusError` from a resolver is Yoga's
|
|
485
|
+
masked 500.** A guarded field and `requireUser()` answer an outage 503 on
|
|
486
|
+
their own; `ctx.janus.user()` read directly, or `auth.signIn` in a mutation,
|
|
487
|
+
does not. Wire `maskedErrors: { maskError: janusMaskError() }`.
|
|
488
|
+
- **An `auth` function answering `null` is a `TypeError`, not anonymous.**
|
|
489
|
+
Return an instance, or throw the error you want the client to read; a
|
|
490
|
+
request no issuer owns should not fall back to a default by accident. The
|
|
491
|
+
opt-in resolvers (`socialResolvers`, `passkeyResolvers`, …) and `access`
|
|
492
|
+
still take one fixed instance.
|
|
493
|
+
- **`ctx.janus.user()` is `null` where no directive guards the field.** Read
|
|
494
|
+
it only where anonymous is a valid answer, or call `requireUser(ctx)`.
|
|
495
|
+
- **A type's `@authenticated` guards its fields, not the field that returns
|
|
496
|
+
it.** `type Ward @authenticated` leaves `Query.ward` open: its resolver runs
|
|
497
|
+
for an anonymous request, and the error lands on `ward.name`. Put the
|
|
498
|
+
directive on the field too — or call `requireUser()`, as above — when the
|
|
499
|
+
lookup itself must not run.
|
|
500
|
+
- **One refused field sets the status of the whole response.** Yoga answers
|
|
501
|
+
the highest `extensions.http.status` among the errors, so `{ open me }`
|
|
502
|
+
from an anonymous request is a 401 whose `data` still holds `open`. A client
|
|
503
|
+
reads `data` and `errors`, not only the status.
|
|
504
|
+
- **A renewed session is sent back only on an HTTP response from Yoga.**
|
|
505
|
+
`useJanus()` sets it in Yoga's `onResponse`, which a server on envelop
|
|
506
|
+
alone never calls; and an operation over graphql-ws has no response at
|
|
507
|
+
all. There, `ctx.janus` still renews the session in the store, but the
|
|
508
|
+
browser keeps the cookie with its old expiry until the next renewal over
|
|
509
|
+
HTTP, a `renewAfter` later: a browser whose only traffic is the WebSocket
|
|
510
|
+
should renew through an HTTP route of yours.
|
|
511
|
+
- **A sign-in mutation passes the device itself.** `@softistx/janus-graphql`
|
|
512
|
+
signs nobody in: with `janus({ devices })`, call
|
|
513
|
+
`auth.signIn(input, { device: deviceOf(ctx.request) })` and, when it answers
|
|
514
|
+
a `deviceToken`, `sendDevice(ctx.request, result.deviceToken)`. That goes
|
|
515
|
+
through `useJanus()`'s `onResponse`, so it sets the cookie over HTTP
|
|
516
|
+
through Yoga only; over graphql-ws the context has no request, and both helpers throw a `TypeError` saying so. See
|
|
517
|
+
[the context](docs/guide/context.md#a-sign-in-mutation-and-the-device-cookie).
|
|
518
|
+
- **An `auth` of your own needs `cookie` for the renewal.** A wrapper that
|
|
519
|
+
passes on only `authenticate` and `types` sends no renewed cookie; pass
|
|
520
|
+
`cookie: auth.cookie` along.
|
|
521
|
+
- **`useJanus({ type })` narrows the whole server.** A user of any other type
|
|
522
|
+
is anonymous everywhere, and a directive naming another type is refused
|
|
523
|
+
when the schema is built.
|
|
524
|
+
- **On a field, `@permission` reads `args.id` — even on a field of the
|
|
525
|
+
object.** `type Record { notes: String @permission(name: "view", type:
|
|
526
|
+
"record") }` is refused at start-up: `notes` takes no `id`. Write it on the
|
|
527
|
+
type, whose default is `parent.id`, or say `id: "parent.id"`.
|
|
528
|
+
- **A `FORBIDDEN` tells the user the object exists.** Keep `NOT_FOUND`, the
|
|
529
|
+
default, on anything reached by an id the client chose; use
|
|
530
|
+
`onDeny: FORBIDDEN` on a field of an object the user may already see.
|
|
531
|
+
- **The parent must carry the fields its `fromField`s read.** A type-level
|
|
532
|
+
`@permission` checks the parent itself, so a resolver answering
|
|
533
|
+
`{ id, title }` for a record whose `doctors` read `doctorId` denies every
|
|
534
|
+
doctor. Answer the field, or read the id from `args` with a loader.
|
|
535
|
+
- **A loader's own error is a 500.** `@permission` answers a `JanusError`
|
|
536
|
+
with its status, but a driver's error thrown by a loader is masked like any
|
|
537
|
+
other: throw `StoreFailure` for an outage, so it is a 503.
|
|
538
|
+
- **A request remembers its checks.** The same object, permission and user
|
|
539
|
+
asked twice in one request is one check — so a mutation that grants or
|
|
540
|
+
revokes, then asks again in the same request, reads the answer from
|
|
541
|
+
before the change. Call `access.can` directly there. In a subscription,
|
|
542
|
+
`@permission` asks afresh on every event; `can(ctx, …)` in its resolver
|
|
543
|
+
reads the memo — call `ctx.janus.access.can` there.
|
|
544
|
+
- **`@permission` is not a filter.** A list of ids requires the permission
|
|
545
|
+
on every one, and one denial denies the field; to answer only the items a
|
|
546
|
+
user may see, ask `access.list()` for their ids.
|
|
547
|
+
- **A context built without a request cannot authenticate.** `ctx.janus.user()`
|
|
548
|
+
rejects with a `TypeError` — a transport that is not HTTP, or a graphql-ws
|
|
549
|
+
operation whose connection no `janusConnection().onConnect` accepted, or
|
|
550
|
+
whose context was built without Yoga's `...ctx` spread, which carries
|
|
551
|
+
`ctx.extra`.
|
|
552
|
+
- **A session revoked while a socket is open keeps its running streams.**
|
|
553
|
+
An operation authenticates once, when it subscribes, and each event's
|
|
554
|
+
`@authenticated` reads that answer; the next subscribe, and a
|
|
555
|
+
reconnection, are refused. Close the
|
|
556
|
+
socket yourself to cut it at once. `@permission` sees a `revoke()` at the
|
|
557
|
+
next event.
|
|
558
|
+
- **Bun's graphql-ws `extra` holds no request.** Without
|
|
559
|
+
`janusConnection({ upgrade })`, a browser's cookie is never read there,
|
|
560
|
+
and only `connectionParams` authenticates.
|
|
561
|
+
- **`invitationPreview` and `acceptInvitation` are not throttled.** They are
|
|
562
|
+
open to whoever holds a code, and the library limits nothing: throttle them
|
|
563
|
+
in front of GraphQL (a rate limit by IP on the operation). Send the code in
|
|
564
|
+
the variables of a POST, never in a GET's URL, which proxies log.
|
|
565
|
+
- **`authorize` is the only guard of the owner fields.** The core authorises
|
|
566
|
+
nobody: a user who is signed in and passes `authorize` may invite into the
|
|
567
|
+
scope. `false` answers `NOT_FOUND`, so a scope's existence is not revealed.
|
|
568
|
+
- **A failed `sendInvitation` leaves the invitation pending.** Its error goes
|
|
569
|
+
up to the client; the invitation exists and counts against `maxPending`.
|
|
570
|
+
`resendInvitation` makes a new code and calls the hook again.
|
|
571
|
+
- **`totalCount` belongs to the page `invitations` returns.** It counts with
|
|
572
|
+
the scope and filters that resolver carried, so a `JanusInvitationPage` of
|
|
573
|
+
your own fails with `totalCount is answered only on pages \`invitations\` returns`.
|
|
574
|
+
- **Bound API key pages read the key history on a store without `listUserBoundApiKeys`.**
|
|
575
|
+
The core then reads the user's keys 100 at a time until a page fills; the
|
|
576
|
+
Mongo, Drizzle and memory stores have it. `revokeApiKey` reads the key once
|
|
577
|
+
before and once after.
|
|
578
|
+
- **`lifetimes.days` must match `janus({ apiKeys: { lifetimes } })`.** A day
|
|
579
|
+
count offered here but not configured there is refused by the core on
|
|
580
|
+
create, `API_KEY_INVALID` with `extensions.field: "lifetimeDays"`.
|
|
581
|
+
- **`InvitationSignIn` means not signed in.** An invitation proves an inbox,
|
|
582
|
+
not who holds an existing account: the invitee is sent to the sign-in page.
|
|
583
|
+
Nothing of that user (not their id) is answered to an anonymous caller.
|
|
584
|
+
- **Accepting while signed in as somebody else replaces the session cookie**
|
|
585
|
+
of a new invitee's accept: the response sets the invitee's cookie over it.
|
|
586
|
+
- **`@fresh` reads seconds; `requireFresh()` a duration.** `@fresh(maxAge:
|
|
587
|
+
10)` is ten seconds, not ten minutes — write `600`. `requireFresh(ctx,
|
|
588
|
+
'10m')` takes the unit, and refuses a bare number, which `@softistx/janus`
|
|
589
|
+
would read as milliseconds.
|
|
590
|
+
- **`useJanus()` reads the system clock unless given `janus()`'s.** With
|
|
591
|
+
`janus({ clock: fixedClock(…) })` in a spec and no `useJanus({ clock })`,
|
|
592
|
+
every session looks as old as the fixed date, and every `@fresh` field
|
|
593
|
+
answers `STEP_UP_REQUIRED`. Pass the same clock to both.
|
|
594
|
+
- **A subscription field's `@fresh` is checked when it subscribes.** Its
|
|
595
|
+
events keep coming past `maxAge`; that `@fresh` is not asked again on
|
|
596
|
+
each one, as `@permission` is. A `@fresh` on the payload's type or its
|
|
597
|
+
fields is asked on every event, like any field.
|
|
598
|
+
- **An avatar's `url` must point at a route that checks the session and the
|
|
599
|
+
access rule.** A public bucket URL or a signed one needs no session and
|
|
600
|
+
outlives the membership that allowed it. `@permission` on the field decides
|
|
601
|
+
who learns the URL; only the route decides who gets the bytes.
|
|
602
|
+
- **`socialResolvers()` returns `Query` and `Mutation` keys.** Spreading it
|
|
603
|
+
beside resolvers of your own with the same keys replaces one with the other;
|
|
604
|
+
merge the maps. The flow `socialSignInStart` answers is a secret: keep it in
|
|
605
|
+
an `HttpOnly` cookie of the BFF, never in a URL, and forward the
|
|
606
|
+
`Set-Cookie` of `socialSignInComplete`'s response.
|
|
607
|
+
- **`passkeyRegistrationOptions` is a query that writes.** It makes and stores
|
|
608
|
+
a challenge each time, so a client or a cache that replays queries makes
|
|
609
|
+
several; ask it once per registration. The response says
|
|
610
|
+
`cache-control: no-store` by itself (through `useJanus()`'s `onResponse`).
|
|
611
|
+
The challenge is spent by `registerPasskey` even when the response does not
|
|
612
|
+
verify (`PASSKEY_INVALID`): ask for new options.
|
|
613
|
+
- **`registerPasskey` and `removePasskey` carry no `@fresh`.** The core refuses
|
|
614
|
+
a stale session itself (`STEP_UP_REQUIRED`, `passkeys.freshWithin`); do not
|
|
615
|
+
add a `@fresh` of another window, it would never be the looser of the two.
|
|
616
|
+
- **`confirmSecondFactorPasskey` has no `@authenticated`**: the visitor has not
|
|
617
|
+
signed in yet. Its protection is the challenge and its five attempts, shared
|
|
618
|
+
with the TOTP code. `SecondFactorRequired.passkeyOptions` names the user's
|
|
619
|
+
credential ids: answer it only to a visitor who proved the first factor.
|
|
620
|
+
- **`passkeySignInOptions` and `passkeySignIn` have no `@authenticated`**:
|
|
621
|
+
they open the session. `passkeySignInOptions` is a query that writes (one
|
|
622
|
+
short-lived token per call, `Cache-Control: no-store`): **rate-limit it**
|
|
623
|
+
where requests enter. `passkeySignIn` allows one attempt per challenge; a
|
|
624
|
+
refusal is `CREDENTIALS_INVALID`, 401, and the visitor asks for new options.
|
|
625
|
+
- **`confirmSecondFactor` and `recoverSecondFactor` have no `@authenticated`**:
|
|
626
|
+
the visitor has not signed in yet. Their protection is the challenge and
|
|
627
|
+
its five attempts. Answer a `JanusSecondFactorChallenge` only to a visitor
|
|
628
|
+
who proved the first factor, and keep it out of URLs and logs.
|
|
629
|
+
- **`enrollSecondFactor` answers the secret once.** Send the response with
|
|
630
|
+
`cache-control: no-store`; no call answers it again. The core asks for no
|
|
631
|
+
fresh session before `enrollSecondFactor`, `activateSecondFactor`,
|
|
632
|
+
`regenerateRecoveryCodes` or `disableSecondFactor`: that is your
|
|
633
|
+
`freshWithin`, not a default.
|
|
634
|
+
- **The writes need a session, not an API key.** Under `useJanus({ apiKey: true })`
|
|
635
|
+
a key authenticates as its owner, so `enrollSecondFactor`,
|
|
636
|
+
`activateSecondFactor`, `regenerateRecoveryCodes`, `disableSecondFactor`,
|
|
637
|
+
`requestStepUp` and `confirmStepUp` answer `UNAUTHENTICATED` to a key.
|
|
638
|
+
- **The answers that carry a secret say `Cache-Control: no-store`**:
|
|
639
|
+
`enrollSecondFactor`, `activateSecondFactor`, `regenerateRecoveryCodes`,
|
|
640
|
+
every sign-in that answers the session token with `answerToken`
|
|
641
|
+
(`confirmSecondFactor`, `recoverSecondFactor`, `confirmSecondFactorPasskey`,
|
|
642
|
+
`socialSignInComplete`), and every answer that carries a single-use
|
|
643
|
+
challenge or flow: `socialSignInStart` and `linkSocial` (`flow`),
|
|
644
|
+
`SocialSecondFactor` (`challenge`), `passkeyRegistrationOptions`
|
|
645
|
+
(`challenge`), `requestStepUp` (`challenge`), and `JanusSecondFactorChallenge`
|
|
646
|
+
when your sign-in resolver passes the request:
|
|
647
|
+
`secondFactorChallengeOut(result, ctx.request)`. See the
|
|
648
|
+
[passkeys](docs/guide/passkeys.md), [second-factor](docs/guide/second-factor.md)
|
|
649
|
+
and [social](docs/guide/social.md) guides. The header goes through
|
|
650
|
+
`useJanus()`'s `onResponse`: over HTTP through Yoga only, not graphql-ws nor
|
|
651
|
+
an envelop-only server (a context with no request answers without it); see
|
|
652
|
+
[the troubleshooting entry](docs/troubleshooting.md#a-response-that-answers-a-challenge-or-a-flow-is-cached).
|
|
653
|
+
- **`disableSecondFactor` checks its code through a step-up**, so a user type
|
|
654
|
+
with no e-mail (it has no `stepUp`) cannot use it, nor `requestStepUp` or
|
|
655
|
+
`confirmStepUp`: each throws a `TypeError` naming itself. Disabling the
|
|
656
|
+
factor also removes every passkey of the user (the core's rule: a passkey
|
|
657
|
+
is a second factor beside TOTP, never instead of it).
|
|
658
|
+
- **A denial of a list field's item fails the whole list** where the item is
|
|
659
|
+
non-null (`[Doctor!]!`), as GraphQL's null propagation always does. Guard
|
|
660
|
+
the list field, or make the item nullable.
|
|
661
|
+
|
|
662
|
+
## Documentation
|
|
663
|
+
|
|
664
|
+
- [Guides](docs/README.md) — the directives, account avatars, social sign-in, passkeys, the TOTP second factor, invitations, API keys, the step-up over GraphQL, subscriptions over graphql-ws, the context and the lazy user, errors as statuses, telemetry, and federation
|
|
665
|
+
- [Troubleshooting](docs/troubleshooting.md) — by the message or status you see
|
|
666
|
+
- [Roadmap](docs/roadmap.md) — what is next, and what is not planned
|
|
667
|
+
|
|
668
|
+
## Type safety, counted
|
|
669
|
+
|
|
670
|
+
Eighty-six plausible mistakes are refused by the compiler, each with a
|
|
671
|
+
`@ts-expect-error` case in `test/types/`:
|
|
672
|
+
|
|
673
|
+
- seven in `context.ts`: reading the user or the session where either may be
|
|
674
|
+
`null` (twice), a field of another user type once `JanusContext` is narrowed,
|
|
675
|
+
`ctx.janus.access` where `useJanus()` was given none, and a context narrowed
|
|
676
|
+
to a user type the instance does not know, and `principal()` and `apiKey()`
|
|
677
|
+
read where `useJanus({ apiKey: true })` was not given;
|
|
678
|
+
- nine in `helpers.ts`: `requireUser()` — a field of another user type once
|
|
679
|
+
narrowed, a user type the instance does not know, an empty list of user
|
|
680
|
+
types — and `can()` — a
|
|
681
|
+
permission the object's type does not declare, an object type the model
|
|
682
|
+
does not, an object without a field a `fromField` reads, a condition reached
|
|
683
|
+
with no `ctx`, a `ctx` of the wrong shape, and a context with no `access`;
|
|
684
|
+
- nine in `plugin.ts`: `useJanus()` given a user type the instance does not
|
|
685
|
+
know, something that is not what `janus()` answered (or a function), a
|
|
686
|
+
`types` entry the function's instance does not know, the `permissions()`
|
|
687
|
+
instance as `auth`, `applyJanusDirectives()` without `auth` or narrowed
|
|
688
|
+
to a user type the instance does not know, and `janusMaskError()` given a
|
|
689
|
+
misspelled `report` or one reading what a `JanusError` does not carry;
|
|
690
|
+
- five in `wiring.ts`: `useJanus()`'s `loaders` for an object type the model
|
|
691
|
+
does not declare, a loader answering an object without a field a
|
|
692
|
+
`fromField` reads, `conditions` for a type no `when()` is reached on, a
|
|
693
|
+
condition answering a `ctx` of the wrong shape, and `loaders` without
|
|
694
|
+
`access`;
|
|
695
|
+
- five in `fresh.ts`: `requireFresh()` given a bare number, a duration
|
|
696
|
+
written as prose, no `maxAge` at all, or the request instead of the
|
|
697
|
+
context, and `useJanus()` given a timestamp as its `clock`;
|
|
698
|
+
- six in `connection.ts`: `janusConnection()` given a user type the
|
|
699
|
+
instance does not know, the `permissions()` instance as `auth`, or a
|
|
700
|
+
timestamp as its `clock`; `ctx.janus.access` from a connection given no
|
|
701
|
+
`access`, a field of another user type once narrowed, and an `upgrade`
|
|
702
|
+
answering a token rather than a request;
|
|
703
|
+
- four in `avatar.ts`: `avatarResolvers()` given no `url`, a `url` answering a
|
|
704
|
+
number or a promise, and `toJanusAvatar()` given an object with no `avatar`;
|
|
705
|
+
- five in `social.ts`: `socialResolvers()` given an instance whose user types configure no `social`, given no `auth`, given an `auth` that is a string, and given an `auth` function that answers an instance with no `social` or something else than an instance;
|
|
706
|
+
- nine in `passkeys.ts`: the sign-in fields read without a guard where `firstFactor: true` was not given (twice), `firstFactor: true` on an instance whose `passkeys` has no `firstFactor: true`, an `auth` function that answers something else than an instance, `passkeyResolvers()` given an instance whose `janus()` has no `passkeys`, given no `auth`, given a `device` of the wrong shape, given an instance with several user types and no `type`, and given a `type` the instance does not know. The `type` of a single-type instance only limits the fields, so it is allowed.
|
|
707
|
+
- seven in `second-factor.ts`: `secondFactorResolvers()` given an instance whose `janus()` has no `secondFactor`, a `freshWithin` as a bare number or as prose, an instance with several user types and no `type`, a `type` the instance does not know, a `device` of the wrong shape, and `secondFactorViewerFields()` given an instance with no `secondFactor`.
|
|
708
|
+
- eleven in `invitations.ts`: `invitationResolvers()` given an instance whose `janus()` has no `invitations`, given no `auth`, given no `authorize`, given a `device` of the wrong shape, an `authorize` that answers for an action that does not exist, an `inviterType` the instance has no user of, and `authorize`'s `subject` read without its optional checks (`invitation.invitedBy`), with `page.limit` as a string, with `input.role` compared as a number, with `page.order` compared to the SDL's `'NEWEST'`, and a hook whose `ctx` is typed as something that is not a context.
|
|
709
|
+
- nine in `api-keys.ts`: `apiKeysResolvers()` given an instance whose `janus()` has no `apiKeys`, given no `auth`, given no `authorize`, given an `authorize` without `revoke`, given `lifetimes.days` empty, a hook that answers a string, a `bound` that answers an id instead of `{ type, id }`, and the `revoke` hook's `subject.key` read without its check, and the `list` hook's `page.limit` compared to a string.
|
|
710
|
+
|
|
711
|
+
`plugin.ts` also holds this README's quick start, and `connection.ts` the
|
|
712
|
+
graphql-ws wiring — Yoga's recipe, without Yoga, and Bun's `upgrade` —
|
|
713
|
+
against graphql-ws's own types; both must keep compiling.
|
|
714
|
+
|
|
715
|
+
## Licence
|
|
716
|
+
|
|
717
|
+
MIT
|