You're reading docs for Nextly Alpha. APIs may change between releases.

Plugins

Signed-in people of your own kind

Let people who are not staff sign in through your plugin — a shop's customers, a site's members — without ever reaching the admin.

Alpha (0.x) — @experimental. Plugin-defined kinds of signed-in person are new. Recognising a person on a request, access rules that admit one, and the Direct API acting as one work today; audit records naming a person are still to come. Pin your versions.

Nextly's own sign-in is for staff: the people who use the admin. A plugin that signs in anyone else — a shop's customers, a site's members — registers its own kind of signed-in person. Your plugin owns everything about that kind's sessions: sign-up, sign-in, cookies, password resets. Core only asks your plugin who is signed in, and only where your code asks for that kind.

Such a person:

  • never reaches the admin, core's REST API, or any route that does not ask for their kind;
  • holds no role and no permission, and cannot be given one;
  • is never taken for a staff user, even when their id matches one.

Register a kind

import { definePlugin, type PrincipalKindDefinition } from "@nextlyhq/plugin-sdk";

// Your plugin's own session reader: whatever your sign-in stored.
declare function readMySession(
  request: Request
): Promise<{ accountId: string; verified: boolean; plan: string | null } | null>;

type Account = { verified: boolean; plan: string | null };

const account: PrincipalKindDefinition<Account> = {
  name: "account",
  attributes: { verified: "boolean", plan: "string" },
  async resolve(request) {
    const session = await readMySession(request);
    if (!session) return null;
    return {
      id: session.accountId,
      attributes: { verified: session.verified, plan: session.plan },
    };
  },
};

export default definePlugin({
  name: "@acme/accounts",
  version: "1.0.0",
  nextly: ">=0.0.2-alpha.67",
  contributes: { principals: [account] },
});

Core names the kind <plugin>:<name>, where <plugin> is your plugin's slug: @acme/accounts registers acme-accounts:account. That full name is how a route and server code ask for it.

FieldRules
nameA lowercase letter, then up to 31 lowercase letters, digits or dashes.
attributesEvery attribute the kind exposes, with its type: "boolean", "string" or "number". Typed from your attribute type, so verified: "string" does not compile for a boolean.
resolve(request)Who of this kind is signed in on the request, or null.
lookup(id)Optional. The person with this id, for running as them without a request.

The app refuses to start on a kind whose name, attributes or resolver cannot be used, whose full name is longer than 191 characters (the width audit rows store it in), or whose full name another plugin's kind already holds.

What resolve must answer

  • null for nobody. A resolver that throws also counts as nobody. The throw is logged with the error's name only, never its message, because a message can quote the token it failed to read.
  • An id that is a non-empty string of at most 128 characters, unique within the kind, and never reused once the person is deleted. An id outside those bounds counts as nobody, and a warning says why.
  • Every declared attribute, each with a value of its declared type or null for "not known". An attribute type cannot be optional: write plan: string | null, not plan?: string. A missing attribute or a value of the wrong type counts as nobody. An attribute you did not declare is dropped.

resolve reads cookies and headers. It is handed the request without its body, so reading the body there cannot take it from your handler.

Core calls resolve only where an entry point asks for the kind, and at most once per request, whoever asks: the route, its handler and any server code asking again all see one answer. No staff path ever calls it.

Serve the person from a route

Add principal to a route:

{
  method: "GET",
  path: "/me",
  principal: { kind: "acme-accounts:account" },
  handler: async (req, ctx) => {
    // ctx.principal is the signed-in account; ctx.user and ctx.caller are null.
    return Response.json({ id: ctx.principal?.id });
  },
}

A route that asks for a kind reads neither the staff session nor an API key. Its handler sees the person or nobody, never staff, even in a browser that is signed in to the admin as well. ctx.auth.currentUser answers null there too.

  • With required left at its default (true), a request with no such person is refused with 401 AUTH_REQUIRED, the same answer any route gives an unauthenticated caller.
  • With required: false, the handler runs, and ctx.principal is null when nobody is signed in.
  • principal cannot be combined with public or requiredPermission: the app refuses to start on either pair, and on a kind no plugin registers.

Writes from another site

A person's writes take the route's cross-site check exactly as a staff session cookie's do: the origin by default, a token with csrf: true, and a refusal with csrf: false. A request carrying an Authorization: Bearer header is exempt, because a page on another site cannot make a browser send one. On a route whose principal is not required, a write with nobody of the kind signed in is anonymous: left unchecked with csrf unset, and checked for its origin, without a token, with csrf: true (see which callers each csrf setting checks).

Leave csrf at its default for routes your site's pages call. csrf: true asks for core's admin token, whose cookie lives on /admin, so a page outside the admin cannot send it. If your plugin wants a token on its own forms, mint and check one in the handler.

Ask from server code

From your plugin's own code, ctx.principals reaches your own kinds by the name you gave them. It is present when your plugin registers a kind:

const account = await ctx.principals?.fromRequest(request, "account");

From the app's own server code, nextly.principals takes the full kind:

import { nextly } from "nextly";

export async function GET(request: Request) {
  const account = await nextly.principals.fromRequest(
    request,
    "acme-accounts:account"
  );
  return Response.json({ signedIn: account !== null });
}

Both share the request's answer with every other entry point asking for the same kind. Both answer null to a write from another site, as ctx.auth.currentUser does, unless the request carries a Bearer token. Asking for a kind nobody registered throws, rather than answering nobody.

To act as a person without a request, for example in a job, look them up by id. byId calls the kind's lookup, checks its answer exactly as a resolver's is checked, and answers null for an id the plugin does not return. It throws for a kind with no lookup. The plugin that owns the kind has ctx.principals.byId(name, id) too.

import { nextly } from "nextly";

export async function forAccount(accountId: string) {
  return nextly.principals.byId("acme-accounts:account", accountId);
}

Let a person read and write your collections

A collection admits a person only through its own code-defined rule. Rules see the person as principal, with their kind, id and declared attributes, beside a user that is null:

defineCollection({
  slug: "orders",
  access: {
    read: ({ principal }) => principal?.kind === "acme-accounts:account",
    create: ({ principal }) => principal?.attributes.verified === true,
  },
  fields: [/* ... */],
});
  • A collection with no rule for the operation refuses a person. An anonymous visitor is refused there too for a create, update or delete, and falls through to the public default only for a read.
  • A rule written for staff, such as ({ user }) => !!user, refuses a person, because their user is null.
  • A rule set to true admits a person, as it admits every anonymous visitor.
  • Database permissions and the super-admin bypass never apply to a person, and a person can never publish or unpublish.
  • A field's rule receives principal too, so a field can be kept from members with read: ({ principal }) => principal === null. A field with no rule follows the collection's decision.
  • Related media in a row a person may read reaches them as it reaches an anonymous visitor; a related staff user, role or permission never does.
  • A rule that limits a read to the rows a person owns is not offered yet. Check ownership in your own code.

Run an operation as the person by passing them as principal. Access rules always apply:

import { nextly, type Principal } from "nextly";

export async function ordersOf(account: Principal) {
  return nextly.find({ collection: "orders", principal: account });
}

A plugin's own service call takes the same option: ctx.services.collections.createEntry("orders", data, { principal: account }).

The call is refused, and runs nothing, when it also sets overrideAccess: true, trusted or frameworkFilter, names a user or an API key, or names a person core did not make. Only collection and Single operations can run as a person; any other operation refuses the option. findSingles made as a person lists, and counts, only the Singles the person may read. Hooks for the operation receive the person as principal, with no user. A document created as a person has no owner, because the owner column names staff users; an update made as one leaves the owner as it was.

Record what a person does

Name a person in your audit rows with actorPrincipal and targetPrincipal, by kind and id. A Principal will do:

await ctx.audit?.write({
  kind: "acme-accounts.signed-in",
  actorPrincipal: ctx.principal,
  request: req,
  metadata: { method: "password" },
});

The row keeps the person's kind and id in fields of its own, and keeps its network address, browser and metadata, as it does for a staff user who exists. A person's writes appear in the audit log, not the activity log, which records staff users only. Name one party per role: a role named with both a person and a user id is dropped, and a warning is logged. So is an event naming a person of a kind no running plugin registers, a misspelled kind for instance: no deletion report could ever reach its row.

Email a person

Name the person on every email your plugin sends to one, with person on ctx.services.email.send or sendWithTemplate:

import type { PluginContext, Principal } from "@nextlyhq/plugin-sdk";

export async function sendVerification(
  ctx: PluginContext,
  account: Principal,
  address: string,
  link: string
) {
  await ctx.services.email.sendWithTemplate(
    "acme-accounts-verify",
    address,
    { link },
    { person: account }
  );
}

The delivery record of the message keeps the person's kind and id beside the digest of the address it went to, on the row of the to address; a copied address is someone else's. Core cannot tell a person from an address, so a deletion report reaches only the records of sends that named the person: name them on every email to one. A person that cannot name one, or names a kind no running plugin registers, is refused before anything is sent.

Report a person deleted

When your plugin deletes a person, report it:

await ctx.db.transaction(async tx => {
  // ...delete the account from your own tables with tx...
  await ctx.principals?.reportDeleted(
    { kind: "acme-accounts:account", id: accountId },
    { tx }
  );
});

Core erases the person from the audit trail, in your transaction when you pass tx, so the deletion and the erasure commit or roll back together:

  • the address and browser on every row the person acted on;
  • your metadata on every row of yours naming them;
  • the address digest on every email delivery record naming them.

The rows stay. Core names the person on them by a keyed digest of kind and id in place of the id, and keeps that digest and when, never the id. Every row written about the person afterwards, even by a request that recognised them before the report, is written already erased. Rows about anyone else stay as they were, a staff user with the same id included, and so do the delivery records of anyone else at the same address. An email sent after the report, the one telling the person their account is gone among them, is recorded already erased, even when it is sent inside the report's transaction. Reporting a person twice is harmless.

Without tx, the report runs in a transaction of its own, and is refused when made inside an open transaction, rather than joining it or racing it. Only your own kinds can be reported. How the digest's key survives a rotation of NEXTLY_SECRET is in Audit Log.

A person is not a staff user

A person's id never goes where a staff user's id goes. Do not pass it as a userId, an actorUserId or a targetUserId, or to ctx.auth.completeLogin: completeLogin signs in a staff account, and a person's id there names whichever staff user happens to hold the same id. In an audit row, an id that names no staff user is stored as an erased account's; use actorPrincipal and targetPrincipal instead. Keep your people in your own collections, keyed by the person's kind and id.

Stability

Everything here is @experimental until the feature is complete. These are meant to become stable: a definition's fields and their meaning, the <plugin>:<name> naming, what resolve must answer, the id bounds, a route's principal with required, ctx.principal, fromRequest, byId, principal in collection and field rules, the principal option's refusals, Principal, PrincipalRef, actorPrincipal and targetPrincipal on audit rows, person on a plugin's email sends, and reportDeleted with what it erases. The contributes.principals key, where nextly.principals hangs, the spelling of a route's principal, the option's name and where the person sits in a hook's context may still change.