@softistx/janus-graphql
v0.38.13
Published
GraphQL for @softistx/janus: an envelop plugin (and a graxia one) with the signed-in user on the context, fields guarded by @authenticated, @fresh and @permission, and every error with the status it deserves
Maintainers
Readme
@softistx/janus-graphql
@softistx/janus in a GraphQL
server: the signed-in user on the context, authenticated only when a field
asks, fields and types guarded by @authenticated, @fresh and
@permission, the
same guards on subscriptions over graphql-ws, and every error answered with
the status it deserves — an outage as 503, never as 401, 403 or 404.
An envelop plugin, so it runs in
GraphQL Yoga and any server built
on envelop — and, from @softistx/janus-graphql/graxia, a plugin and an error
masker for a graxia server.
import { janusMaskError, janusTypeDefs, type JanusContext, useJanus } from '@softistx/janus-graphql';
import { createSchema, createYoga, type YogaInitialContext } from 'graphql-yoga';
import { access } from './access'; // what permissions() answered
import { auth } from './auth'; // what janus() answered
type Context = YogaInitialContext & JanusContext<typeof auth, typeof access>;
const typeDefs = /* GraphQL */ `
type Query {
me: User @authenticated
ward(id: ID!): Ward @permission(name: "enter", type: "ward")
}
type User { id: ID!, email: String }
type Ward { id: ID!, name: String, roster: [String!] @authenticated(type: ["staff"]) }
`;
export const yoga = createYoga({
schema: createSchema({
typeDefs: [janusTypeDefs, typeDefs],
resolvers: {
Query: {
me: async (_: unknown, __: unknown, ctx: Context) => ctx.janus.user(), // never null here
ward: (_: unknown, { id }: { id: string }) => wards.find(id), // only for a user who may enter it
},
},
}),
plugins: [useJanus({ auth, access })],
maskedErrors: { maskError: janusMaskError() }, // STORE_FAILED → 503, not "Unexpected error."
});0.x. A minor version may still change the surface; the changelog says how.
Install
Public on npmjs:
bun add @softistx/janus-graphql @softistx/janus graphql @graphql-tools/utils @envelop/core
bun add -d typescript # 6 or 7Every peer is required but graphql-ws and @softistx/graxia:
| Peer | Range | Why |
| --- | --- | --- |
| @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 |
| graphql | ^16.9.0 \|\| ^17.0.0 | The schema and GraphQLError are yours; a second copy of graphql fails every schema |
| @graphql-tools/utils | >=10.0.0 <14 | mapSchema and getDirective, which apply the directives |
| @envelop/core | ^5.0.0 \|\| ^6.0.0 | Types only — the Plugin useJanus() answers. Yoga already brings it |
| typescript | ^6.0.3 \|\| ^7.0.0 | As for @softistx/janus |
| @softistx/graxia | ^0.15.0 || ^0.16.0 || ^0.17.0 || ^0.18.0 || ^0.19.0 || ^0.20.0, optional | Only for the /graxia entry point (janusGraxia() imports its definePlugin); it needs graphql ^17.1.0. bun add @softistx/graxia |
| 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 |
The floors are tested, not claimed: the package's specs and its typecheck run
on graphql 16.9.0, @graphql-tools/utils 10.0.0, @envelop/core 5.0.0
and graphql-ws 6.0.0 as well, together, with a single copy of graphql,
in the Floors job, on every CI run.
Like @softistx/janus, it expects "moduleResolution": "bundler": the
declarations import without extensions, so nodenext is not supported.
The SDL ships twice: janusTypeDefs, a string for createSchema, and
graphql/janus.graphqls in the package, for a code generator or an editor
that reads files — node_modules/@softistx/janus-graphql/graphql/janus.graphqls.
API
| Export | What it is |
| --- | --- |
| 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); 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. apiKey: 'service' does the same and also accepts an object's service key (janus({ apiKeys: { service } })): principal() may answer via: 'serviceKey' (user() is null, the owner is bound), @fresh refuses it too. Under Yoga, a session authenticate renewed is sent again as Set-Cookie on the response, to a request that presented it as the cookie |
| janusGraxia({ …, mapCode? }), JanusGraxiaOptions, MapCode, MappedCode, guardGraxiaSchema(schema, options), janusGraxiaMaskError({ report?, fallback?, mapCode? }) | From @softistx/janus-graphql/graxia, for @softistx/graxia: the plugin (ctx.janus in onContext, the renewed Set-Cookie in onResponse, mapCode on the errors of every result, each subscription event included), the schema transform that applies the directives, and the maskError with janusMaskError()'s behaviour. See graxia |
| 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 |
| 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 |
| ctx.janus.access | The permissions() instance given to useJanus(). Absent from the type — and from the context — without one |
| 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 |
| @authenticated(type: [String!]) | On a field, a type or an interface. A signed-in user, of one of the types when it names some. Anonymous: UNAUTHENTICATED. Another type: FORBIDDEN. Every one that applies — the field's, its type's, its interfaces' — must hold |
| @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. A service key (apiKey: 'service'): FORBIDDEN, 403, extensions.reason: "serviceKey". Checked after @authenticated, before @permission; the smallest maxAge that applies holds; on a subscription field, checked when it subscribes |
| @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 |
| 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 |
| conditions: { [type]: (object, ctx) => ctx } | The ctx @permission passes to access.can for a permission that reaches a when() |
| 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 |
| requireUser(ctx, { type? }) | The signed-in user, narrowed to type — one or a non-empty list — or a denial: UNAUTHENTICATED, FORBIDDEN |
| 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 |
| 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 |
| 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 |
| 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 |
| 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 |
| 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 |
| janusSocialTypeDefs | Opt-in SDL (graphql/janus-social.graphqls): socialSignInStart, socialSignInComplete, linkSocial, unlinkSocial and socialLinks, with SocialFlowStart, JanusSocialLink and the result union SocialSignInResult. It extends Query and Mutation and needs janusTypeDefs |
| socialResolvers({ auth, type?, answerToken?, bindCallback? }) | 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. bindCallback(callback, { args, ctx }) binds the callback to the connection whose URL received it (connections.callback(id, callback) of @softistx/janus-social), which a connection with a per-connection redirectUri requires: guide. A refusal carries returnTo and flowSpent in extensions; PROVIDER_ERROR is 502 |
| 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 Strings. It extends Query and Mutation and needs janusTypeDefs |
| 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 extends Query and Mutation and needs janusTypeDefs and janusPasskeyTypeDefs |
| passkeyResolvers({ auth, type?, firstFactor?, answerToken?, device?, signInGuard? }) | 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; signInGuard(user, ctx) runs on passkeySignIn before the session and its cookie exist and throws to refuse (a thrown GraphQLError is answered as it is; it needs firstFactor: true, else a TypeError at wiring). 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 |
| 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 Strings. It extends Query and Mutation and needs janusTypeDefs |
| 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), and answer method (totp or recovery) to tell the two apart (confirmSecondFactorPasskey answers passkey; PasskeySignedIn.method is null after passkeySignIn); 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 |
| secondFactorViewerFields(options) | The two fields — secondFactor { enabled recoveryCodesLeft } and sessionConfirmedUntil — for your own Viewer type: resolvers: { Viewer: secondFactorViewerFields({ auth }) } |
| 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 |
| 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 Strings; 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 extends Query and Mutation and needs janusTypeDefs |
| 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 |
| 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 extends Query and Mutation and needs janusTypeDefs |
| 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 |
| ApiKeysResolversOptions, ApiKeysAuth, ApiKeysAuthorize, ApiKeyLifetimes, ApiKeySubjectBase, ApiKeyCreateSubject, ApiKeyListSubject, ApiKeyRevokeSubject, ApiKeysResolvers | The types of the API key resolvers |
| 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 |
| janusErrorOf(error) | The JanusError behind a resolver's error (itself, or under a chain of GraphQLErrors' originalError), or undefined: map a refusal (INVITATION_NOT_PENDING, NOT_FOUND…) per operation |
| janusGraphQLError(error) | A JanusError as the GraphQLError the client reads: its code, its status, and only what the client can act on |
| 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 |
| 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 |
| JanusContext<typeof auth, typeof access?, Type?, ApiKey?> | What useJanus() adds to the context, for your resolvers' ctx |
| deviceOf(request, options?) and sendDevice(request, deviceToken, options?) | The device cookie of a sign-in mutation (guide), 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). |
| 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 |
graxia
A server on @softistx/graxia (what
@alxia/graphql 0.17 serves GraphQL with) uses the /graxia entry point,
beside the Yoga one. @softistx/graxia ^0.15.0 || ^0.16.0 || ^0.17.0 || ^0.18.0 || ^0.19.0 || ^0.20.0 is an optional peer.
import { createGraxia, createSchema } from '@softistx/graxia';
import { janusTypeDefs } from '@softistx/janus-graphql';
import { guardGraxiaSchema, janusGraxia, janusGraxiaMaskError } from '@softistx/janus-graphql/graxia';
const options = { auth, access }; // what useJanus() takes
export const graxia = createGraxia({
schema: guardGraxiaSchema(createSchema()({ typeDefs: [janusTypeDefs, typeDefs], resolvers }), options),
plugins: [janusGraxia(options)],
maskError: janusGraxiaMaskError(),
});ctx.janus, the directives, the denials and the renewed session cookie behave
as under Yoga; a schema using the directives that was not guarded refuses to
start. Pass the same mapCode to janusGraxia() and janusGraxiaMaskError(): the
plugin answers your own codes on the exposed errors of every result, each
subscription event included, the masker on the masked ones. See the graxia guide.
Directives
type Query {
me: User @authenticated # any signed-in user
record(id: ID!): Record @permission(name: "view", type: "record") # args.id
records(ids: [ID!]!): [Record!]!
@permission(name: "view", type: "record", id: "args.ids") # every id
}
type Record @permission(name: "view", type: "record") { # parent.id: the record itself
title: String
billing: Billing @permission(name: "manage", type: "record", onDeny: FORBIDDEN)
}
type Mutation {
changeEmail(email: String!): User @fresh(maxAge: 600) # signed in or stepped up < 10 min ago
}useJanus({
auth,
access,
loaders: { record: (id, ctx) => records.find(id) }, // record has a fromField: an id alone is not enough
conditions: { record: (record, ctx: Context) => ({ onShift: ctx.shift.open }) }, // the ctx of a when() record's permissions reach
});Each runs before the resolver, which a refused request never reaches.
@fresh(maxAge) takes seconds, and answers an older session
STEP_UP_REQUIRED: the client then calls your two step-up mutations,
which run auth.stepUp.request and confirm — shown in
the step-up guide — and sends the request again.
Every @authenticated is checked first, then @fresh, then each
@permission, so a stale session asks no permission check.
@permission implies a signed-in user, and asks access.can with the parent
itself when the id is parent.id, with what loaders[type] answers for an
id of a type with a fromField, and with { type, id } otherwise. Every
directive that applies must hold — the field's, its type's, its
interfaces' — asked outermost first, so a type's NOT_FOUND answers before
a field's FORBIDDEN could tell the object exists. The same question asked
twice in a request, by two fields or by a directive and can(), is one
check. What no request could pass — an object type or a permission the
model does not declare, a malformed id:, an argument the field does not
take, a missing loader or condition, a maxAge not above zero — is a
TypeError at start-up naming the field. Detail: the directives guide.
Avatars
type Viewer {
avatar: JanusAvatar @permission(name: "viewAvatar", type: "user", id: "parent.id")
}import {
avatarResolvers,
janusAvatarTypeDefs,
janusTypeDefs,
requireUser,
toJanusAvatar,
} from '@softistx/janus-graphql';
import { createSchema } from 'graphql-yoga';
const typeDefs = /* GraphQL */ `
type Viewer {
avatar: JanusAvatar @permission(name: "viewAvatar", type: "user", id: "parent.id")
}
type Query {
viewer: Viewer @authenticated
}
`;
createSchema({
typeDefs: [janusTypeDefs, janusAvatarTypeDefs, typeDefs],
resolvers: {
...avatarResolvers({ url: ({ userId, id }, size) => `/avatars/${userId}/${size}?v=${encodeURIComponent(id)}` }),
Query: { viewer: (_, __, ctx) => requireUser(ctx) },
Viewer: { avatar: (user) => toJanusAvatar(user) },
},
});url(size:) is the path of your own route, which checks the session and
the access rule before it streams the image; janus keeps only the avatar's id.
Detail: the avatars guide.
One server, several issuers
auth may be a function of the request's context instead of one instance,
so a single Yoga server serves several janus() instances — each with its
own stores, cookie and user types — and picks the one per request:
const issuers = { 'a.example': authA, 'b.example': authB };
useJanus({
// ctx.request over HTTP; null (or a throw) refuses the request
auth: (ctx) => issuers[new URL(ctx.request?.url ?? 'http://x').host],
types: ['patient', 'staff'], // the user types the directives may name
});
janusConnection({
// graphql-ws: the connection's ctx — read the upgrade request in ctx.extra.request
auth: (ctx) => issuers[hostOf(ctx)], // hostOf: your own reading of the upgrade request, ctx.extra.request on ws
});The function may be async. It runs once per request, the first time
ctx.janus.user() or session() asks, so a query that reads neither never
calls it. A session of one issuer is not seen through another: each
instance authenticates against its own store. A plain instance works as
before. The details are in the context guide.
Social sign-in
Opt-in, beside the avatar type. The BFF keeps the flow in its own cookie:
import { janusSocialTypeDefs, janusTypeDefs, socialResolvers } from '@softistx/janus-graphql';
import { createSchema } from 'graphql-yoga';
createSchema({
typeDefs: [janusTypeDefs, janusSocialTypeDefs, typeDefs], // typeDefs declares Query and Mutation
resolvers: { ...socialResolvers({ auth }), SocialSignedIn: { user: (signedIn: { user: unknown }) => signedIn.user } },
});
// mutation { socialSignInStart(provider: "google", returnTo: "/home") { url flow expiresAt } }
// mutation { socialSignInComplete(callbackUrl: "https://app/cb?code=…&state=…", flow: "…") { … } }A BFF that keeps the session in its own cookie and forwards it as
Authorization: Bearer passes socialResolvers({ auth, answerToken: true }):
SocialSignedIn.token then answers the session token, with Cache-Control: no-store, and no cookie is set.
linkSocial and unlinkSocial are @authenticated @fresh(maxAge: 600). Detail:
the social guide.
Passkeys
Opt-in, for users who hold passkeys as a second factor (janus({ passkeys })):
import { janusPasskeyTypeDefs, janusTypeDefs, passkeyResolvers } from '@softistx/janus-graphql';
createSchema({
typeDefs: [janusTypeDefs, janusPasskeyTypeDefs, typeDefs], // typeDefs declares Query and Mutation
resolvers: { ...passkeyResolvers({ auth }), PasskeySignedIn: { user: (signedIn: { user: unknown }) => signedIn.user } },
});
// { passkeyRegistrationOptions { options challenge expiresAt } }
// mutation { registerPasskey(challenge: "…", response: "<JSON>", name: "Laptop") { credentialId } }
// mutation { confirmSecondFactorPasskey(challenge: "…", assertion: "<JSON>") { userId expiresAt } }The browser's JSON travels as strings. Detail: the passkeys guide.
Passkey as the first factor
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:
createSchema({
typeDefs: [janusTypeDefs, janusPasskeyTypeDefs, janusPasskeySignInTypeDefs, typeDefs],
resolvers: { ...passkeyResolvers({ auth, firstFactor: true }), PasskeySignedIn: { user: (signedIn: { user: unknown }) => signedIn.user } },
});
// { passkeySignInOptions { options challenge expiresAt } }
// mutation { passkeySignIn(challenge: "…", assertion: "<JSON>") { userId expiresAt newDevice } }One auth instance per request
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:
const authFor = (ctx: { host: string }) => instances.get(ctx.host); // null: UNAUTHENTICATED
passkeyResolvers({ auth: authFor, firstFactor: true });
useJanus({ auth: authFor, types: ['user'] });Second factor (TOTP)
Opt-in, for users who may hold an authenticator app (janus({ secondFactor })):
import {
janusSecondFactorTypeDefs,
janusTypeDefs,
secondFactorResolvers,
secondFactorViewerFields,
} from '@softistx/janus-graphql';
const options = { auth, freshWithin: '10m' } as const; // your policy: the freshness window
createSchema({
typeDefs: [janusTypeDefs, janusSecondFactorTypeDefs, typeDefs], // typeDefs declares Query, Mutation and Viewer
resolvers: {
...secondFactorResolvers(options),
Viewer: secondFactorViewerFields(options), // Viewer.secondFactor, Viewer.sessionConfirmedUntil
SecondFactorSignedIn: { user: (signedIn: { user: unknown }) => signedIn.user },
},
});
// mutation { enrollSecondFactor { secret uri } }
// mutation { activateSecondFactor(code: "123456") { recoveryCodes } }
// mutation { confirmSecondFactor(challenge: "…", code: "654321") { userId expiresAt } }Detail, with the sign-in and the step-up: the second-factor guide.
Invitations
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:
import { invitationResolvers, janusInvitationTypeDefs, janusTypeDefs, can } from '@softistx/janus-graphql';
createSchema({
typeDefs: [janusTypeDefs, janusInvitationTypeDefs, typeDefs], // typeDefs declares Query and Mutation
resolvers: {
...invitationResolvers({
auth,
authorize: (action, { scope }, ctx: Context) => can(ctx, 'invite', { type: 'organization', id: scope }), // the hooks are methods: type `ctx` as your context
sendInvitation: ({ invitation, code }) => mailer.sendInvitation(invitation, `https://app.test/join#${code}`),
}),
},
});
// mutation { issueInvitation(scope: "acme", email: "[email protected]", name: "Grace", role: "member") { invitation { id status } } }
// mutation { issueInvitation(scope: "acme", email: "[email protected]", name: "Grace", role: "member", ref: "crm-1", type: "staff") { invitation { id ref type } } }
// query { invitations(scope: "acme", role: "member", ref: "crm-1", order: NEWEST, limit: 20) { items { id email ref type } nextCursor totalCount } }
// 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+
// query { invitationPreview(code: "…") { scope email name role type organization needsPassword } }
// mutation { acceptInvitation(code: "…", password: "…") { __typename … on InvitationSignedIn { userId scope role } } }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.
API keys
Opt-in, for personal API keys with janus({ apiKeys }), optionally bound to an object (a workspace). You say who may create, list and revoke:
import { apiKeysResolvers, apiKeysTypeDefs, janusTypeDefs, can } from '@softistx/janus-graphql';
// Context: YogaInitialContext & JanusContext<typeof auth, typeof access>, as in the quick start.
// The hooks are methods: type `ctx` as your context and `can(ctx, …)` reads it.
createSchema({
typeDefs: [janusTypeDefs, apiKeysTypeDefs, typeDefs], // typeDefs declares Query and Mutation
resolvers: {
...apiKeysResolvers({
auth, // janus({ …, apiKeys: { store, prefix, lifetimes: ['30d', '90d', '365d'], maxActive } })
lifetimes: { days: [30, 90, 365], default: 90 },
bound: (asked) => (asked === null ? null : { type: 'workspace', id: asked }),
authorize: {
create: ({ bound }, ctx: Context) => bound !== null && can(ctx, 'member', bound),
list: ({ bound, every }, ctx: Context) => bound !== null && can(ctx, every ? 'owner' : 'member', bound),
revoke: ({ bound, own }, ctx: Context) => own === true || (bound !== null && can(ctx, 'owner', bound)),
},
}),
},
});
// mutation { createApiKey(name: "CI", lifetimeDays: 90, scopes: ["deploy:read"], boundTo: "acme") { secret apiKey { id prefix status expiresAt } } }
// query { apiKeys(boundTo: "acme", limit: 20) { items { id name status lastUsedAt } nextCursor } }
// query { boundApiKeys(boundTo: "acme") { items { id userId name status } nextCursor } }
// mutation { revokeApiKey(id: "…", boundTo: "acme") { id status } }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.
Subscriptions over graphql-ws
Yoga's recommended graphql-ws setup, with onConnect added:
import { janusConnection } from '@softistx/janus-graphql';
import { useServer } from 'graphql-ws/use/ws';
useServer(
{
onConnect: janusConnection({ auth }).onConnect, // no valid session: closed 4403
execute: (args: any) => args.rootValue.execute(args),
subscribe: (args: any) => args.rootValue.subscribe(args),
onSubscribe: async (ctx, _id, params) => {
const { schema, execute, subscribe, contextFactory, parse, validate } =
yoga.getEnveloped({ ...ctx, req: ctx.extra.request, socket: ctx.extra.socket, params });
const args = {
schema,
operationName: params.operationName,
document: parse(params.query),
variableValues: params.variables,
contextValue: await contextFactory(), // useJanus() finds the connection by ctx.extra
rootValue: { execute, subscribe },
};
const errors = validate(args.schema, args.document);
return errors.length ? errors : args;
},
},
wsServer,
);A browser's session cookie travels on the upgrade request; any other client
sends connectionParams: { authorization: 'Bearer <token>' }, which is
read first. Each operation is authenticated again from that credential
when it subscribes: @authenticated and @fresh are checked then, and
@permission on every event. A session revoked mid-stream is refused at
the next subscribe, not at the next event. Detail, Bun, and a server
without Yoga: the subscriptions guide.
Errors
This package defines no error class. A denial is a GraphQLError, and
every one carries a code and the HTTP status Yoga answers with:
{ "errors": [{ "message": "Not signed in", "path": ["me"], "extensions": { "code": "UNAUTHENTICATED" } }] }| Code | Status | When |
| --- | --- | --- |
| UNAUTHENTICATED | 401 | An anonymous request reached a guarded field, requireUser() or requireFresh() |
| FORBIDDEN | 403 | A user of a type the directive or requireUser() does not name; a @permission(onDeny: FORBIDDEN) denied |
| STEP_UP_REQUIRED | 403 | A session older than @fresh(maxAge) or requireFresh() allows: ask for a step-up, then send the request again |
| NOT_FOUND | 404 | A @permission denied — its default — or a loader answered null; denial('NOT_FOUND') |
| SERVICE_UNAVAILABLE | 503 | A store could not answer — STORE_FAILED. Never a denial |
| 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 |
| any other JanusErrorCode | its statusOf | A JanusError a resolver let through: CREDENTIALS_INVALID 401, MAIL_THROTTLED 429, LOGIN_TAKEN 409, … |
The status sits in extensions.http.status, which Yoga reads to answer the
HTTP response and strips from the body. USER_INVALID adds issues,
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
throttled CREDENTIALS_INVALID, MAIL_THROTTLED or window-spent CODE_INVALID retryAfter — with a Retry-After header in
extensions.http.headers, which Yoga answers with; nothing
else — never any other reason, nor login, a hash prefix or a cause. The message is a
fixed one per status, never the core's: read code. Detail, and the status of a
response with several errors: the errors guide.
The message carries nothing of the store's, and a directive answers an
outage itself, before any resolver of yours could log it. report sees
every JanusError answered 5xx, once, whichever path it took:
createYoga({
schema,
plugins: [useJanus({ auth, access })],
maskedErrors: {
maskError: janusMaskError({
report: (error) => logger.error({ code: error.code, cause: error.cause }), // slot, operation: which call failed
}),
},
});Traps
janusGraxiaMaskError({ mapCode })alone never reaches a denial or an already-coded error. graxia givesmaskErroronly the errors it masks; passmapCodetojanusGraxia()too (guide).magicLink: { enabled: false }reaches the client asextensions.code: "MAGIC_LINK_DISABLED", status 404. The error mapping follows the core'sstatusOf; this package defines no magic-link field. Exposeauth.magicLink.enabledyourself (aBooleanfield) to hide the button.- Versions up to 0.30.0 treat the optional peers as required. Their package document lacks
peerDependenciesMeta(details), so Bun installsgraphql-wseven when you do not use it.bun install --omit=peerskips it, but it also skips the required peers: add those back withbun add @softistx/janus @envelop/core @graphql-tools/utils graphql typescript, plusgraphql-wsonly for subscriptions. - Without
janusMaskError(), aJanusErrorfrom a resolver is Yoga's masked 500. A guarded field andrequireUser()answer an outage 503 on their own;ctx.janus.user()read directly, orauth.signInin a mutation, does not. WiremaskedErrors: { maskError: janusMaskError() }. - An
authfunction answeringnullis aTypeError, not anonymous. Return an instance, or throw the error you want the client to read; a request no issuer owns should not fall back to a default by accident. The opt-in resolvers (socialResolvers,passkeyResolvers, …) andaccessstill take one fixed instance. ctx.janus.user()isnullwhere no directive guards the field. Read it only where anonymous is a valid answer, or callrequireUser(ctx).- A type's
@authenticatedguards its fields, not the field that returns it.type Ward @authenticatedleavesQuery.wardopen: its resolver runs for an anonymous request, and the error lands onward.name. Put the directive on the field too — or callrequireUser(), as above — when the lookup itself must not run. - One refused field sets the status of the whole response. Yoga answers
the highest
extensions.http.statusamong the errors, so{ open me }from an anonymous request is a 401 whosedatastill holdsopen. A client readsdataanderrors, not only the status. - A renewed session is sent back only on an HTTP response from Yoga.
useJanus()sets it in Yoga'sonResponse, which a server on envelop alone never calls; and an operation over graphql-ws has no response at all. There,ctx.janusstill renews the session in the store, but the browser keeps the cookie with its old expiry until the next renewal over HTTP, arenewAfterlater: a browser whose only traffic is the WebSocket should renew through an HTTP route of yours. - A sign-in mutation passes the device itself.
@softistx/janus-graphqlsigns nobody in: withjanus({ devices }), callauth.signIn(input, { device: deviceOf(ctx.request) })and, when it answers adeviceToken,sendDevice(ctx.request, result.deviceToken). That goes throughuseJanus()'sonResponse, so it sets the cookie over HTTP through Yoga only; over graphql-ws the context has no request, and both helpers throw aTypeErrorsaying so. See the context. - An
authof your own needscookiefor the renewal. A wrapper that passes on onlyauthenticateandtypessends no renewed cookie; passcookie: auth.cookiealong. useJanus({ type })narrows the whole server. A user of any other type is anonymous everywhere, and a directive naming another type is refused when the schema is built.- On a field,
@permissionreadsargs.id— even on a field of the object.type Record { notes: String @permission(name: "view", type: "record") }is refused at start-up:notestakes noid. Write it on the type, whose default isparent.id, or sayid: "parent.id". - A
FORBIDDENtells the user the object exists. KeepNOT_FOUND, the default, on anything reached by an id the client chose; useonDeny: FORBIDDENon a field of an object the user may already see. - The parent must carry the fields its
fromFields read. A type-level@permissionchecks the parent itself, so a resolver answering{ id, title }for a record whosedoctorsreaddoctorIddenies every doctor. Answer the field, or read the id fromargswith a loader. - A loader's own error is a 500.
@permissionanswers aJanusErrorwith its status, but a driver's error thrown by a loader is masked like any other: throwStoreFailurefor an outage, so it is a 503. - A request remembers its checks. The same object, permission and user
asked twice in one request is one check — so a mutation that grants or
revokes, then asks again in the same request, reads the answer from
before the change. Call
access.candirectly there. In a subscription,@permissionasks afresh on every event;can(ctx, …)in its resolver reads the memo — callctx.janus.access.canthere. @permissionis not a filter. A list of ids requires the permission on every one, and one denial denies the field; to answer only the items a user may see, askaccess.list()for their ids.- A context built without a request cannot authenticate.
ctx.janus.user()rejects with aTypeError— a transport that is not HTTP, or a graphql-ws operation whose connection nojanusConnection().onConnectaccepted, or whose context was built without Yoga's...ctxspread, which carriesctx.extra. - A session revoked while a socket is open keeps its running streams.
An operation authenticates once, when it subscribes, and each event's
@authenticatedreads that answer; the next subscribe, and a reconnection, are refused. Close the socket yourself to cut it at once.@permissionsees arevoke()at the next event. - Bun's graphql-ws
extraholds no request. WithoutjanusConnection({ upgrade }), a browser's cookie is never read there, and onlyconnectionParamsauthenticates. invitationPreviewandacceptInvitationare not throttled. They are open to whoever holds a code, and the library limits nothing: throttle them in front of GraphQL (a rate limit by IP on the operation). Send the code in the variables of a POST, never in a GET's URL, which proxies log.authorizeis the only guard of the owner fields. The core authorises nobody: a user who is signed in and passesauthorizemay invite into the scope.falseanswersNOT_FOUND, so a scope's existence is not revealed.- A failed
sendInvitationleaves the invitation pending. Its error goes up to the client; the invitation exists and counts againstmaxPending.resendInvitationmakes a new code and calls the hook again. totalCountbelongs to the pageinvitationsreturns. It counts with the scope and filters that resolver carried, so aJanusInvitationPageof your own fails withtotalCount is answered only on pages \invitations` returns`.- Bound API key pages read the key history on a store without
listUserBoundApiKeys. The core then reads the user's keys 100 at a time until a page fills; the Mongo, Drizzle and memory stores have it.revokeApiKeyreads the key once before and once after. lifetimes.daysmust matchjanus({ apiKeys: { lifetimes } }). A day count offered here but not configured there is refused by the core on create,API_KEY_INVALIDwithextensions.field: "lifetimeDays".InvitationSignInmeans not signed in. An invitation proves an inbox, not who holds an existing account: the invitee is sent to the sign-in page. Nothing of that user (not their id) is answered to an anonymous caller.- Accepting while signed in as somebody else replaces the session cookie of a new invitee's accept: the response sets the invitee's cookie over it.
@freshreads seconds;requireFresh()a duration.@fresh(maxAge: 10)is ten seconds, not ten minutes — write600.requireFresh(ctx, '10m')takes the unit, and refuses a bare number, which@softistx/januswould read as milliseconds.useJanus()reads the system clock unless givenjanus()'s. Withjanus({ clock: fixedClock(…) })in a spec and nouseJanus({ clock }), every session looks as old as the fixed date, and every@freshfield answersSTEP_UP_REQUIRED. Pass the same clock to both.- A subscription field's
@freshis checked when it subscribes. Its events keep coming pastmaxAge; that@freshis not asked again on each one, as@permissionis. A@freshon the payload's type or its fields is asked on every event, like any field. - An avatar's
urlmust point at a route that checks the session and the access rule. A public bucket URL or a signed one needs no session and outlives the membership that allowed it.@permissionon the field decides who learns the URL; only the route decides who gets the bytes. socialResolvers()returnsQueryandMutationkeys. Spreading it beside resolvers of your own with the same keys replaces one with the other; merge the maps. The flowsocialSignInStartanswers is a secret: keep it in anHttpOnlycookie of the BFF, never in a URL, and forward theSet-CookieofsocialSignInComplete's response.passkeyRegistrationOptionsis a query that writes. It makes and stores a challenge each time, so a client or a cache that replays queries makes several; ask it once per registration. The response sayscache-control: no-storeby itself (throughuseJanus()'sonResponse). The challenge is spent byregisterPasskeyeven when the response does not verify (PASSKEY_INVALID): ask for new options.registerPasskeyandremovePasskeycarry no@fresh. The core refuses a stale session itself (STEP_UP_REQUIRED,passkeys.freshWithin); do not add a@freshof another window, it would never be the looser of the two.confirmSecondFactorPasskeyhas no@authenticated: the visitor has not signed in yet. Its protection is the challenge and its five attempts, shared with the TOTP code.SecondFactorRequired.passkeyOptionsnames the user's credential ids: answer it only to a visitor who proved the first factor.passkeySignInOptionsandpasskeySignInhave no@authenticated: they open the session.passkeySignInOptionsis a query that writes (one short-lived token per call,Cache-Control: no-store): rate-limit it where requests enter.passkeySignInallows one attempt per challenge; a refusal isCREDENTIALS_INVALID, 401, and the visitor asks for new options.confirmSecondFactorandrecoverSecondFactorhave no@authenticated: the visitor has not signed in yet. Their protection is the challenge and its five attempts. Answer aJanusSecondFactorChallengeonly to a visitor who proved the first factor, and keep it out of URLs and logs.enrollSecondFactoranswers the secret once. Send the response withcache-control: no-store; no call answers it again. The core asks for no fresh session beforeenrollSecondFactor,activateSecondFactor,regenerateRecoveryCodesordisableSecondFactor: that is yourfreshWithin, not a default.- The writes need a session, not an API key. Under
useJanus({ apiKey: true })a key authenticates as its owner, soenrollSecondFactor,activateSecondFactor,regenerateRecoveryCodes,disableSecondFactor,requestStepUpandconfirmStepUpanswerUNAUTHENTICATEDto a key. - The answers that carry a secret say
Cache-Control: no-store:enrollSecondFactor,activateSecondFactor,regenerateRecoveryCodes, every sign-in that answers the session token withanswerToken(confirmSecondFactor,recoverSecondFactor,confirmSecondFactorPasskey,socialSignInComplete), and every answer that carries a single-use challenge or flow:socialSignInStartandlinkSocial(flow),SocialSecondFactor(challenge),passkeyRegistrationOptions(challenge),requestStepUp(challenge), andJanusSecondFactorChallengewhen your sign-in resolver passes the request:secondFactorChallengeOut(result, ctx.request). See the passkeys, second-factor and social guides. The header goes throughuseJanus()'sonResponse: over HTTP through Yoga only, not graphql-ws nor an envelop-only server (a context with no request answers without it); see the troubleshooting entry. disableSecondFactorchecks its code through a step-up, so a user type with no e-mail (it has nostepUp) cannot use it, norrequestStepUporconfirmStepUp: each throws aTypeErrornaming itself. Disabling the factor also removes every passkey of the user (the core's rule: a passkey is a second factor beside TOTP, never instead of it).- A denial of a list field's item fails the whole list where the item is
non-null (
[Doctor!]!), as GraphQL's null propagation always does. Guard the list field, or make the item nullable. - A service key never passes a user guard. Under
useJanus({ apiKey: 'service' }),@authenticated,@freshand@permissionanswer a service keyFORBIDDEN(403,extensions.reason: "serviceKey"): it has no user, andUNAUTHENTICATEDwould send a client to sign in again. Readctx.janus.principal()in its resolvers.useJanus({ type, apiKey: 'service' })leaves service keys anonymous, sincetypenarrows the server to users of that type.
Documentation
- Guides — the directives, graxia, 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
- Troubleshooting — by the message or status you see
- Roadmap — what is next, and what is not planned
Type safety, counted
Eighty-eight plausible mistakes are refused by the compiler, each with a
@ts-expect-error case in test/types/:
- seven in
context.ts: reading the user or the session where either may benull(twice), a field of another user type onceJanusContextis narrowed,ctx.janus.accesswhereuseJanus()was given none, and a context narrowed to a user type the instance does not know, andprincipal()andapiKey()read whereuseJanus({ apiKey: true })was not given; - nine in
helpers.ts:requireUser()— a field of another user type once narrowed, a user type the instance does not know, an empty list of user types — andcan()— a permission the object's type does not declare, an object type the model does not, an object without a field afromFieldreads, a condition reached with noctx, actxof the wrong shape, and a context with noaccess; - nine in
plugin.ts:useJanus()given a user type the instance does not know, something that is not whatjanus()answered (or a function), atypesentry the function's instance does not know, thepermissions()instance asauth,applyJanusDirectives()withoutauthor narrowed to a user type the instance does not know, andjanusMaskError()given a misspelledreportor one reading what aJanusErrordoes not carry; - five in
wiring.ts:useJanus()'sloadersfor an object type the model does not declare, a loader answering an object without a field afromFieldreads,conditionsfor a type nowhen()is reached on, a condition answering actxof the wrong shape, andloaderswithoutaccess; - five in
fresh.ts:requireFresh()given a bare number, a duration written as prose, nomaxAgeat all, or the request instead of the context, anduseJanus()given a timestamp as itsclock; - six in
connection.ts:janusConnection()given a user type the instance does not know, thepermissions()instance asauth, or a timestamp as itsclock;ctx.janus.accessfrom a connection given noaccess, a field of another user type once narrowed, and anupgradeanswering a token rather than a request; - four in
avatar.ts:avatarResolvers()given nourl, aurlanswering a number or a promise, andtoJanusAvatar()given an object with noavatar; - five in
social.ts:socialResolvers()given an instance whose user types configure nosocial, given noauth, given anauththat is a string, and given anauthfunction that answers an instance with nosocialor something else than an instance; - nine in
passkeys.ts: the sign-in fields read without a guard wherefirstFactor: truewas not given (twice),firstFactor: trueon an instance whosepasskeyshas nofirstFactor: true, anauthfunction that answers something else than an instance,passkeyResolvers()given an instance whosejanus()has nopasskeys, given noauth, given adeviceof the wrong shape, given an instance with several user types and notype, and given atypethe instance does not know. Thetypeof a single-type instance only limits the fields, so it is allowed. - seven in
second-factor.ts:secondFactorResolvers()given an instance whosejanus()has nosecondFactor, afreshWithinas a bare number or as prose, an instance with several user types and notype, atypethe instance does not know, adeviceof the wrong shape, andsecondFactorViewerFields()given an instance with nosecondFactor. - eleven in
invitations.ts:invitationResolvers()given an instance whosejanus()has noinvitations, given noauth, given noauthorize, given adeviceof the wrong shape, anauthorizethat answers for an action that does not exist, aninviterTypethe instance has no user of, andauthorize'ssubjectread without its optional checks (invitation.invitedBy), withpage.limitas a string, withinput.rolecompared as a number, withpage.ordercompared to the SDL's'NEWEST', and a hook whosectxis typed as something that is not a context. - nine in
api-keys.ts:apiKeysResolvers()given an instance whosejanus()has noapiKeys, given noauth, given noauthorize, given anauthorizewithoutrevoke, givenlifetimes.daysempty, a hook that answers a string, aboundthat answers an id instead of{ type, id }, and therevokehook'ssubject.keyread without its check, and thelisthook'spage.limitcompared to a string.
plugin.ts also holds this README's quick start, and connection.ts the
graphql-ws wiring — Yoga's recipe, without Yoga, and Bun's upgrade —
against graphql-ws's own types; both must keep compiling.
Licence
MIT
