@plinthjs/api-tokens 0.1.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +14 -14
- package/dist/index.d.ts +14 -14
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +6 -6
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @plinthjs/api-tokens
|
|
2
2
|
|
|
3
|
-
Lightweight API token authentication for Plinth
|
|
3
|
+
Lightweight API token authentication for Plinth. Issue personal
|
|
4
4
|
access tokens with abilities and optional expiry, store only a SHA-256 hash of each secret, and
|
|
5
5
|
authenticate `id|secret` bearer tokens with a constant-time `TokenGuard`. Persistence sits behind a
|
|
6
6
|
small `TokenStore` interface with an in-memory `ArrayTokenStore` default, and the clock and id/secret
|
package/dist/index.cjs
CHANGED
|
@@ -20,7 +20,7 @@ var PersonalAccessToken = class _PersonalAccessToken {
|
|
|
20
20
|
tokenableId;
|
|
21
21
|
/** @see PersonalAccessTokenAttributes.tokenableType */
|
|
22
22
|
tokenableType;
|
|
23
|
-
/** @see PersonalAccessTokenAttributes.lastUsedAt
|
|
23
|
+
/** @see PersonalAccessTokenAttributes.lastUsedAt - mutable: refreshed by the guard on auth. */
|
|
24
24
|
lastUsedAt;
|
|
25
25
|
/** @see PersonalAccessTokenAttributes.expiresAt */
|
|
26
26
|
expiresAt;
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/token.ts","../src/factory.ts","../src/store.ts","../src/guard.ts","../src/has-api-tokens.ts","../src/index.ts"],"names":["createHash","randomBytes","uuid","timingSafeEqual"],"mappings":";;;;;;;;AAUO,IAAM,gBAAA,GAAmB;AAkCzB,IAAM,mBAAA,GAAN,MAAM,oBAAA,CAA6D;AAAA;AAAA,EAE/D,EA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,MAAA,GAAgC;AAC9B,MAAA,OAAO,KAAA,CAAM,KAAI,CAAE,MAAA,CAAO,CAAC,KAAA,KAAU,OAAA,CAAQ,KAAA,EAAO,KAAK,CAAC,CAAA;AAAA,IAC5D,CAAA;AAAA,IACA,SAAS,OAAA,EAA0B;AACjC,MAAA,OAAO,KAAA,CACJ,KAAI,CACJ,IAAA;AAAA,QACC,CAAC,KAAA,KACC,OAAA,CAAQ,KAAA,EAAO,KAAK,CAAA,KACnB,KAAA,CAAM,SAAA,CAAU,QAAA,CAAS,gBAAgB,CAAA,IAAK,KAAA,CAAM,SAAA,CAAU,SAAS,OAAO,CAAA;AAAA,OACnF;AAAA,IACJ;AAAA,GACF;AACF;;;AClEO,IAAM,OAAA,GAAU","file":"index.cjs","sourcesContent":["/**\n * `PersonalAccessToken`.\n *\n * A record of an issued API token. The plaintext token is NEVER stored; only its SHA-256 hash\n * ({@link PersonalAccessToken.tokenHash}) is. A token also carries an ability list that scopes what\n * it may do — {@link PersonalAccessToken.can} mirrors Sanctum's `tokenCan()`, where the wildcard\n * `'*'` grants every ability and any other ability requires an exact string match.\n */\n\n/** The wildcard ability that grants every permission, as in Sanctum. */\nexport const WILDCARD_ABILITY = '*'\n\n/**\n * The persisted shape of a personal access token — the columns of Sanctum's\n * `personal_access_tokens` table. The plaintext is intentionally absent: only {@link tokenHash} is\n * kept. Optional columns are omitted entirely when unset (never present-but-`undefined`) so the\n * record round-trips cleanly under `exactOptionalPropertyTypes`.\n */\nexport interface PersonalAccessTokenAttributes {\n /** The token id — the part before the `|` in the plaintext, used to look the record up. */\n id: string\n /** A human-readable name for the token (e.g. the device or integration it was issued for). */\n name: string\n /** The lowercase SHA-256 hex digest of the secret (the part of the plaintext after the `|`). */\n tokenHash: string\n /** The abilities granted to the token; `['*']` grants everything. */\n abilities: string[]\n /** The primary key of the owning model (`tokenable_id`), if the token belongs to one. */\n tokenableId?: string | number\n /** The type/morph name of the owning model (`tokenable_type`), if the token belongs to one. */\n tokenableType?: string\n /** Epoch milliseconds when the token was last used to authenticate, if ever. */\n lastUsedAt?: number\n /** Epoch milliseconds when the token expires; absent means it never expires. */\n expiresAt?: number\n /** Epoch milliseconds when the token was created. */\n createdAt: number\n}\n\n/**\n * A personal access token record. Construct directly from attributes, or via\n * {@link PersonalAccessToken.from}. Behaviour ({@link can}/{@link cant}/{@link isExpired}) lives\n * here; persistence lives behind a `TokenStore`.\n */\nexport class PersonalAccessToken implements PersonalAccessTokenAttributes {\n /** @see PersonalAccessTokenAttributes.id */\n readonly id: string\n /** @see PersonalAccessTokenAttributes.name */\n readonly name: string\n /** @see PersonalAccessTokenAttributes.tokenHash */\n readonly tokenHash: string\n /** @see PersonalAccessTokenAttributes.abilities */\n readonly abilities: string[]\n /** @see PersonalAccessTokenAttributes.tokenableId */\n readonly tokenableId?: string | number\n /** @see PersonalAccessTokenAttributes.tokenableType */\n readonly tokenableType?: string\n /** @see PersonalAccessTokenAttributes.lastUsedAt — mutable: refreshed by the guard on auth. */\n lastUsedAt?: number\n /** @see PersonalAccessTokenAttributes.expiresAt */\n readonly expiresAt?: number\n /** @see PersonalAccessTokenAttributes.createdAt */\n readonly createdAt: number\n\n constructor(attributes: PersonalAccessTokenAttributes) {\n this.id = attributes.id\n this.name = attributes.name\n this.tokenHash = attributes.tokenHash\n this.abilities = [...attributes.abilities]\n if (attributes.tokenableId !== undefined) this.tokenableId = attributes.tokenableId\n if (attributes.tokenableType !== undefined) this.tokenableType = attributes.tokenableType\n if (attributes.lastUsedAt !== undefined) this.lastUsedAt = attributes.lastUsedAt\n if (attributes.expiresAt !== undefined) this.expiresAt = attributes.expiresAt\n this.createdAt = attributes.createdAt\n }\n\n /** Build a token from a plain attributes object. The `PersonalAccessToken::make()` equivalent. */\n static from(attributes: PersonalAccessTokenAttributes): PersonalAccessToken {\n return new PersonalAccessToken(attributes)\n }\n\n /**\n * Whether the token is granted `ability`. The wildcard `'*'` ability grants everything; any\n * other ability must match an entry exactly.\n */\n can(ability: string): boolean {\n return this.abilities.includes(WILDCARD_ABILITY) || this.abilities.includes(ability)\n }\n\n /** The negation of {@link can}. */\n cant(ability: string): boolean {\n return !this.can(ability)\n }\n\n /** Whether the token has expired relative to `now` (epoch ms). Never-expiring tokens are false. */\n isExpired(now: number): boolean {\n return this.expiresAt !== undefined && this.expiresAt <= now\n }\n\n /** A plain snapshot of the record, omitting any unset optional fields. */\n toAttributes(): PersonalAccessTokenAttributes {\n const attributes: PersonalAccessTokenAttributes = {\n id: this.id,\n name: this.name,\n tokenHash: this.tokenHash,\n abilities: [...this.abilities],\n createdAt: this.createdAt,\n }\n if (this.tokenableId !== undefined) attributes.tokenableId = this.tokenableId\n if (this.tokenableType !== undefined) attributes.tokenableType = this.tokenableType\n if (this.lastUsedAt !== undefined) attributes.lastUsedAt = this.lastUsedAt\n if (this.expiresAt !== undefined) attributes.expiresAt = this.expiresAt\n return attributes\n }\n}\n","/**\n * Token issuance and the plaintext/hash scheme — the Sanctum `HasApiTokens::createToken`\n * equivalent.\n *\n * TOKEN FORMAT (Sanctum parity):\n * plaintext = `${id}|${secret}`\n * where `id` is the stored row id (here a UUID v4) and `secret` is `randomBytes(40)` rendered as\n * hex. The two are joined by a single `|`. On authentication the client sends the whole plaintext\n * as the bearer token; the id locates the row and the secret is verified against the hash.\n *\n * HASHING (Sanctum parity): Sanctum hashes ONLY the secret — the part AFTER the `|` — with SHA-256\n * and stores the lowercase hex digest. It does NOT hash the `id|` prefix. {@link hashSecret} is the\n * single definition of that rule and is used by both issuance and verification so they can never\n * drift. SHA-256 (not a slow KDF) is appropriate here because the secret is high-entropy random,\n * not a user-chosen password.\n */\nimport { createHash, randomBytes } from 'node:crypto'\n\nimport { uuid } from '@plinthjs/support'\n\nimport { PersonalAccessToken } from './token'\n\nimport type { TokenStore } from './store'\n\n/** The default abilities granted when none are specified — full access, as in Sanctum. */\nconst DEFAULT_ABILITIES: readonly string[] = ['*']\n\n/** Number of random bytes in the secret; 40 bytes → an 80-char hex secret (Sanctum uses ~40). */\nconst SECRET_BYTES = 40\n\n/** The separator between the id and the secret in a plaintext token. */\nexport const TOKEN_SEPARATOR = '|'\n\n/**\n * Hash the secret portion of a token with SHA-256, returning the lowercase hex digest. This is the\n * canonical hashing rule — it takes the SECRET ONLY (never the `id|` prefix), matching Sanctum, and\n * is shared by issuance and verification so the two stay in lockstep.\n */\nexport function hashSecret(secret: string): string {\n return createHash('sha256').update(secret).digest('hex')\n}\n\n/**\n * Split a plaintext bearer token into its `{ id, secret }` parts, or `null` if it is not in the\n * `id|secret` form. The id is everything before the first `|`; the secret is everything after, so a\n * secret may itself contain `|` without ambiguity. Empty id or empty secret yields `null`.\n */\nexport function parseToken(plainTextToken: string): { id: string; secret: string } | null {\n const index = plainTextToken.indexOf(TOKEN_SEPARATOR)\n if (index <= 0) return null\n const id = plainTextToken.slice(0, index)\n const secret = plainTextToken.slice(index + 1)\n if (secret.length === 0) return null\n return { id, secret }\n}\n\n/** Generate a fresh high-entropy secret as a hex string. */\nfunction generateSecret(): string {\n return randomBytes(SECRET_BYTES).toString('hex')\n}\n\n/** Options for {@link createToken} — the named parameters of Sanctum's `createToken`. */\nexport interface CreateTokenOptions {\n /** A human-readable name for the token. */\n name: string\n /** The abilities to grant; defaults to `['*']` (full access). */\n abilities?: string[]\n /** Epoch milliseconds when the token should expire; omit for a non-expiring token. */\n expiresAt?: number\n /** The owning model's primary key (`tokenable_id`). */\n tokenableId?: string | number\n /** The owning model's type/morph name (`tokenable_type`). */\n tokenableType?: string\n}\n\n/** Overridable seams for {@link createToken}, primarily for deterministic tests. */\nexport interface CreateTokenSeams {\n /** Clock used for `createdAt`; defaults to `Date.now`. Epoch milliseconds. */\n now?: () => number\n /** Id generator; defaults to a UUID v4. */\n generateId?: () => string\n /** Secret generator; defaults to 40 random bytes as hex. */\n generateSecret?: () => string\n}\n\n/**\n * The result of issuing a token. {@link plainTextToken} is the full `id|secret` string and is\n * returned EXACTLY ONCE — it is never recoverable from {@link accessToken}, which holds only the\n * hash.\n */\nexport interface NewAccessToken {\n /** The persisted record (hash only — no plaintext). */\n accessToken: PersonalAccessToken\n /** The full plaintext token to hand to the client this one time. */\n plainTextToken: string\n}\n\n/**\n * Issue a new personal access token, persist its record (hash only) to `store`, and return the\n * record together with the one-time plaintext.\n */\nexport function createToken(\n store: TokenStore,\n options: CreateTokenOptions,\n seams?: CreateTokenSeams,\n): NewAccessToken {\n const now = (seams?.now ?? Date.now)()\n const id = (seams?.generateId ?? uuid)()\n const secret = (seams?.generateSecret ?? generateSecret)()\n const abilities = options.abilities ?? [...DEFAULT_ABILITIES]\n\n const attributes = {\n id,\n name: options.name,\n tokenHash: hashSecret(secret),\n abilities,\n createdAt: now,\n } as ConstructorParameters<typeof PersonalAccessToken>[0]\n if (options.tokenableId !== undefined) attributes.tokenableId = options.tokenableId\n if (options.tokenableType !== undefined) attributes.tokenableType = options.tokenableType\n if (options.expiresAt !== undefined) attributes.expiresAt = options.expiresAt\n\n const accessToken = new PersonalAccessToken(attributes)\n store.save(accessToken)\n\n return { accessToken, plainTextToken: `${id}${TOKEN_SEPARATOR}${secret}` }\n}\n\n/** Alias for {@link createToken}, matching the `issueToken` naming used elsewhere in Plinth. */\nexport const issueToken: (\n store: TokenStore,\n options: CreateTokenOptions,\n seams?: CreateTokenSeams,\n) => NewAccessToken = createToken\n","/**\n * `TokenStore` — the persistence seam for personal access tokens.\n *\n * Sanctum stores tokens in a database table; Plinth keeps the framework dependency-free, so the\n * store is an interface the application implements against its own ORM. {@link ArrayTokenStore} is\n * an in-memory implementation suitable for tests and ephemeral use.\n */\nimport type { PersonalAccessToken } from './token'\n\n/**\n * The seam between the guard/factory and however tokens are persisted — the Sanctum\n * `personal_access_tokens` repository equivalent. Lookups are by token id (the part before the `|`).\n */\nexport interface TokenStore {\n /** Find a token by its id, or `undefined` if none is stored. */\n find(id: string): PersonalAccessToken | undefined\n /** Persist (insert or replace) a token, keyed by its id. */\n save(token: PersonalAccessToken): void\n /** Delete the token with the given id, if present. The revoke equivalent. */\n delete(id: string): void\n /** Every stored token. */\n all(): PersonalAccessToken[]\n}\n\n/**\n * Free-function form of {@link TokenStore.find}: look a token up by id, or `undefined`. Exists so\n * callers can read a store without tripping `unicorn/no-array-callback-reference`, which cannot tell\n * a repository's `.find(id)` apart from `Array.prototype.find` (the collision is resolved here once).\n */\nexport function findToken(store: TokenStore, id: string): PersonalAccessToken | undefined {\n // eslint-disable-next-line unicorn/no-array-callback-reference -- repository lookup, not Array#find\n return store.find(id)\n}\n\n/**\n * An in-memory {@link TokenStore} backed by a `Map`. Not persistent across processes — intended for\n * tests, fixtures, and short-lived use. Real persistence is implemented by the application.\n */\nexport class ArrayTokenStore implements TokenStore {\n private readonly tokens = new Map<string, PersonalAccessToken>()\n\n /** Seed the store with an optional initial set of tokens. */\n constructor(initial?: Iterable<PersonalAccessToken>) {\n if (initial !== undefined) {\n for (const token of initial) this.tokens.set(token.id, token)\n }\n }\n\n find(id: string): PersonalAccessToken | undefined {\n return this.tokens.get(id)\n }\n\n save(token: PersonalAccessToken): void {\n this.tokens.set(token.id, token)\n }\n\n delete(id: string): void {\n this.tokens.delete(id)\n }\n\n all(): PersonalAccessToken[] {\n return [...this.tokens.values()]\n }\n\n /** Remove every stored token. Convenience for resetting between tests. */\n flush(): void {\n this.tokens.clear()\n }\n\n /** The number of stored tokens. */\n get size(): number {\n return this.tokens.size\n }\n}\n","/**\n * `TokenGuard` — authenticate a bearer token against a {@link TokenStore}.\n *\n * Given a plaintext `id|secret` bearer token it locates the\n * record by id, verifies the presented secret against the stored SHA-256 hash in CONSTANT TIME\n * ({@link timingSafeEqual}, length-guarded so unequal lengths never throw and never leak timing),\n * rejects expired tokens, and on success stamps `lastUsedAt` from the injected clock.\n */\nimport { timingSafeEqual } from 'node:crypto'\n\nimport { hashSecret, parseToken } from './factory'\nimport { findToken } from './store'\n\nimport type { TokenStore } from './store'\nimport type { PersonalAccessToken } from './token'\n\n/**\n * Constant-time equality of two hex digest strings. Returns `false` immediately when the lengths\n * differ (so `timingSafeEqual`, which throws on unequal-length buffers, is never reached), and\n * otherwise compares the bytes without short-circuiting. Used to compare token hashes.\n */\nexport function hashesMatch(a: string, b: string): boolean {\n const left = Buffer.from(a, 'utf8')\n const right = Buffer.from(b, 'utf8')\n if (left.length !== right.length) return false\n return timingSafeEqual(left, right)\n}\n\n/**\n * Authenticates personal access tokens. Construct with a {@link TokenStore} and, optionally, a\n * clock seam (epoch ms) used to test expiry and stamp `lastUsedAt`.\n */\nexport class TokenGuard {\n private readonly store: TokenStore\n private readonly clock: () => number\n\n /**\n * @param store The token repository to look records up in.\n * @param clock Returns the current time in epoch ms; defaults to `Date.now`. Injectable for tests.\n */\n constructor(store: TokenStore, clock?: () => number) {\n this.store = store\n this.clock = clock ?? Date.now\n }\n\n /**\n * Resolve a plaintext bearer token to its record, or `null` if it is malformed, unknown, the\n * secret does not match (constant-time), or it has expired. On success the record's `lastUsedAt`\n * is set to the current clock time and persisted. The Sanctum token-resolution equivalent.\n */\n authenticate(bearer: string): PersonalAccessToken | null {\n const parts = parseToken(bearer)\n if (parts === null) return null\n const { id, secret } = parts\n\n const token = findToken(this.store, id)\n if (token === undefined) return null\n\n if (!hashesMatch(hashSecret(secret), token.tokenHash)) return null\n\n const now = this.clock()\n if (token.isExpired(now)) return null\n\n token.lastUsedAt = now\n this.store.save(token)\n return token\n }\n\n /**\n * Resolve a bearer token to the id of its owning model (`tokenable_id`), or `null` if the token\n * is invalid or carries no owner. Convenience over {@link authenticate} for guards that only need\n * the user id.\n */\n authenticateToken(bearer: string): string | number | null {\n const token = this.authenticate(bearer)\n if (token === null) return null\n return token.tokenableId ?? null\n }\n\n /** Whether `bearer` resolves to a valid, unexpired token. */\n check(bearer: string): boolean {\n return this.authenticate(bearer) !== null\n }\n}\n","/**\n * `HasApiTokens`, as a helper bound to a\n * {@link TokenStore} and a tokenable owner.\n *\n * Plinth has no PHP traits, so instead of mixing methods into a model class this returns a small\n * object whose `createToken` / `tokens` / `tokenCan` are pre-bound to one owner. The owner's id and\n * (optional) morph type are stamped onto every token it issues, and `tokens()` lists only that\n * owner's tokens.\n */\nimport { createToken } from './factory'\nimport { WILDCARD_ABILITY } from './token'\n\nimport type { CreateTokenSeams, NewAccessToken } from './factory'\nimport type { TokenStore } from './store'\nimport type { PersonalAccessToken } from './token'\n\n/** The owning model of a set of tokens — its primary key and optional morph type. */\nexport interface Tokenable {\n /** The owner's primary key, stamped as `tokenableId` on issued tokens. */\n id: string | number\n /** The owner's morph type/name, stamped as `tokenableType` on issued tokens. */\n type?: string\n}\n\n/** The per-token inputs accepted by {@link HasApiTokens.createToken} (owner is already bound). */\nexport interface HasApiTokensCreateOptions {\n /** A human-readable name for the token. */\n name: string\n /** The abilities to grant; defaults to `['*']`. */\n abilities?: string[]\n /** Epoch milliseconds when the token should expire; omit for a non-expiring token. */\n expiresAt?: number\n}\n\n/** The owner-bound token API returned by {@link hasApiTokens}. */\nexport interface HasApiTokens {\n /** Issue a token for the bound owner, persisting it and returning the one-time plaintext. */\n createToken(options: HasApiTokensCreateOptions, seams?: CreateTokenSeams): NewAccessToken\n /** Every stored token belonging to the bound owner. */\n tokens(): PersonalAccessToken[]\n /** Whether any of the owner's tokens grants `ability` (wildcard `'*'` counts). */\n tokenCan(ability: string): boolean\n}\n\n/** Whether `token` belongs to `owner` (matching id and, when set, morph type). */\nfunction ownedBy(token: PersonalAccessToken, owner: Tokenable): boolean {\n if (token.tokenableId !== owner.id) return false\n if (owner.type === undefined) return true\n return token.tokenableType === owner.type\n}\n\n/**\n * Bind the token API to a `store` and a tokenable `owner`. Tokens issued via the returned object are stamped with the owner's id/type, and\n * {@link HasApiTokens.tokens} / {@link HasApiTokens.tokenCan} are scoped to that owner.\n */\nexport function hasApiTokens(store: TokenStore, owner: Tokenable): HasApiTokens {\n return {\n createToken(options: HasApiTokensCreateOptions, seams?: CreateTokenSeams): NewAccessToken {\n const base = {\n name: options.name,\n tokenableId: owner.id,\n } as Parameters<typeof createToken>[1]\n if (options.abilities !== undefined) base.abilities = options.abilities\n if (options.expiresAt !== undefined) base.expiresAt = options.expiresAt\n if (owner.type !== undefined) base.tokenableType = owner.type\n return createToken(store, base, seams)\n },\n tokens(): PersonalAccessToken[] {\n return store.all().filter((token) => ownedBy(token, owner))\n },\n tokenCan(ability: string): boolean {\n return store\n .all()\n .some(\n (token) =>\n ownedBy(token, owner) &&\n (token.abilities.includes(WILDCARD_ABILITY) || token.abilities.includes(ability)),\n )\n },\n }\n}\n","/**\n * @plinthjs/api-tokens — API token authentication, the Sanctum equivalent.\n *\n * Stateless bearer-token auth with zero dependencies beyond `node:crypto` and `@plinthjs/support`.\n * Issue a token with {@link createToken} (the plaintext is returned ONCE; only its SHA-256 hash is\n * stored), persist it through a {@link TokenStore} ({@link ArrayTokenStore} ships in-memory), and\n * authenticate incoming bearer tokens with {@link TokenGuard}, which verifies the secret in\n * constant time and honours per-token {@link PersonalAccessToken.can | abilities} and expiry.\n *\n * TOKEN SCHEME: plaintext = `${id}|${secret}`; the stored hash is `sha256(secret)` in hex — the\n * secret being only the part AFTER the `|`, exactly as Sanctum hashes it.\n */\n\n/** The Plinth version this build of `sanctum` ships with. */\nexport const VERSION = '0.1.0'\n\nexport {\n type CreateTokenOptions,\n type CreateTokenSeams,\n createToken,\n hashSecret,\n issueToken,\n type NewAccessToken,\n parseToken,\n TOKEN_SEPARATOR,\n} from './factory'\nexport { TokenGuard, hashesMatch } from './guard'\nexport {\n type HasApiTokens,\n hasApiTokens,\n type HasApiTokensCreateOptions,\n type Tokenable,\n} from './has-api-tokens'\nexport { ArrayTokenStore, findToken, type TokenStore } from './store'\nexport { PersonalAccessToken, type PersonalAccessTokenAttributes, WILDCARD_ABILITY } from './token'\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/token.ts","../src/factory.ts","../src/store.ts","../src/guard.ts","../src/has-api-tokens.ts","../src/index.ts"],"names":["createHash","randomBytes","uuid","timingSafeEqual"],"mappings":";;;;;;;;AAUO,IAAM,gBAAA,GAAmB;AAkCzB,IA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,EAAO,IAAA,EAAM,KAAK,CAAA;AAAA,IACvC,CAAA;AAAA,IACA,MAAA,GAAgC;AAC9B,MAAA,OAAO,KAAA,CAAM,KAAI,CAAE,MAAA,CAAO,CAAC,KAAA,KAAU,OAAA,CAAQ,KAAA,EAAO,KAAK,CAAC,CAAA;AAAA,IAC5D,CAAA;AAAA,IACA,SAAS,OAAA,EAA0B;AACjC,MAAA,OAAO,KAAA,CACJ,KAAI,CACJ,IAAA;AAAA,QACC,CAAC,KAAA,KACC,OAAA,CAAQ,KAAA,EAAO,KAAK,CAAA,KACnB,KAAA,CAAM,SAAA,CAAU,QAAA,CAAS,gBAAgB,CAAA,IAAK,KAAA,CAAM,SAAA,CAAU,SAAS,OAAO,CAAA;AAAA,OACnF;AAAA,IACJ;AAAA,GACF;AACF;;;AClEO,IAAM,OAAA,GAAU","file":"index.cjs","sourcesContent":["/**\n * `PersonalAccessToken`.\n *\n * A record of an issued API token. The plaintext token is NEVER stored; only its SHA-256 hash\n * ({@link PersonalAccessToken.tokenHash}) is. A token also carries an ability list that scopes what\n * it may do - {@link PersonalAccessToken.can} mirrors Sanctum's `tokenCan()`, where the wildcard\n * `'*'` grants every ability and any other ability requires an exact string match.\n */\n\n/** The wildcard ability that grants every permission, as in Sanctum. */\nexport const WILDCARD_ABILITY = '*'\n\n/**\n * The persisted shape of a personal access token - the columns of Sanctum's\n * `personal_access_tokens` table. The plaintext is intentionally absent: only {@link tokenHash} is\n * kept. Optional columns are omitted entirely when unset (never present-but-`undefined`) so the\n * record round-trips cleanly under `exactOptionalPropertyTypes`.\n */\nexport interface PersonalAccessTokenAttributes {\n /** The token id - the part before the `|` in the plaintext, used to look the record up. */\n id: string\n /** A human-readable name for the token (e.g. the device or integration it was issued for). */\n name: string\n /** The lowercase SHA-256 hex digest of the secret (the part of the plaintext after the `|`). */\n tokenHash: string\n /** The abilities granted to the token; `['*']` grants everything. */\n abilities: string[]\n /** The primary key of the owning model (`tokenable_id`), if the token belongs to one. */\n tokenableId?: string | number\n /** The type/morph name of the owning model (`tokenable_type`), if the token belongs to one. */\n tokenableType?: string\n /** Epoch milliseconds when the token was last used to authenticate, if ever. */\n lastUsedAt?: number\n /** Epoch milliseconds when the token expires; absent means it never expires. */\n expiresAt?: number\n /** Epoch milliseconds when the token was created. */\n createdAt: number\n}\n\n/**\n * A personal access token record. Construct directly from attributes, or via\n * {@link PersonalAccessToken.from}. Behaviour ({@link can}/{@link cant}/{@link isExpired}) lives\n * here; persistence lives behind a `TokenStore`.\n */\nexport class PersonalAccessToken implements PersonalAccessTokenAttributes {\n /** @see PersonalAccessTokenAttributes.id */\n readonly id: string\n /** @see PersonalAccessTokenAttributes.name */\n readonly name: string\n /** @see PersonalAccessTokenAttributes.tokenHash */\n readonly tokenHash: string\n /** @see PersonalAccessTokenAttributes.abilities */\n readonly abilities: string[]\n /** @see PersonalAccessTokenAttributes.tokenableId */\n readonly tokenableId?: string | number\n /** @see PersonalAccessTokenAttributes.tokenableType */\n readonly tokenableType?: string\n /** @see PersonalAccessTokenAttributes.lastUsedAt - mutable: refreshed by the guard on auth. */\n lastUsedAt?: number\n /** @see PersonalAccessTokenAttributes.expiresAt */\n readonly expiresAt?: number\n /** @see PersonalAccessTokenAttributes.createdAt */\n readonly createdAt: number\n\n constructor(attributes: PersonalAccessTokenAttributes) {\n this.id = attributes.id\n this.name = attributes.name\n this.tokenHash = attributes.tokenHash\n this.abilities = [...attributes.abilities]\n if (attributes.tokenableId !== undefined) this.tokenableId = attributes.tokenableId\n if (attributes.tokenableType !== undefined) this.tokenableType = attributes.tokenableType\n if (attributes.lastUsedAt !== undefined) this.lastUsedAt = attributes.lastUsedAt\n if (attributes.expiresAt !== undefined) this.expiresAt = attributes.expiresAt\n this.createdAt = attributes.createdAt\n }\n\n /** Build a token from a plain attributes object. The `PersonalAccessToken::make()` equivalent. */\n static from(attributes: PersonalAccessTokenAttributes): PersonalAccessToken {\n return new PersonalAccessToken(attributes)\n }\n\n /**\n * Whether the token is granted `ability`. The wildcard `'*'` ability grants everything; any\n * other ability must match an entry exactly.\n */\n can(ability: string): boolean {\n return this.abilities.includes(WILDCARD_ABILITY) || this.abilities.includes(ability)\n }\n\n /** The negation of {@link can}. */\n cant(ability: string): boolean {\n return !this.can(ability)\n }\n\n /** Whether the token has expired relative to `now` (epoch ms). Never-expiring tokens are false. */\n isExpired(now: number): boolean {\n return this.expiresAt !== undefined && this.expiresAt <= now\n }\n\n /** A plain snapshot of the record, omitting any unset optional fields. */\n toAttributes(): PersonalAccessTokenAttributes {\n const attributes: PersonalAccessTokenAttributes = {\n id: this.id,\n name: this.name,\n tokenHash: this.tokenHash,\n abilities: [...this.abilities],\n createdAt: this.createdAt,\n }\n if (this.tokenableId !== undefined) attributes.tokenableId = this.tokenableId\n if (this.tokenableType !== undefined) attributes.tokenableType = this.tokenableType\n if (this.lastUsedAt !== undefined) attributes.lastUsedAt = this.lastUsedAt\n if (this.expiresAt !== undefined) attributes.expiresAt = this.expiresAt\n return attributes\n }\n}\n","/**\n * Token issuance and the plaintext/hash scheme - the Sanctum `HasApiTokens::createToken`\n * equivalent.\n *\n * TOKEN FORMAT (Sanctum parity):\n * plaintext = `${id}|${secret}`\n * where `id` is the stored row id (here a UUID v4) and `secret` is `randomBytes(40)` rendered as\n * hex. The two are joined by a single `|`. On authentication the client sends the whole plaintext\n * as the bearer token; the id locates the row and the secret is verified against the hash.\n *\n * HASHING (Sanctum parity): Sanctum hashes ONLY the secret - the part AFTER the `|` - with SHA-256\n * and stores the lowercase hex digest. It does NOT hash the `id|` prefix. {@link hashSecret} is the\n * single definition of that rule and is used by both issuance and verification so they can never\n * drift. SHA-256 (not a slow KDF) is appropriate here because the secret is high-entropy random,\n * not a user-chosen password.\n */\nimport { createHash, randomBytes } from 'node:crypto'\n\nimport { uuid } from '@plinthjs/support'\n\nimport { PersonalAccessToken } from './token'\n\nimport type { TokenStore } from './store'\n\n/** The default abilities granted when none are specified - full access, as in Sanctum. */\nconst DEFAULT_ABILITIES: readonly string[] = ['*']\n\n/** Number of random bytes in the secret; 40 bytes → an 80-char hex secret (Sanctum uses ~40). */\nconst SECRET_BYTES = 40\n\n/** The separator between the id and the secret in a plaintext token. */\nexport const TOKEN_SEPARATOR = '|'\n\n/**\n * Hash the secret portion of a token with SHA-256, returning the lowercase hex digest. This is the\n * canonical hashing rule - it takes the SECRET ONLY (never the `id|` prefix), matching Sanctum, and\n * is shared by issuance and verification so the two stay in lockstep.\n */\nexport function hashSecret(secret: string): string {\n return createHash('sha256').update(secret).digest('hex')\n}\n\n/**\n * Split a plaintext bearer token into its `{ id, secret }` parts, or `null` if it is not in the\n * `id|secret` form. The id is everything before the first `|`; the secret is everything after, so a\n * secret may itself contain `|` without ambiguity. Empty id or empty secret yields `null`.\n */\nexport function parseToken(plainTextToken: string): { id: string; secret: string } | null {\n const index = plainTextToken.indexOf(TOKEN_SEPARATOR)\n if (index <= 0) return null\n const id = plainTextToken.slice(0, index)\n const secret = plainTextToken.slice(index + 1)\n if (secret.length === 0) return null\n return { id, secret }\n}\n\n/** Generate a fresh high-entropy secret as a hex string. */\nfunction generateSecret(): string {\n return randomBytes(SECRET_BYTES).toString('hex')\n}\n\n/** Options for {@link createToken} - the named parameters of Sanctum's `createToken`. */\nexport interface CreateTokenOptions {\n /** A human-readable name for the token. */\n name: string\n /** The abilities to grant; defaults to `['*']` (full access). */\n abilities?: string[]\n /** Epoch milliseconds when the token should expire; omit for a non-expiring token. */\n expiresAt?: number\n /** The owning model's primary key (`tokenable_id`). */\n tokenableId?: string | number\n /** The owning model's type/morph name (`tokenable_type`). */\n tokenableType?: string\n}\n\n/** Overridable seams for {@link createToken}, primarily for deterministic tests. */\nexport interface CreateTokenSeams {\n /** Clock used for `createdAt`; defaults to `Date.now`. Epoch milliseconds. */\n now?: () => number\n /** Id generator; defaults to a UUID v4. */\n generateId?: () => string\n /** Secret generator; defaults to 40 random bytes as hex. */\n generateSecret?: () => string\n}\n\n/**\n * The result of issuing a token. {@link plainTextToken} is the full `id|secret` string and is\n * returned EXACTLY ONCE - it is never recoverable from {@link accessToken}, which holds only the\n * hash.\n */\nexport interface NewAccessToken {\n /** The persisted record (hash only - no plaintext). */\n accessToken: PersonalAccessToken\n /** The full plaintext token to hand to the client this one time. */\n plainTextToken: string\n}\n\n/**\n * Issue a new personal access token, persist its record (hash only) to `store`, and return the\n * record together with the one-time plaintext.\n */\nexport function createToken(\n store: TokenStore,\n options: CreateTokenOptions,\n seams?: CreateTokenSeams,\n): NewAccessToken {\n const now = (seams?.now ?? Date.now)()\n const id = (seams?.generateId ?? uuid)()\n const secret = (seams?.generateSecret ?? generateSecret)()\n const abilities = options.abilities ?? [...DEFAULT_ABILITIES]\n\n const attributes = {\n id,\n name: options.name,\n tokenHash: hashSecret(secret),\n abilities,\n createdAt: now,\n } as ConstructorParameters<typeof PersonalAccessToken>[0]\n if (options.tokenableId !== undefined) attributes.tokenableId = options.tokenableId\n if (options.tokenableType !== undefined) attributes.tokenableType = options.tokenableType\n if (options.expiresAt !== undefined) attributes.expiresAt = options.expiresAt\n\n const accessToken = new PersonalAccessToken(attributes)\n store.save(accessToken)\n\n return { accessToken, plainTextToken: `${id}${TOKEN_SEPARATOR}${secret}` }\n}\n\n/** Alias for {@link createToken}, matching the `issueToken` naming used elsewhere in Plinth. */\nexport const issueToken: (\n store: TokenStore,\n options: CreateTokenOptions,\n seams?: CreateTokenSeams,\n) => NewAccessToken = createToken\n","/**\n * `TokenStore` - the persistence seam for personal access tokens.\n *\n * Sanctum stores tokens in a database table; Plinth keeps the framework dependency-free, so the\n * store is an interface the application implements against its own ORM. {@link ArrayTokenStore} is\n * an in-memory implementation suitable for tests and ephemeral use.\n */\nimport type { PersonalAccessToken } from './token'\n\n/**\n * The seam between the guard/factory and however tokens are persisted - the Sanctum\n * `personal_access_tokens` repository equivalent. Lookups are by token id (the part before the `|`).\n */\nexport interface TokenStore {\n /** Find a token by its id, or `undefined` if none is stored. */\n find(id: string): PersonalAccessToken | undefined\n /** Persist (insert or replace) a token, keyed by its id. */\n save(token: PersonalAccessToken): void\n /** Delete the token with the given id, if present. The revoke equivalent. */\n delete(id: string): void\n /** Every stored token. */\n all(): PersonalAccessToken[]\n}\n\n/**\n * Free-function form of {@link TokenStore.find}: look a token up by id, or `undefined`. Exists so\n * callers can read a store without tripping `unicorn/no-array-callback-reference`, which cannot tell\n * a repository's `.find(id)` apart from `Array.prototype.find` (the collision is resolved here once).\n */\nexport function findToken(store: TokenStore, id: string): PersonalAccessToken | undefined {\n // eslint-disable-next-line unicorn/no-array-callback-reference -- repository lookup, not Array#find\n return store.find(id)\n}\n\n/**\n * An in-memory {@link TokenStore} backed by a `Map`. Not persistent across processes - intended for\n * tests, fixtures, and short-lived use. Real persistence is implemented by the application.\n */\nexport class ArrayTokenStore implements TokenStore {\n private readonly tokens = new Map<string, PersonalAccessToken>()\n\n /** Seed the store with an optional initial set of tokens. */\n constructor(initial?: Iterable<PersonalAccessToken>) {\n if (initial !== undefined) {\n for (const token of initial) this.tokens.set(token.id, token)\n }\n }\n\n find(id: string): PersonalAccessToken | undefined {\n return this.tokens.get(id)\n }\n\n save(token: PersonalAccessToken): void {\n this.tokens.set(token.id, token)\n }\n\n delete(id: string): void {\n this.tokens.delete(id)\n }\n\n all(): PersonalAccessToken[] {\n return [...this.tokens.values()]\n }\n\n /** Remove every stored token. Convenience for resetting between tests. */\n flush(): void {\n this.tokens.clear()\n }\n\n /** The number of stored tokens. */\n get size(): number {\n return this.tokens.size\n }\n}\n","/**\n * `TokenGuard` - authenticate a bearer token against a {@link TokenStore}.\n *\n * Given a plaintext `id|secret` bearer token it locates the\n * record by id, verifies the presented secret against the stored SHA-256 hash in CONSTANT TIME\n * ({@link timingSafeEqual}, length-guarded so unequal lengths never throw and never leak timing),\n * rejects expired tokens, and on success stamps `lastUsedAt` from the injected clock.\n */\nimport { timingSafeEqual } from 'node:crypto'\n\nimport { hashSecret, parseToken } from './factory'\nimport { findToken } from './store'\n\nimport type { TokenStore } from './store'\nimport type { PersonalAccessToken } from './token'\n\n/**\n * Constant-time equality of two hex digest strings. Returns `false` immediately when the lengths\n * differ (so `timingSafeEqual`, which throws on unequal-length buffers, is never reached), and\n * otherwise compares the bytes without short-circuiting. Used to compare token hashes.\n */\nexport function hashesMatch(a: string, b: string): boolean {\n const left = Buffer.from(a, 'utf8')\n const right = Buffer.from(b, 'utf8')\n if (left.length !== right.length) return false\n return timingSafeEqual(left, right)\n}\n\n/**\n * Authenticates personal access tokens. Construct with a {@link TokenStore} and, optionally, a\n * clock seam (epoch ms) used to test expiry and stamp `lastUsedAt`.\n */\nexport class TokenGuard {\n private readonly store: TokenStore\n private readonly clock: () => number\n\n /**\n * @param store The token repository to look records up in.\n * @param clock Returns the current time in epoch ms; defaults to `Date.now`. Injectable for tests.\n */\n constructor(store: TokenStore, clock?: () => number) {\n this.store = store\n this.clock = clock ?? Date.now\n }\n\n /**\n * Resolve a plaintext bearer token to its record, or `null` if it is malformed, unknown, the\n * secret does not match (constant-time), or it has expired. On success the record's `lastUsedAt`\n * is set to the current clock time and persisted. The Sanctum token-resolution equivalent.\n */\n authenticate(bearer: string): PersonalAccessToken | null {\n const parts = parseToken(bearer)\n if (parts === null) return null\n const { id, secret } = parts\n\n const token = findToken(this.store, id)\n if (token === undefined) return null\n\n if (!hashesMatch(hashSecret(secret), token.tokenHash)) return null\n\n const now = this.clock()\n if (token.isExpired(now)) return null\n\n token.lastUsedAt = now\n this.store.save(token)\n return token\n }\n\n /**\n * Resolve a bearer token to the id of its owning model (`tokenable_id`), or `null` if the token\n * is invalid or carries no owner. Convenience over {@link authenticate} for guards that only need\n * the user id.\n */\n authenticateToken(bearer: string): string | number | null {\n const token = this.authenticate(bearer)\n if (token === null) return null\n return token.tokenableId ?? null\n }\n\n /** Whether `bearer` resolves to a valid, unexpired token. */\n check(bearer: string): boolean {\n return this.authenticate(bearer) !== null\n }\n}\n","/**\n * `HasApiTokens`, as a helper bound to a\n * {@link TokenStore} and a tokenable owner.\n *\n * Plinth has no PHP traits, so instead of mixing methods into a model class this returns a small\n * object whose `createToken` / `tokens` / `tokenCan` are pre-bound to one owner. The owner's id and\n * (optional) morph type are stamped onto every token it issues, and `tokens()` lists only that\n * owner's tokens.\n */\nimport { createToken } from './factory'\nimport { WILDCARD_ABILITY } from './token'\n\nimport type { CreateTokenSeams, NewAccessToken } from './factory'\nimport type { TokenStore } from './store'\nimport type { PersonalAccessToken } from './token'\n\n/** The owning model of a set of tokens - its primary key and optional morph type. */\nexport interface Tokenable {\n /** The owner's primary key, stamped as `tokenableId` on issued tokens. */\n id: string | number\n /** The owner's morph type/name, stamped as `tokenableType` on issued tokens. */\n type?: string\n}\n\n/** The per-token inputs accepted by {@link HasApiTokens.createToken} (owner is already bound). */\nexport interface HasApiTokensCreateOptions {\n /** A human-readable name for the token. */\n name: string\n /** The abilities to grant; defaults to `['*']`. */\n abilities?: string[]\n /** Epoch milliseconds when the token should expire; omit for a non-expiring token. */\n expiresAt?: number\n}\n\n/** The owner-bound token API returned by {@link hasApiTokens}. */\nexport interface HasApiTokens {\n /** Issue a token for the bound owner, persisting it and returning the one-time plaintext. */\n createToken(options: HasApiTokensCreateOptions, seams?: CreateTokenSeams): NewAccessToken\n /** Every stored token belonging to the bound owner. */\n tokens(): PersonalAccessToken[]\n /** Whether any of the owner's tokens grants `ability` (wildcard `'*'` counts). */\n tokenCan(ability: string): boolean\n}\n\n/** Whether `token` belongs to `owner` (matching id and, when set, morph type). */\nfunction ownedBy(token: PersonalAccessToken, owner: Tokenable): boolean {\n if (token.tokenableId !== owner.id) return false\n if (owner.type === undefined) return true\n return token.tokenableType === owner.type\n}\n\n/**\n * Bind the token API to a `store` and a tokenable `owner`. Tokens issued via the returned object are stamped with the owner's id/type, and\n * {@link HasApiTokens.tokens} / {@link HasApiTokens.tokenCan} are scoped to that owner.\n */\nexport function hasApiTokens(store: TokenStore, owner: Tokenable): HasApiTokens {\n return {\n createToken(options: HasApiTokensCreateOptions, seams?: CreateTokenSeams): NewAccessToken {\n const base = {\n name: options.name,\n tokenableId: owner.id,\n } as Parameters<typeof createToken>[1]\n if (options.abilities !== undefined) base.abilities = options.abilities\n if (options.expiresAt !== undefined) base.expiresAt = options.expiresAt\n if (owner.type !== undefined) base.tokenableType = owner.type\n return createToken(store, base, seams)\n },\n tokens(): PersonalAccessToken[] {\n return store.all().filter((token) => ownedBy(token, owner))\n },\n tokenCan(ability: string): boolean {\n return store\n .all()\n .some(\n (token) =>\n ownedBy(token, owner) &&\n (token.abilities.includes(WILDCARD_ABILITY) || token.abilities.includes(ability)),\n )\n },\n }\n}\n","/**\n * @plinthjs/api-tokens - API token authentication.\n *\n * Stateless bearer-token auth with zero dependencies beyond `node:crypto` and `@plinthjs/support`.\n * Issue a token with {@link createToken} (the plaintext is returned ONCE; only its SHA-256 hash is\n * stored), persist it through a {@link TokenStore} ({@link ArrayTokenStore} ships in-memory), and\n * authenticate incoming bearer tokens with {@link TokenGuard}, which verifies the secret in\n * constant time and honours per-token {@link PersonalAccessToken.can | abilities} and expiry.\n *\n * TOKEN SCHEME: plaintext = `${id}|${secret}`; the stored hash is `sha256(secret)` in hex - the\n * secret being only the part AFTER the `|`, exactly as Sanctum hashes it.\n */\n\n/** The Plinth version this build of `sanctum` ships with. */\nexport const VERSION = '0.1.0'\n\nexport {\n type CreateTokenOptions,\n type CreateTokenSeams,\n createToken,\n hashSecret,\n issueToken,\n type NewAccessToken,\n parseToken,\n TOKEN_SEPARATOR,\n} from './factory'\nexport { TokenGuard, hashesMatch } from './guard'\nexport {\n type HasApiTokens,\n hasApiTokens,\n type HasApiTokensCreateOptions,\n type Tokenable,\n} from './has-api-tokens'\nexport { ArrayTokenStore, findToken, type TokenStore } from './store'\nexport { PersonalAccessToken, type PersonalAccessTokenAttributes, WILDCARD_ABILITY } from './token'\n"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -3,19 +3,19 @@
|
|
|
3
3
|
*
|
|
4
4
|
* A record of an issued API token. The plaintext token is NEVER stored; only its SHA-256 hash
|
|
5
5
|
* ({@link PersonalAccessToken.tokenHash}) is. A token also carries an ability list that scopes what
|
|
6
|
-
* it may do
|
|
6
|
+
* it may do - {@link PersonalAccessToken.can} mirrors Sanctum's `tokenCan()`, where the wildcard
|
|
7
7
|
* `'*'` grants every ability and any other ability requires an exact string match.
|
|
8
8
|
*/
|
|
9
9
|
/** The wildcard ability that grants every permission, as in Sanctum. */
|
|
10
10
|
declare const WILDCARD_ABILITY = "*";
|
|
11
11
|
/**
|
|
12
|
-
* The persisted shape of a personal access token
|
|
12
|
+
* The persisted shape of a personal access token - the columns of Sanctum's
|
|
13
13
|
* `personal_access_tokens` table. The plaintext is intentionally absent: only {@link tokenHash} is
|
|
14
14
|
* kept. Optional columns are omitted entirely when unset (never present-but-`undefined`) so the
|
|
15
15
|
* record round-trips cleanly under `exactOptionalPropertyTypes`.
|
|
16
16
|
*/
|
|
17
17
|
interface PersonalAccessTokenAttributes {
|
|
18
|
-
/** The token id
|
|
18
|
+
/** The token id - the part before the `|` in the plaintext, used to look the record up. */
|
|
19
19
|
id: string;
|
|
20
20
|
/** A human-readable name for the token (e.g. the device or integration it was issued for). */
|
|
21
21
|
name: string;
|
|
@@ -52,7 +52,7 @@ declare class PersonalAccessToken implements PersonalAccessTokenAttributes {
|
|
|
52
52
|
readonly tokenableId?: string | number;
|
|
53
53
|
/** @see PersonalAccessTokenAttributes.tokenableType */
|
|
54
54
|
readonly tokenableType?: string;
|
|
55
|
-
/** @see PersonalAccessTokenAttributes.lastUsedAt
|
|
55
|
+
/** @see PersonalAccessTokenAttributes.lastUsedAt - mutable: refreshed by the guard on auth. */
|
|
56
56
|
lastUsedAt?: number;
|
|
57
57
|
/** @see PersonalAccessTokenAttributes.expiresAt */
|
|
58
58
|
readonly expiresAt?: number;
|
|
@@ -75,7 +75,7 @@ declare class PersonalAccessToken implements PersonalAccessTokenAttributes {
|
|
|
75
75
|
}
|
|
76
76
|
|
|
77
77
|
/**
|
|
78
|
-
* `TokenStore`
|
|
78
|
+
* `TokenStore` - the persistence seam for personal access tokens.
|
|
79
79
|
*
|
|
80
80
|
* Sanctum stores tokens in a database table; Plinth keeps the framework dependency-free, so the
|
|
81
81
|
* store is an interface the application implements against its own ORM. {@link ArrayTokenStore} is
|
|
@@ -83,7 +83,7 @@ declare class PersonalAccessToken implements PersonalAccessTokenAttributes {
|
|
|
83
83
|
*/
|
|
84
84
|
|
|
85
85
|
/**
|
|
86
|
-
* The seam between the guard/factory and however tokens are persisted
|
|
86
|
+
* The seam between the guard/factory and however tokens are persisted - the Sanctum
|
|
87
87
|
* `personal_access_tokens` repository equivalent. Lookups are by token id (the part before the `|`).
|
|
88
88
|
*/
|
|
89
89
|
interface TokenStore {
|
|
@@ -103,7 +103,7 @@ interface TokenStore {
|
|
|
103
103
|
*/
|
|
104
104
|
declare function findToken(store: TokenStore, id: string): PersonalAccessToken | undefined;
|
|
105
105
|
/**
|
|
106
|
-
* An in-memory {@link TokenStore} backed by a `Map`. Not persistent across processes
|
|
106
|
+
* An in-memory {@link TokenStore} backed by a `Map`. Not persistent across processes - intended for
|
|
107
107
|
* tests, fixtures, and short-lived use. Real persistence is implemented by the application.
|
|
108
108
|
*/
|
|
109
109
|
declare class ArrayTokenStore implements TokenStore {
|
|
@@ -124,7 +124,7 @@ declare class ArrayTokenStore implements TokenStore {
|
|
|
124
124
|
declare const TOKEN_SEPARATOR = "|";
|
|
125
125
|
/**
|
|
126
126
|
* Hash the secret portion of a token with SHA-256, returning the lowercase hex digest. This is the
|
|
127
|
-
* canonical hashing rule
|
|
127
|
+
* canonical hashing rule - it takes the SECRET ONLY (never the `id|` prefix), matching Sanctum, and
|
|
128
128
|
* is shared by issuance and verification so the two stay in lockstep.
|
|
129
129
|
*/
|
|
130
130
|
declare function hashSecret(secret: string): string;
|
|
@@ -137,7 +137,7 @@ declare function parseToken(plainTextToken: string): {
|
|
|
137
137
|
id: string;
|
|
138
138
|
secret: string;
|
|
139
139
|
} | null;
|
|
140
|
-
/** Options for {@link createToken}
|
|
140
|
+
/** Options for {@link createToken} - the named parameters of Sanctum's `createToken`. */
|
|
141
141
|
interface CreateTokenOptions {
|
|
142
142
|
/** A human-readable name for the token. */
|
|
143
143
|
name: string;
|
|
@@ -161,11 +161,11 @@ interface CreateTokenSeams {
|
|
|
161
161
|
}
|
|
162
162
|
/**
|
|
163
163
|
* The result of issuing a token. {@link plainTextToken} is the full `id|secret` string and is
|
|
164
|
-
* returned EXACTLY ONCE
|
|
164
|
+
* returned EXACTLY ONCE - it is never recoverable from {@link accessToken}, which holds only the
|
|
165
165
|
* hash.
|
|
166
166
|
*/
|
|
167
167
|
interface NewAccessToken {
|
|
168
|
-
/** The persisted record (hash only
|
|
168
|
+
/** The persisted record (hash only - no plaintext). */
|
|
169
169
|
accessToken: PersonalAccessToken;
|
|
170
170
|
/** The full plaintext token to hand to the client this one time. */
|
|
171
171
|
plainTextToken: string;
|
|
@@ -212,7 +212,7 @@ declare class TokenGuard {
|
|
|
212
212
|
check(bearer: string): boolean;
|
|
213
213
|
}
|
|
214
214
|
|
|
215
|
-
/** The owning model of a set of tokens
|
|
215
|
+
/** The owning model of a set of tokens - its primary key and optional morph type. */
|
|
216
216
|
interface Tokenable {
|
|
217
217
|
/** The owner's primary key, stamped as `tokenableId` on issued tokens. */
|
|
218
218
|
id: string | number;
|
|
@@ -244,7 +244,7 @@ interface HasApiTokens {
|
|
|
244
244
|
declare function hasApiTokens(store: TokenStore, owner: Tokenable): HasApiTokens;
|
|
245
245
|
|
|
246
246
|
/**
|
|
247
|
-
* @plinthjs/api-tokens
|
|
247
|
+
* @plinthjs/api-tokens - API token authentication.
|
|
248
248
|
*
|
|
249
249
|
* Stateless bearer-token auth with zero dependencies beyond `node:crypto` and `@plinthjs/support`.
|
|
250
250
|
* Issue a token with {@link createToken} (the plaintext is returned ONCE; only its SHA-256 hash is
|
|
@@ -252,7 +252,7 @@ declare function hasApiTokens(store: TokenStore, owner: Tokenable): HasApiTokens
|
|
|
252
252
|
* authenticate incoming bearer tokens with {@link TokenGuard}, which verifies the secret in
|
|
253
253
|
* constant time and honours per-token {@link PersonalAccessToken.can | abilities} and expiry.
|
|
254
254
|
*
|
|
255
|
-
* TOKEN SCHEME: plaintext = `${id}|${secret}`; the stored hash is `sha256(secret)` in hex
|
|
255
|
+
* TOKEN SCHEME: plaintext = `${id}|${secret}`; the stored hash is `sha256(secret)` in hex - the
|
|
256
256
|
* secret being only the part AFTER the `|`, exactly as Sanctum hashes it.
|
|
257
257
|
*/
|
|
258
258
|
/** The Plinth version this build of `sanctum` ships with. */
|
package/dist/index.d.ts
CHANGED
|
@@ -3,19 +3,19 @@
|
|
|
3
3
|
*
|
|
4
4
|
* A record of an issued API token. The plaintext token is NEVER stored; only its SHA-256 hash
|
|
5
5
|
* ({@link PersonalAccessToken.tokenHash}) is. A token also carries an ability list that scopes what
|
|
6
|
-
* it may do
|
|
6
|
+
* it may do - {@link PersonalAccessToken.can} mirrors Sanctum's `tokenCan()`, where the wildcard
|
|
7
7
|
* `'*'` grants every ability and any other ability requires an exact string match.
|
|
8
8
|
*/
|
|
9
9
|
/** The wildcard ability that grants every permission, as in Sanctum. */
|
|
10
10
|
declare const WILDCARD_ABILITY = "*";
|
|
11
11
|
/**
|
|
12
|
-
* The persisted shape of a personal access token
|
|
12
|
+
* The persisted shape of a personal access token - the columns of Sanctum's
|
|
13
13
|
* `personal_access_tokens` table. The plaintext is intentionally absent: only {@link tokenHash} is
|
|
14
14
|
* kept. Optional columns are omitted entirely when unset (never present-but-`undefined`) so the
|
|
15
15
|
* record round-trips cleanly under `exactOptionalPropertyTypes`.
|
|
16
16
|
*/
|
|
17
17
|
interface PersonalAccessTokenAttributes {
|
|
18
|
-
/** The token id
|
|
18
|
+
/** The token id - the part before the `|` in the plaintext, used to look the record up. */
|
|
19
19
|
id: string;
|
|
20
20
|
/** A human-readable name for the token (e.g. the device or integration it was issued for). */
|
|
21
21
|
name: string;
|
|
@@ -52,7 +52,7 @@ declare class PersonalAccessToken implements PersonalAccessTokenAttributes {
|
|
|
52
52
|
readonly tokenableId?: string | number;
|
|
53
53
|
/** @see PersonalAccessTokenAttributes.tokenableType */
|
|
54
54
|
readonly tokenableType?: string;
|
|
55
|
-
/** @see PersonalAccessTokenAttributes.lastUsedAt
|
|
55
|
+
/** @see PersonalAccessTokenAttributes.lastUsedAt - mutable: refreshed by the guard on auth. */
|
|
56
56
|
lastUsedAt?: number;
|
|
57
57
|
/** @see PersonalAccessTokenAttributes.expiresAt */
|
|
58
58
|
readonly expiresAt?: number;
|
|
@@ -75,7 +75,7 @@ declare class PersonalAccessToken implements PersonalAccessTokenAttributes {
|
|
|
75
75
|
}
|
|
76
76
|
|
|
77
77
|
/**
|
|
78
|
-
* `TokenStore`
|
|
78
|
+
* `TokenStore` - the persistence seam for personal access tokens.
|
|
79
79
|
*
|
|
80
80
|
* Sanctum stores tokens in a database table; Plinth keeps the framework dependency-free, so the
|
|
81
81
|
* store is an interface the application implements against its own ORM. {@link ArrayTokenStore} is
|
|
@@ -83,7 +83,7 @@ declare class PersonalAccessToken implements PersonalAccessTokenAttributes {
|
|
|
83
83
|
*/
|
|
84
84
|
|
|
85
85
|
/**
|
|
86
|
-
* The seam between the guard/factory and however tokens are persisted
|
|
86
|
+
* The seam between the guard/factory and however tokens are persisted - the Sanctum
|
|
87
87
|
* `personal_access_tokens` repository equivalent. Lookups are by token id (the part before the `|`).
|
|
88
88
|
*/
|
|
89
89
|
interface TokenStore {
|
|
@@ -103,7 +103,7 @@ interface TokenStore {
|
|
|
103
103
|
*/
|
|
104
104
|
declare function findToken(store: TokenStore, id: string): PersonalAccessToken | undefined;
|
|
105
105
|
/**
|
|
106
|
-
* An in-memory {@link TokenStore} backed by a `Map`. Not persistent across processes
|
|
106
|
+
* An in-memory {@link TokenStore} backed by a `Map`. Not persistent across processes - intended for
|
|
107
107
|
* tests, fixtures, and short-lived use. Real persistence is implemented by the application.
|
|
108
108
|
*/
|
|
109
109
|
declare class ArrayTokenStore implements TokenStore {
|
|
@@ -124,7 +124,7 @@ declare class ArrayTokenStore implements TokenStore {
|
|
|
124
124
|
declare const TOKEN_SEPARATOR = "|";
|
|
125
125
|
/**
|
|
126
126
|
* Hash the secret portion of a token with SHA-256, returning the lowercase hex digest. This is the
|
|
127
|
-
* canonical hashing rule
|
|
127
|
+
* canonical hashing rule - it takes the SECRET ONLY (never the `id|` prefix), matching Sanctum, and
|
|
128
128
|
* is shared by issuance and verification so the two stay in lockstep.
|
|
129
129
|
*/
|
|
130
130
|
declare function hashSecret(secret: string): string;
|
|
@@ -137,7 +137,7 @@ declare function parseToken(plainTextToken: string): {
|
|
|
137
137
|
id: string;
|
|
138
138
|
secret: string;
|
|
139
139
|
} | null;
|
|
140
|
-
/** Options for {@link createToken}
|
|
140
|
+
/** Options for {@link createToken} - the named parameters of Sanctum's `createToken`. */
|
|
141
141
|
interface CreateTokenOptions {
|
|
142
142
|
/** A human-readable name for the token. */
|
|
143
143
|
name: string;
|
|
@@ -161,11 +161,11 @@ interface CreateTokenSeams {
|
|
|
161
161
|
}
|
|
162
162
|
/**
|
|
163
163
|
* The result of issuing a token. {@link plainTextToken} is the full `id|secret` string and is
|
|
164
|
-
* returned EXACTLY ONCE
|
|
164
|
+
* returned EXACTLY ONCE - it is never recoverable from {@link accessToken}, which holds only the
|
|
165
165
|
* hash.
|
|
166
166
|
*/
|
|
167
167
|
interface NewAccessToken {
|
|
168
|
-
/** The persisted record (hash only
|
|
168
|
+
/** The persisted record (hash only - no plaintext). */
|
|
169
169
|
accessToken: PersonalAccessToken;
|
|
170
170
|
/** The full plaintext token to hand to the client this one time. */
|
|
171
171
|
plainTextToken: string;
|
|
@@ -212,7 +212,7 @@ declare class TokenGuard {
|
|
|
212
212
|
check(bearer: string): boolean;
|
|
213
213
|
}
|
|
214
214
|
|
|
215
|
-
/** The owning model of a set of tokens
|
|
215
|
+
/** The owning model of a set of tokens - its primary key and optional morph type. */
|
|
216
216
|
interface Tokenable {
|
|
217
217
|
/** The owner's primary key, stamped as `tokenableId` on issued tokens. */
|
|
218
218
|
id: string | number;
|
|
@@ -244,7 +244,7 @@ interface HasApiTokens {
|
|
|
244
244
|
declare function hasApiTokens(store: TokenStore, owner: Tokenable): HasApiTokens;
|
|
245
245
|
|
|
246
246
|
/**
|
|
247
|
-
* @plinthjs/api-tokens
|
|
247
|
+
* @plinthjs/api-tokens - API token authentication.
|
|
248
248
|
*
|
|
249
249
|
* Stateless bearer-token auth with zero dependencies beyond `node:crypto` and `@plinthjs/support`.
|
|
250
250
|
* Issue a token with {@link createToken} (the plaintext is returned ONCE; only its SHA-256 hash is
|
|
@@ -252,7 +252,7 @@ declare function hasApiTokens(store: TokenStore, owner: Tokenable): HasApiTokens
|
|
|
252
252
|
* authenticate incoming bearer tokens with {@link TokenGuard}, which verifies the secret in
|
|
253
253
|
* constant time and honours per-token {@link PersonalAccessToken.can | abilities} and expiry.
|
|
254
254
|
*
|
|
255
|
-
* TOKEN SCHEME: plaintext = `${id}|${secret}`; the stored hash is `sha256(secret)` in hex
|
|
255
|
+
* TOKEN SCHEME: plaintext = `${id}|${secret}`; the stored hash is `sha256(secret)` in hex - the
|
|
256
256
|
* secret being only the part AFTER the `|`, exactly as Sanctum hashes it.
|
|
257
257
|
*/
|
|
258
258
|
/** The Plinth version this build of `sanctum` ships with. */
|
package/dist/index.js
CHANGED
|
@@ -18,7 +18,7 @@ var PersonalAccessToken = class _PersonalAccessToken {
|
|
|
18
18
|
tokenableId;
|
|
19
19
|
/** @see PersonalAccessTokenAttributes.tokenableType */
|
|
20
20
|
tokenableType;
|
|
21
|
-
/** @see PersonalAccessTokenAttributes.lastUsedAt
|
|
21
|
+
/** @see PersonalAccessTokenAttributes.lastUsedAt - mutable: refreshed by the guard on auth. */
|
|
22
22
|
lastUsedAt;
|
|
23
23
|
/** @see PersonalAccessTokenAttributes.expiresAt */
|
|
24
24
|
expiresAt;
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/token.ts","../src/factory.ts","../src/store.ts","../src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AAA,EAAW,IAAA,CAAK,gBAAgB,KAAA,CAAM,IAAA;AACzD,MAAA,OAAO,WAAA,CAAY,KAAA,EAAO,IAAA,EAAM,KAAK,CAAA;AAAA,IACvC,CAAA;AAAA,IACA,MAAA,GAAgC;AAC9B,MAAA,OAAO,KAAA,CAAM,KAAI,CAAE,MAAA,CAAO,CAAC,KAAA,KAAU,OAAA,CAAQ,KAAA,EAAO,KAAK,CAAC,CAAA;AAAA,IAC5D,CAAA;AAAA,IACA,SAAS,OAAA,EAA0B;AACjC,MAAA,OAAO,KAAA,CACJ,KAAI,CACJ,IAAA;AAAA,QACC,CAAC,KAAA,KACC,OAAA,CAAQ,KAAA,EAAO,KAAK,CAAA,KACnB,KAAA,CAAM,SAAA,CAAU,QAAA,CAAS,gBAAgB,CAAA,IAAK,KAAA,CAAM,SAAA,CAAU,SAAS,OAAO,CAAA;AAAA,OACnF;AAAA,IACJ;AAAA,GACF;AACF;;;AClEO,IAAM,OAAA,GAAU","file":"index.js","sourcesContent":["/**\n * `PersonalAccessToken`.\n *\n * A record of an issued API token. The plaintext token is NEVER stored; only its SHA-256 hash\n * ({@link PersonalAccessToken.tokenHash}) is. A token also carries an ability list that scopes what\n * it may do — {@link PersonalAccessToken.can} mirrors Sanctum's `tokenCan()`, where the wildcard\n * `'*'` grants every ability and any other ability requires an exact string match.\n */\n\n/** The wildcard ability that grants every permission, as in Sanctum. */\nexport const WILDCARD_ABILITY = '*'\n\n/**\n * The persisted shape of a personal access token — the columns of Sanctum's\n * `personal_access_tokens` table. The plaintext is intentionally absent: only {@link tokenHash} is\n * kept. Optional columns are omitted entirely when unset (never present-but-`undefined`) so the\n * record round-trips cleanly under `exactOptionalPropertyTypes`.\n */\nexport interface PersonalAccessTokenAttributes {\n /** The token id — the part before the `|` in the plaintext, used to look the record up. */\n id: string\n /** A human-readable name for the token (e.g. the device or integration it was issued for). */\n name: string\n /** The lowercase SHA-256 hex digest of the secret (the part of the plaintext after the `|`). */\n tokenHash: string\n /** The abilities granted to the token; `['*']` grants everything. */\n abilities: string[]\n /** The primary key of the owning model (`tokenable_id`), if the token belongs to one. */\n tokenableId?: string | number\n /** The type/morph name of the owning model (`tokenable_type`), if the token belongs to one. */\n tokenableType?: string\n /** Epoch milliseconds when the token was last used to authenticate, if ever. */\n lastUsedAt?: number\n /** Epoch milliseconds when the token expires; absent means it never expires. */\n expiresAt?: number\n /** Epoch milliseconds when the token was created. */\n createdAt: number\n}\n\n/**\n * A personal access token record. Construct directly from attributes, or via\n * {@link PersonalAccessToken.from}. Behaviour ({@link can}/{@link cant}/{@link isExpired}) lives\n * here; persistence lives behind a `TokenStore`.\n */\nexport class PersonalAccessToken implements PersonalAccessTokenAttributes {\n /** @see PersonalAccessTokenAttributes.id */\n readonly id: string\n /** @see PersonalAccessTokenAttributes.name */\n readonly name: string\n /** @see PersonalAccessTokenAttributes.tokenHash */\n readonly tokenHash: string\n /** @see PersonalAccessTokenAttributes.abilities */\n readonly abilities: string[]\n /** @see PersonalAccessTokenAttributes.tokenableId */\n readonly tokenableId?: string | number\n /** @see PersonalAccessTokenAttributes.tokenableType */\n readonly tokenableType?: string\n /** @see PersonalAccessTokenAttributes.lastUsedAt — mutable: refreshed by the guard on auth. */\n lastUsedAt?: number\n /** @see PersonalAccessTokenAttributes.expiresAt */\n readonly expiresAt?: number\n /** @see PersonalAccessTokenAttributes.createdAt */\n readonly createdAt: number\n\n constructor(attributes: PersonalAccessTokenAttributes) {\n this.id = attributes.id\n this.name = attributes.name\n this.tokenHash = attributes.tokenHash\n this.abilities = [...attributes.abilities]\n if (attributes.tokenableId !== undefined) this.tokenableId = attributes.tokenableId\n if (attributes.tokenableType !== undefined) this.tokenableType = attributes.tokenableType\n if (attributes.lastUsedAt !== undefined) this.lastUsedAt = attributes.lastUsedAt\n if (attributes.expiresAt !== undefined) this.expiresAt = attributes.expiresAt\n this.createdAt = attributes.createdAt\n }\n\n /** Build a token from a plain attributes object. The `PersonalAccessToken::make()` equivalent. */\n static from(attributes: PersonalAccessTokenAttributes): PersonalAccessToken {\n return new PersonalAccessToken(attributes)\n }\n\n /**\n * Whether the token is granted `ability`. The wildcard `'*'` ability grants everything; any\n * other ability must match an entry exactly.\n */\n can(ability: string): boolean {\n return this.abilities.includes(WILDCARD_ABILITY) || this.abilities.includes(ability)\n }\n\n /** The negation of {@link can}. */\n cant(ability: string): boolean {\n return !this.can(ability)\n }\n\n /** Whether the token has expired relative to `now` (epoch ms). Never-expiring tokens are false. */\n isExpired(now: number): boolean {\n return this.expiresAt !== undefined && this.expiresAt <= now\n }\n\n /** A plain snapshot of the record, omitting any unset optional fields. */\n toAttributes(): PersonalAccessTokenAttributes {\n const attributes: PersonalAccessTokenAttributes = {\n id: this.id,\n name: this.name,\n tokenHash: this.tokenHash,\n abilities: [...this.abilities],\n createdAt: this.createdAt,\n }\n if (this.tokenableId !== undefined) attributes.tokenableId = this.tokenableId\n if (this.tokenableType !== undefined) attributes.tokenableType = this.tokenableType\n if (this.lastUsedAt !== undefined) attributes.lastUsedAt = this.lastUsedAt\n if (this.expiresAt !== undefined) attributes.expiresAt = this.expiresAt\n return attributes\n }\n}\n","/**\n * Token issuance and the plaintext/hash scheme — the Sanctum `HasApiTokens::createToken`\n * equivalent.\n *\n * TOKEN FORMAT (Sanctum parity):\n * plaintext = `${id}|${secret}`\n * where `id` is the stored row id (here a UUID v4) and `secret` is `randomBytes(40)` rendered as\n * hex. The two are joined by a single `|`. On authentication the client sends the whole plaintext\n * as the bearer token; the id locates the row and the secret is verified against the hash.\n *\n * HASHING (Sanctum parity): Sanctum hashes ONLY the secret — the part AFTER the `|` — with SHA-256\n * and stores the lowercase hex digest. It does NOT hash the `id|` prefix. {@link hashSecret} is the\n * single definition of that rule and is used by both issuance and verification so they can never\n * drift. SHA-256 (not a slow KDF) is appropriate here because the secret is high-entropy random,\n * not a user-chosen password.\n */\nimport { createHash, randomBytes } from 'node:crypto'\n\nimport { uuid } from '@plinthjs/support'\n\nimport { PersonalAccessToken } from './token'\n\nimport type { TokenStore } from './store'\n\n/** The default abilities granted when none are specified — full access, as in Sanctum. */\nconst DEFAULT_ABILITIES: readonly string[] = ['*']\n\n/** Number of random bytes in the secret; 40 bytes → an 80-char hex secret (Sanctum uses ~40). */\nconst SECRET_BYTES = 40\n\n/** The separator between the id and the secret in a plaintext token. */\nexport const TOKEN_SEPARATOR = '|'\n\n/**\n * Hash the secret portion of a token with SHA-256, returning the lowercase hex digest. This is the\n * canonical hashing rule — it takes the SECRET ONLY (never the `id|` prefix), matching Sanctum, and\n * is shared by issuance and verification so the two stay in lockstep.\n */\nexport function hashSecret(secret: string): string {\n return createHash('sha256').update(secret).digest('hex')\n}\n\n/**\n * Split a plaintext bearer token into its `{ id, secret }` parts, or `null` if it is not in the\n * `id|secret` form. The id is everything before the first `|`; the secret is everything after, so a\n * secret may itself contain `|` without ambiguity. Empty id or empty secret yields `null`.\n */\nexport function parseToken(plainTextToken: string): { id: string; secret: string } | null {\n const index = plainTextToken.indexOf(TOKEN_SEPARATOR)\n if (index <= 0) return null\n const id = plainTextToken.slice(0, index)\n const secret = plainTextToken.slice(index + 1)\n if (secret.length === 0) return null\n return { id, secret }\n}\n\n/** Generate a fresh high-entropy secret as a hex string. */\nfunction generateSecret(): string {\n return randomBytes(SECRET_BYTES).toString('hex')\n}\n\n/** Options for {@link createToken} — the named parameters of Sanctum's `createToken`. */\nexport interface CreateTokenOptions {\n /** A human-readable name for the token. */\n name: string\n /** The abilities to grant; defaults to `['*']` (full access). */\n abilities?: string[]\n /** Epoch milliseconds when the token should expire; omit for a non-expiring token. */\n expiresAt?: number\n /** The owning model's primary key (`tokenable_id`). */\n tokenableId?: string | number\n /** The owning model's type/morph name (`tokenable_type`). */\n tokenableType?: string\n}\n\n/** Overridable seams for {@link createToken}, primarily for deterministic tests. */\nexport interface CreateTokenSeams {\n /** Clock used for `createdAt`; defaults to `Date.now`. Epoch milliseconds. */\n now?: () => number\n /** Id generator; defaults to a UUID v4. */\n generateId?: () => string\n /** Secret generator; defaults to 40 random bytes as hex. */\n generateSecret?: () => string\n}\n\n/**\n * The result of issuing a token. {@link plainTextToken} is the full `id|secret` string and is\n * returned EXACTLY ONCE — it is never recoverable from {@link accessToken}, which holds only the\n * hash.\n */\nexport interface NewAccessToken {\n /** The persisted record (hash only — no plaintext). */\n accessToken: PersonalAccessToken\n /** The full plaintext token to hand to the client this one time. */\n plainTextToken: string\n}\n\n/**\n * Issue a new personal access token, persist its record (hash only) to `store`, and return the\n * record together with the one-time plaintext.\n */\nexport function createToken(\n store: TokenStore,\n options: CreateTokenOptions,\n seams?: CreateTokenSeams,\n): NewAccessToken {\n const now = (seams?.now ?? Date.now)()\n const id = (seams?.generateId ?? uuid)()\n const secret = (seams?.generateSecret ?? generateSecret)()\n const abilities = options.abilities ?? [...DEFAULT_ABILITIES]\n\n const attributes = {\n id,\n name: options.name,\n tokenHash: hashSecret(secret),\n abilities,\n createdAt: now,\n } as ConstructorParameters<typeof PersonalAccessToken>[0]\n if (options.tokenableId !== undefined) attributes.tokenableId = options.tokenableId\n if (options.tokenableType !== undefined) attributes.tokenableType = options.tokenableType\n if (options.expiresAt !== undefined) attributes.expiresAt = options.expiresAt\n\n const accessToken = new PersonalAccessToken(attributes)\n store.save(accessToken)\n\n return { accessToken, plainTextToken: `${id}${TOKEN_SEPARATOR}${secret}` }\n}\n\n/** Alias for {@link createToken}, matching the `issueToken` naming used elsewhere in Plinth. */\nexport const issueToken: (\n store: TokenStore,\n options: CreateTokenOptions,\n seams?: CreateTokenSeams,\n) => NewAccessToken = createToken\n","/**\n * `TokenStore` — the persistence seam for personal access tokens.\n *\n * Sanctum stores tokens in a database table; Plinth keeps the framework dependency-free, so the\n * store is an interface the application implements against its own ORM. {@link ArrayTokenStore} is\n * an in-memory implementation suitable for tests and ephemeral use.\n */\nimport type { PersonalAccessToken } from './token'\n\n/**\n * The seam between the guard/factory and however tokens are persisted — the Sanctum\n * `personal_access_tokens` repository equivalent. Lookups are by token id (the part before the `|`).\n */\nexport interface TokenStore {\n /** Find a token by its id, or `undefined` if none is stored. */\n find(id: string): PersonalAccessToken | undefined\n /** Persist (insert or replace) a token, keyed by its id. */\n save(token: PersonalAccessToken): void\n /** Delete the token with the given id, if present. The revoke equivalent. */\n delete(id: string): void\n /** Every stored token. */\n all(): PersonalAccessToken[]\n}\n\n/**\n * Free-function form of {@link TokenStore.find}: look a token up by id, or `undefined`. Exists so\n * callers can read a store without tripping `unicorn/no-array-callback-reference`, which cannot tell\n * a repository's `.find(id)` apart from `Array.prototype.find` (the collision is resolved here once).\n */\nexport function findToken(store: TokenStore, id: string): PersonalAccessToken | undefined {\n // eslint-disable-next-line unicorn/no-array-callback-reference -- repository lookup, not Array#find\n return store.find(id)\n}\n\n/**\n * An in-memory {@link TokenStore} backed by a `Map`. Not persistent across processes — intended for\n * tests, fixtures, and short-lived use. Real persistence is implemented by the application.\n */\nexport class ArrayTokenStore implements TokenStore {\n private readonly tokens = new Map<string, PersonalAccessToken>()\n\n /** Seed the store with an optional initial set of tokens. */\n constructor(initial?: Iterable<PersonalAccessToken>) {\n if (initial !== undefined) {\n for (const token of initial) this.tokens.set(token.id, token)\n }\n }\n\n find(id: string): PersonalAccessToken | undefined {\n return this.tokens.get(id)\n }\n\n save(token: PersonalAccessToken): void {\n this.tokens.set(token.id, token)\n }\n\n delete(id: string): void {\n this.tokens.delete(id)\n }\n\n all(): PersonalAccessToken[] {\n return [...this.tokens.values()]\n }\n\n /** Remove every stored token. Convenience for resetting between tests. */\n flush(): void {\n this.tokens.clear()\n }\n\n /** The number of stored tokens. */\n get size(): number {\n return this.tokens.size\n }\n}\n","/**\n * `TokenGuard` — authenticate a bearer token against a {@link TokenStore}.\n *\n * Given a plaintext `id|secret` bearer token it locates the\n * record by id, verifies the presented secret against the stored SHA-256 hash in CONSTANT TIME\n * ({@link timingSafeEqual}, length-guarded so unequal lengths never throw and never leak timing),\n * rejects expired tokens, and on success stamps `lastUsedAt` from the injected clock.\n */\nimport { timingSafeEqual } from 'node:crypto'\n\nimport { hashSecret, parseToken } from './factory'\nimport { findToken } from './store'\n\nimport type { TokenStore } from './store'\nimport type { PersonalAccessToken } from './token'\n\n/**\n * Constant-time equality of two hex digest strings. Returns `false` immediately when the lengths\n * differ (so `timingSafeEqual`, which throws on unequal-length buffers, is never reached), and\n * otherwise compares the bytes without short-circuiting. Used to compare token hashes.\n */\nexport function hashesMatch(a: string, b: string): boolean {\n const left = Buffer.from(a, 'utf8')\n const right = Buffer.from(b, 'utf8')\n if (left.length !== right.length) return false\n return timingSafeEqual(left, right)\n}\n\n/**\n * Authenticates personal access tokens. Construct with a {@link TokenStore} and, optionally, a\n * clock seam (epoch ms) used to test expiry and stamp `lastUsedAt`.\n */\nexport class TokenGuard {\n private readonly store: TokenStore\n private readonly clock: () => number\n\n /**\n * @param store The token repository to look records up in.\n * @param clock Returns the current time in epoch ms; defaults to `Date.now`. Injectable for tests.\n */\n constructor(store: TokenStore, clock?: () => number) {\n this.store = store\n this.clock = clock ?? Date.now\n }\n\n /**\n * Resolve a plaintext bearer token to its record, or `null` if it is malformed, unknown, the\n * secret does not match (constant-time), or it has expired. On success the record's `lastUsedAt`\n * is set to the current clock time and persisted. The Sanctum token-resolution equivalent.\n */\n authenticate(bearer: string): PersonalAccessToken | null {\n const parts = parseToken(bearer)\n if (parts === null) return null\n const { id, secret } = parts\n\n const token = findToken(this.store, id)\n if (token === undefined) return null\n\n if (!hashesMatch(hashSecret(secret), token.tokenHash)) return null\n\n const now = this.clock()\n if (token.isExpired(now)) return null\n\n token.lastUsedAt = now\n this.store.save(token)\n return token\n }\n\n /**\n * Resolve a bearer token to the id of its owning model (`tokenable_id`), or `null` if the token\n * is invalid or carries no owner. Convenience over {@link authenticate} for guards that only need\n * the user id.\n */\n authenticateToken(bearer: string): string | number | null {\n const token = this.authenticate(bearer)\n if (token === null) return null\n return token.tokenableId ?? null\n }\n\n /** Whether `bearer` resolves to a valid, unexpired token. */\n check(bearer: string): boolean {\n return this.authenticate(bearer) !== null\n }\n}\n","/**\n * `HasApiTokens`, as a helper bound to a\n * {@link TokenStore} and a tokenable owner.\n *\n * Plinth has no PHP traits, so instead of mixing methods into a model class this returns a small\n * object whose `createToken` / `tokens` / `tokenCan` are pre-bound to one owner. The owner's id and\n * (optional) morph type are stamped onto every token it issues, and `tokens()` lists only that\n * owner's tokens.\n */\nimport { createToken } from './factory'\nimport { WILDCARD_ABILITY } from './token'\n\nimport type { CreateTokenSeams, NewAccessToken } from './factory'\nimport type { TokenStore } from './store'\nimport type { PersonalAccessToken } from './token'\n\n/** The owning model of a set of tokens — its primary key and optional morph type. */\nexport interface Tokenable {\n /** The owner's primary key, stamped as `tokenableId` on issued tokens. */\n id: string | number\n /** The owner's morph type/name, stamped as `tokenableType` on issued tokens. */\n type?: string\n}\n\n/** The per-token inputs accepted by {@link HasApiTokens.createToken} (owner is already bound). */\nexport interface HasApiTokensCreateOptions {\n /** A human-readable name for the token. */\n name: string\n /** The abilities to grant; defaults to `['*']`. */\n abilities?: string[]\n /** Epoch milliseconds when the token should expire; omit for a non-expiring token. */\n expiresAt?: number\n}\n\n/** The owner-bound token API returned by {@link hasApiTokens}. */\nexport interface HasApiTokens {\n /** Issue a token for the bound owner, persisting it and returning the one-time plaintext. */\n createToken(options: HasApiTokensCreateOptions, seams?: CreateTokenSeams): NewAccessToken\n /** Every stored token belonging to the bound owner. */\n tokens(): PersonalAccessToken[]\n /** Whether any of the owner's tokens grants `ability` (wildcard `'*'` counts). */\n tokenCan(ability: string): boolean\n}\n\n/** Whether `token` belongs to `owner` (matching id and, when set, morph type). */\nfunction ownedBy(token: PersonalAccessToken, owner: Tokenable): boolean {\n if (token.tokenableId !== owner.id) return false\n if (owner.type === undefined) return true\n return token.tokenableType === owner.type\n}\n\n/**\n * Bind the token API to a `store` and a tokenable `owner`. Tokens issued via the returned object are stamped with the owner's id/type, and\n * {@link HasApiTokens.tokens} / {@link HasApiTokens.tokenCan} are scoped to that owner.\n */\nexport function hasApiTokens(store: TokenStore, owner: Tokenable): HasApiTokens {\n return {\n createToken(options: HasApiTokensCreateOptions, seams?: CreateTokenSeams): NewAccessToken {\n const base = {\n name: options.name,\n tokenableId: owner.id,\n } as Parameters<typeof createToken>[1]\n if (options.abilities !== undefined) base.abilities = options.abilities\n if (options.expiresAt !== undefined) base.expiresAt = options.expiresAt\n if (owner.type !== undefined) base.tokenableType = owner.type\n return createToken(store, base, seams)\n },\n tokens(): PersonalAccessToken[] {\n return store.all().filter((token) => ownedBy(token, owner))\n },\n tokenCan(ability: string): boolean {\n return store\n .all()\n .some(\n (token) =>\n ownedBy(token, owner) &&\n (token.abilities.includes(WILDCARD_ABILITY) || token.abilities.includes(ability)),\n )\n },\n }\n}\n","/**\n * @plinthjs/api-tokens — API token authentication, the Sanctum equivalent.\n *\n * Stateless bearer-token auth with zero dependencies beyond `node:crypto` and `@plinthjs/support`.\n * Issue a token with {@link createToken} (the plaintext is returned ONCE; only its SHA-256 hash is\n * stored), persist it through a {@link TokenStore} ({@link ArrayTokenStore} ships in-memory), and\n * authenticate incoming bearer tokens with {@link TokenGuard}, which verifies the secret in\n * constant time and honours per-token {@link PersonalAccessToken.can | abilities} and expiry.\n *\n * TOKEN SCHEME: plaintext = `${id}|${secret}`; the stored hash is `sha256(secret)` in hex — the\n * secret being only the part AFTER the `|`, exactly as Sanctum hashes it.\n */\n\n/** The Plinth version this build of `sanctum` ships with. */\nexport const VERSION = '0.1.0'\n\nexport {\n type CreateTokenOptions,\n type CreateTokenSeams,\n createToken,\n hashSecret,\n issueToken,\n type NewAccessToken,\n parseToken,\n TOKEN_SEPARATOR,\n} from './factory'\nexport { TokenGuard, hashesMatch } from './guard'\nexport {\n type HasApiTokens,\n hasApiTokens,\n type HasApiTokensCreateOptions,\n type Tokenable,\n} from './has-api-tokens'\nexport { ArrayTokenStore, findToken, type TokenStore } from './store'\nexport { PersonalAccessToken, type PersonalAccessTokenAttributes, WILDCARD_ABILITY } from './token'\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/token.ts","../src/fact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AAM,IAAA,KAAS,MAAA,EAAW,IAAA,CAAK,gBAAgB,KAAA,CAAM,IAAA;AACzD,MAAA,OAAO,WAAA,CAAY,KAAA,EAAO,IAAA,EAAM,KAAK,CAAA;AAAA,IACvC,CAAA;AAAA,IACA,MAAA,GAAgC;AAC9B,MAAA,OAAO,KAAA,CAAM,KAAI,CAAE,MAAA,CAAO,CAAC,KAAA,KAAU,OAAA,CAAQ,KAAA,EAAO,KAAK,CAAC,CAAA;AAAA,IAC5D,CAAA;AAAA,IACA,SAAS,OAAA,EAA0B;AACjC,MAAA,OAAO,KAAA,CACJ,KAAI,CACJ,IAAA;AAAA,QACC,CAAC,KAAA,KACC,OAAA,CAAQ,KAAA,EAAO,KAAK,CAAA,KACnB,KAAA,CAAM,SAAA,CAAU,QAAA,CAAS,gBAAgB,CAAA,IAAK,KAAA,CAAM,SAAA,CAAU,SAAS,OAAO,CAAA;AAAA,OACnF;AAAA,IACJ;AAAA,GACF;AACF;;;AClEO,IAAM,OAAA,GAAU","file":"index.js","sourcesContent":["/**\n * `PersonalAccessToken`.\n *\n * A record of an issued API token. The plaintext token is NEVER stored; only its SHA-256 hash\n * ({@link PersonalAccessToken.tokenHash}) is. A token also carries an ability list that scopes what\n * it may do - {@link PersonalAccessToken.can} mirrors Sanctum's `tokenCan()`, where the wildcard\n * `'*'` grants every ability and any other ability requires an exact string match.\n */\n\n/** The wildcard ability that grants every permission, as in Sanctum. */\nexport const WILDCARD_ABILITY = '*'\n\n/**\n * The persisted shape of a personal access token - the columns of Sanctum's\n * `personal_access_tokens` table. The plaintext is intentionally absent: only {@link tokenHash} is\n * kept. Optional columns are omitted entirely when unset (never present-but-`undefined`) so the\n * record round-trips cleanly under `exactOptionalPropertyTypes`.\n */\nexport interface PersonalAccessTokenAttributes {\n /** The token id - the part before the `|` in the plaintext, used to look the record up. */\n id: string\n /** A human-readable name for the token (e.g. the device or integration it was issued for). */\n name: string\n /** The lowercase SHA-256 hex digest of the secret (the part of the plaintext after the `|`). */\n tokenHash: string\n /** The abilities granted to the token; `['*']` grants everything. */\n abilities: string[]\n /** The primary key of the owning model (`tokenable_id`), if the token belongs to one. */\n tokenableId?: string | number\n /** The type/morph name of the owning model (`tokenable_type`), if the token belongs to one. */\n tokenableType?: string\n /** Epoch milliseconds when the token was last used to authenticate, if ever. */\n lastUsedAt?: number\n /** Epoch milliseconds when the token expires; absent means it never expires. */\n expiresAt?: number\n /** Epoch milliseconds when the token was created. */\n createdAt: number\n}\n\n/**\n * A personal access token record. Construct directly from attributes, or via\n * {@link PersonalAccessToken.from}. Behaviour ({@link can}/{@link cant}/{@link isExpired}) lives\n * here; persistence lives behind a `TokenStore`.\n */\nexport class PersonalAccessToken implements PersonalAccessTokenAttributes {\n /** @see PersonalAccessTokenAttributes.id */\n readonly id: string\n /** @see PersonalAccessTokenAttributes.name */\n readonly name: string\n /** @see PersonalAccessTokenAttributes.tokenHash */\n readonly tokenHash: string\n /** @see PersonalAccessTokenAttributes.abilities */\n readonly abilities: string[]\n /** @see PersonalAccessTokenAttributes.tokenableId */\n readonly tokenableId?: string | number\n /** @see PersonalAccessTokenAttributes.tokenableType */\n readonly tokenableType?: string\n /** @see PersonalAccessTokenAttributes.lastUsedAt - mutable: refreshed by the guard on auth. */\n lastUsedAt?: number\n /** @see PersonalAccessTokenAttributes.expiresAt */\n readonly expiresAt?: number\n /** @see PersonalAccessTokenAttributes.createdAt */\n readonly createdAt: number\n\n constructor(attributes: PersonalAccessTokenAttributes) {\n this.id = attributes.id\n this.name = attributes.name\n this.tokenHash = attributes.tokenHash\n this.abilities = [...attributes.abilities]\n if (attributes.tokenableId !== undefined) this.tokenableId = attributes.tokenableId\n if (attributes.tokenableType !== undefined) this.tokenableType = attributes.tokenableType\n if (attributes.lastUsedAt !== undefined) this.lastUsedAt = attributes.lastUsedAt\n if (attributes.expiresAt !== undefined) this.expiresAt = attributes.expiresAt\n this.createdAt = attributes.createdAt\n }\n\n /** Build a token from a plain attributes object. The `PersonalAccessToken::make()` equivalent. */\n static from(attributes: PersonalAccessTokenAttributes): PersonalAccessToken {\n return new PersonalAccessToken(attributes)\n }\n\n /**\n * Whether the token is granted `ability`. The wildcard `'*'` ability grants everything; any\n * other ability must match an entry exactly.\n */\n can(ability: string): boolean {\n return this.abilities.includes(WILDCARD_ABILITY) || this.abilities.includes(ability)\n }\n\n /** The negation of {@link can}. */\n cant(ability: string): boolean {\n return !this.can(ability)\n }\n\n /** Whether the token has expired relative to `now` (epoch ms). Never-expiring tokens are false. */\n isExpired(now: number): boolean {\n return this.expiresAt !== undefined && this.expiresAt <= now\n }\n\n /** A plain snapshot of the record, omitting any unset optional fields. */\n toAttributes(): PersonalAccessTokenAttributes {\n const attributes: PersonalAccessTokenAttributes = {\n id: this.id,\n name: this.name,\n tokenHash: this.tokenHash,\n abilities: [...this.abilities],\n createdAt: this.createdAt,\n }\n if (this.tokenableId !== undefined) attributes.tokenableId = this.tokenableId\n if (this.tokenableType !== undefined) attributes.tokenableType = this.tokenableType\n if (this.lastUsedAt !== undefined) attributes.lastUsedAt = this.lastUsedAt\n if (this.expiresAt !== undefined) attributes.expiresAt = this.expiresAt\n return attributes\n }\n}\n","/**\n * Token issuance and the plaintext/hash scheme - the Sanctum `HasApiTokens::createToken`\n * equivalent.\n *\n * TOKEN FORMAT (Sanctum parity):\n * plaintext = `${id}|${secret}`\n * where `id` is the stored row id (here a UUID v4) and `secret` is `randomBytes(40)` rendered as\n * hex. The two are joined by a single `|`. On authentication the client sends the whole plaintext\n * as the bearer token; the id locates the row and the secret is verified against the hash.\n *\n * HASHING (Sanctum parity): Sanctum hashes ONLY the secret - the part AFTER the `|` - with SHA-256\n * and stores the lowercase hex digest. It does NOT hash the `id|` prefix. {@link hashSecret} is the\n * single definition of that rule and is used by both issuance and verification so they can never\n * drift. SHA-256 (not a slow KDF) is appropriate here because the secret is high-entropy random,\n * not a user-chosen password.\n */\nimport { createHash, randomBytes } from 'node:crypto'\n\nimport { uuid } from '@plinthjs/support'\n\nimport { PersonalAccessToken } from './token'\n\nimport type { TokenStore } from './store'\n\n/** The default abilities granted when none are specified - full access, as in Sanctum. */\nconst DEFAULT_ABILITIES: readonly string[] = ['*']\n\n/** Number of random bytes in the secret; 40 bytes → an 80-char hex secret (Sanctum uses ~40). */\nconst SECRET_BYTES = 40\n\n/** The separator between the id and the secret in a plaintext token. */\nexport const TOKEN_SEPARATOR = '|'\n\n/**\n * Hash the secret portion of a token with SHA-256, returning the lowercase hex digest. This is the\n * canonical hashing rule - it takes the SECRET ONLY (never the `id|` prefix), matching Sanctum, and\n * is shared by issuance and verification so the two stay in lockstep.\n */\nexport function hashSecret(secret: string): string {\n return createHash('sha256').update(secret).digest('hex')\n}\n\n/**\n * Split a plaintext bearer token into its `{ id, secret }` parts, or `null` if it is not in the\n * `id|secret` form. The id is everything before the first `|`; the secret is everything after, so a\n * secret may itself contain `|` without ambiguity. Empty id or empty secret yields `null`.\n */\nexport function parseToken(plainTextToken: string): { id: string; secret: string } | null {\n const index = plainTextToken.indexOf(TOKEN_SEPARATOR)\n if (index <= 0) return null\n const id = plainTextToken.slice(0, index)\n const secret = plainTextToken.slice(index + 1)\n if (secret.length === 0) return null\n return { id, secret }\n}\n\n/** Generate a fresh high-entropy secret as a hex string. */\nfunction generateSecret(): string {\n return randomBytes(SECRET_BYTES).toString('hex')\n}\n\n/** Options for {@link createToken} - the named parameters of Sanctum's `createToken`. */\nexport interface CreateTokenOptions {\n /** A human-readable name for the token. */\n name: string\n /** The abilities to grant; defaults to `['*']` (full access). */\n abilities?: string[]\n /** Epoch milliseconds when the token should expire; omit for a non-expiring token. */\n expiresAt?: number\n /** The owning model's primary key (`tokenable_id`). */\n tokenableId?: string | number\n /** The owning model's type/morph name (`tokenable_type`). */\n tokenableType?: string\n}\n\n/** Overridable seams for {@link createToken}, primarily for deterministic tests. */\nexport interface CreateTokenSeams {\n /** Clock used for `createdAt`; defaults to `Date.now`. Epoch milliseconds. */\n now?: () => number\n /** Id generator; defaults to a UUID v4. */\n generateId?: () => string\n /** Secret generator; defaults to 40 random bytes as hex. */\n generateSecret?: () => string\n}\n\n/**\n * The result of issuing a token. {@link plainTextToken} is the full `id|secret` string and is\n * returned EXACTLY ONCE - it is never recoverable from {@link accessToken}, which holds only the\n * hash.\n */\nexport interface NewAccessToken {\n /** The persisted record (hash only - no plaintext). */\n accessToken: PersonalAccessToken\n /** The full plaintext token to hand to the client this one time. */\n plainTextToken: string\n}\n\n/**\n * Issue a new personal access token, persist its record (hash only) to `store`, and return the\n * record together with the one-time plaintext.\n */\nexport function createToken(\n store: TokenStore,\n options: CreateTokenOptions,\n seams?: CreateTokenSeams,\n): NewAccessToken {\n const now = (seams?.now ?? Date.now)()\n const id = (seams?.generateId ?? uuid)()\n const secret = (seams?.generateSecret ?? generateSecret)()\n const abilities = options.abilities ?? [...DEFAULT_ABILITIES]\n\n const attributes = {\n id,\n name: options.name,\n tokenHash: hashSecret(secret),\n abilities,\n createdAt: now,\n } as ConstructorParameters<typeof PersonalAccessToken>[0]\n if (options.tokenableId !== undefined) attributes.tokenableId = options.tokenableId\n if (options.tokenableType !== undefined) attributes.tokenableType = options.tokenableType\n if (options.expiresAt !== undefined) attributes.expiresAt = options.expiresAt\n\n const accessToken = new PersonalAccessToken(attributes)\n store.save(accessToken)\n\n return { accessToken, plainTextToken: `${id}${TOKEN_SEPARATOR}${secret}` }\n}\n\n/** Alias for {@link createToken}, matching the `issueToken` naming used elsewhere in Plinth. */\nexport const issueToken: (\n store: TokenStore,\n options: CreateTokenOptions,\n seams?: CreateTokenSeams,\n) => NewAccessToken = createToken\n","/**\n * `TokenStore` - the persistence seam for personal access tokens.\n *\n * Sanctum stores tokens in a database table; Plinth keeps the framework dependency-free, so the\n * store is an interface the application implements against its own ORM. {@link ArrayTokenStore} is\n * an in-memory implementation suitable for tests and ephemeral use.\n */\nimport type { PersonalAccessToken } from './token'\n\n/**\n * The seam between the guard/factory and however tokens are persisted - the Sanctum\n * `personal_access_tokens` repository equivalent. Lookups are by token id (the part before the `|`).\n */\nexport interface TokenStore {\n /** Find a token by its id, or `undefined` if none is stored. */\n find(id: string): PersonalAccessToken | undefined\n /** Persist (insert or replace) a token, keyed by its id. */\n save(token: PersonalAccessToken): void\n /** Delete the token with the given id, if present. The revoke equivalent. */\n delete(id: string): void\n /** Every stored token. */\n all(): PersonalAccessToken[]\n}\n\n/**\n * Free-function form of {@link TokenStore.find}: look a token up by id, or `undefined`. Exists so\n * callers can read a store without tripping `unicorn/no-array-callback-reference`, which cannot tell\n * a repository's `.find(id)` apart from `Array.prototype.find` (the collision is resolved here once).\n */\nexport function findToken(store: TokenStore, id: string): PersonalAccessToken | undefined {\n // eslint-disable-next-line unicorn/no-array-callback-reference -- repository lookup, not Array#find\n return store.find(id)\n}\n\n/**\n * An in-memory {@link TokenStore} backed by a `Map`. Not persistent across processes - intended for\n * tests, fixtures, and short-lived use. Real persistence is implemented by the application.\n */\nexport class ArrayTokenStore implements TokenStore {\n private readonly tokens = new Map<string, PersonalAccessToken>()\n\n /** Seed the store with an optional initial set of tokens. */\n constructor(initial?: Iterable<PersonalAccessToken>) {\n if (initial !== undefined) {\n for (const token of initial) this.tokens.set(token.id, token)\n }\n }\n\n find(id: string): PersonalAccessToken | undefined {\n return this.tokens.get(id)\n }\n\n save(token: PersonalAccessToken): void {\n this.tokens.set(token.id, token)\n }\n\n delete(id: string): void {\n this.tokens.delete(id)\n }\n\n all(): PersonalAccessToken[] {\n return [...this.tokens.values()]\n }\n\n /** Remove every stored token. Convenience for resetting between tests. */\n flush(): void {\n this.tokens.clear()\n }\n\n /** The number of stored tokens. */\n get size(): number {\n return this.tokens.size\n }\n}\n","/**\n * `TokenGuard` - authenticate a bearer token against a {@link TokenStore}.\n *\n * Given a plaintext `id|secret` bearer token it locates the\n * record by id, verifies the presented secret against the stored SHA-256 hash in CONSTANT TIME\n * ({@link timingSafeEqual}, length-guarded so unequal lengths never throw and never leak timing),\n * rejects expired tokens, and on success stamps `lastUsedAt` from the injected clock.\n */\nimport { timingSafeEqual } from 'node:crypto'\n\nimport { hashSecret, parseToken } from './factory'\nimport { findToken } from './store'\n\nimport type { TokenStore } from './store'\nimport type { PersonalAccessToken } from './token'\n\n/**\n * Constant-time equality of two hex digest strings. Returns `false` immediately when the lengths\n * differ (so `timingSafeEqual`, which throws on unequal-length buffers, is never reached), and\n * otherwise compares the bytes without short-circuiting. Used to compare token hashes.\n */\nexport function hashesMatch(a: string, b: string): boolean {\n const left = Buffer.from(a, 'utf8')\n const right = Buffer.from(b, 'utf8')\n if (left.length !== right.length) return false\n return timingSafeEqual(left, right)\n}\n\n/**\n * Authenticates personal access tokens. Construct with a {@link TokenStore} and, optionally, a\n * clock seam (epoch ms) used to test expiry and stamp `lastUsedAt`.\n */\nexport class TokenGuard {\n private readonly store: TokenStore\n private readonly clock: () => number\n\n /**\n * @param store The token repository to look records up in.\n * @param clock Returns the current time in epoch ms; defaults to `Date.now`. Injectable for tests.\n */\n constructor(store: TokenStore, clock?: () => number) {\n this.store = store\n this.clock = clock ?? Date.now\n }\n\n /**\n * Resolve a plaintext bearer token to its record, or `null` if it is malformed, unknown, the\n * secret does not match (constant-time), or it has expired. On success the record's `lastUsedAt`\n * is set to the current clock time and persisted. The Sanctum token-resolution equivalent.\n */\n authenticate(bearer: string): PersonalAccessToken | null {\n const parts = parseToken(bearer)\n if (parts === null) return null\n const { id, secret } = parts\n\n const token = findToken(this.store, id)\n if (token === undefined) return null\n\n if (!hashesMatch(hashSecret(secret), token.tokenHash)) return null\n\n const now = this.clock()\n if (token.isExpired(now)) return null\n\n token.lastUsedAt = now\n this.store.save(token)\n return token\n }\n\n /**\n * Resolve a bearer token to the id of its owning model (`tokenable_id`), or `null` if the token\n * is invalid or carries no owner. Convenience over {@link authenticate} for guards that only need\n * the user id.\n */\n authenticateToken(bearer: string): string | number | null {\n const token = this.authenticate(bearer)\n if (token === null) return null\n return token.tokenableId ?? null\n }\n\n /** Whether `bearer` resolves to a valid, unexpired token. */\n check(bearer: string): boolean {\n return this.authenticate(bearer) !== null\n }\n}\n","/**\n * `HasApiTokens`, as a helper bound to a\n * {@link TokenStore} and a tokenable owner.\n *\n * Plinth has no PHP traits, so instead of mixing methods into a model class this returns a small\n * object whose `createToken` / `tokens` / `tokenCan` are pre-bound to one owner. The owner's id and\n * (optional) morph type are stamped onto every token it issues, and `tokens()` lists only that\n * owner's tokens.\n */\nimport { createToken } from './factory'\nimport { WILDCARD_ABILITY } from './token'\n\nimport type { CreateTokenSeams, NewAccessToken } from './factory'\nimport type { TokenStore } from './store'\nimport type { PersonalAccessToken } from './token'\n\n/** The owning model of a set of tokens - its primary key and optional morph type. */\nexport interface Tokenable {\n /** The owner's primary key, stamped as `tokenableId` on issued tokens. */\n id: string | number\n /** The owner's morph type/name, stamped as `tokenableType` on issued tokens. */\n type?: string\n}\n\n/** The per-token inputs accepted by {@link HasApiTokens.createToken} (owner is already bound). */\nexport interface HasApiTokensCreateOptions {\n /** A human-readable name for the token. */\n name: string\n /** The abilities to grant; defaults to `['*']`. */\n abilities?: string[]\n /** Epoch milliseconds when the token should expire; omit for a non-expiring token. */\n expiresAt?: number\n}\n\n/** The owner-bound token API returned by {@link hasApiTokens}. */\nexport interface HasApiTokens {\n /** Issue a token for the bound owner, persisting it and returning the one-time plaintext. */\n createToken(options: HasApiTokensCreateOptions, seams?: CreateTokenSeams): NewAccessToken\n /** Every stored token belonging to the bound owner. */\n tokens(): PersonalAccessToken[]\n /** Whether any of the owner's tokens grants `ability` (wildcard `'*'` counts). */\n tokenCan(ability: string): boolean\n}\n\n/** Whether `token` belongs to `owner` (matching id and, when set, morph type). */\nfunction ownedBy(token: PersonalAccessToken, owner: Tokenable): boolean {\n if (token.tokenableId !== owner.id) return false\n if (owner.type === undefined) return true\n return token.tokenableType === owner.type\n}\n\n/**\n * Bind the token API to a `store` and a tokenable `owner`. Tokens issued via the returned object are stamped with the owner's id/type, and\n * {@link HasApiTokens.tokens} / {@link HasApiTokens.tokenCan} are scoped to that owner.\n */\nexport function hasApiTokens(store: TokenStore, owner: Tokenable): HasApiTokens {\n return {\n createToken(options: HasApiTokensCreateOptions, seams?: CreateTokenSeams): NewAccessToken {\n const base = {\n name: options.name,\n tokenableId: owner.id,\n } as Parameters<typeof createToken>[1]\n if (options.abilities !== undefined) base.abilities = options.abilities\n if (options.expiresAt !== undefined) base.expiresAt = options.expiresAt\n if (owner.type !== undefined) base.tokenableType = owner.type\n return createToken(store, base, seams)\n },\n tokens(): PersonalAccessToken[] {\n return store.all().filter((token) => ownedBy(token, owner))\n },\n tokenCan(ability: string): boolean {\n return store\n .all()\n .some(\n (token) =>\n ownedBy(token, owner) &&\n (token.abilities.includes(WILDCARD_ABILITY) || token.abilities.includes(ability)),\n )\n },\n }\n}\n","/**\n * @plinthjs/api-tokens - API token authentication.\n *\n * Stateless bearer-token auth with zero dependencies beyond `node:crypto` and `@plinthjs/support`.\n * Issue a token with {@link createToken} (the plaintext is returned ONCE; only its SHA-256 hash is\n * stored), persist it through a {@link TokenStore} ({@link ArrayTokenStore} ships in-memory), and\n * authenticate incoming bearer tokens with {@link TokenGuard}, which verifies the secret in\n * constant time and honours per-token {@link PersonalAccessToken.can | abilities} and expiry.\n *\n * TOKEN SCHEME: plaintext = `${id}|${secret}`; the stored hash is `sha256(secret)` in hex - the\n * secret being only the part AFTER the `|`, exactly as Sanctum hashes it.\n */\n\n/** The Plinth version this build of `sanctum` ships with. */\nexport const VERSION = '0.1.0'\n\nexport {\n type CreateTokenOptions,\n type CreateTokenSeams,\n createToken,\n hashSecret,\n issueToken,\n type NewAccessToken,\n parseToken,\n TOKEN_SEPARATOR,\n} from './factory'\nexport { TokenGuard, hashesMatch } from './guard'\nexport {\n type HasApiTokens,\n hasApiTokens,\n type HasApiTokensCreateOptions,\n type Tokenable,\n} from './has-api-tokens'\nexport { ArrayTokenStore, findToken, type TokenStore } from './store'\nexport { PersonalAccessToken, type PersonalAccessTokenAttributes, WILDCARD_ABILITY } from './token'\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@plinthjs/api-tokens",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"description": "Plinth API token authentication.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"plinth",
|
|
@@ -8,13 +8,13 @@
|
|
|
8
8
|
"typescript",
|
|
9
9
|
"api-tokens"
|
|
10
10
|
],
|
|
11
|
-
"homepage": "https://github.com/anilkumarthakur60/
|
|
11
|
+
"homepage": "https://github.com/anilkumarthakur60/plinthjs/tree/main/packages/api-tokens#readme",
|
|
12
12
|
"bugs": {
|
|
13
|
-
"url": "https://github.com/anilkumarthakur60/
|
|
13
|
+
"url": "https://github.com/anilkumarthakur60/plinthjs/issues"
|
|
14
14
|
},
|
|
15
15
|
"repository": {
|
|
16
16
|
"type": "git",
|
|
17
|
-
"url": "git+https://github.com/anilkumarthakur60/
|
|
17
|
+
"url": "git+https://github.com/anilkumarthakur60/plinthjs.git",
|
|
18
18
|
"directory": "packages/api-tokens"
|
|
19
19
|
},
|
|
20
20
|
"license": "MIT",
|
|
@@ -42,8 +42,8 @@
|
|
|
42
42
|
"access": "public"
|
|
43
43
|
},
|
|
44
44
|
"dependencies": {
|
|
45
|
-
"@plinthjs/support": "^0.1.
|
|
46
|
-
"@plinthjs/contracts": "^0.1.
|
|
45
|
+
"@plinthjs/support": "^0.1.2",
|
|
46
|
+
"@plinthjs/contracts": "^0.1.2"
|
|
47
47
|
},
|
|
48
48
|
"devDependencies": {
|
|
49
49
|
"tsup": "^8.3.5",
|