@venizia/ignis-helpers 0.4.8-7 → 0.4.8-9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/esm/common/constants/http.d.ts +2 -0
  2. package/dist/esm/common/constants/http.js +2 -0
  3. package/dist/esm/common/constants/http.js.map +1 -1
  4. package/dist/esm/modules/storage/base.d.ts +9 -4
  5. package/dist/esm/modules/storage/base.js +10 -4
  6. package/dist/esm/modules/storage/base.js.map +1 -1
  7. package/dist/esm/modules/storage/bun-s3/helper.d.ts +2 -3
  8. package/dist/esm/modules/storage/bun-s3/helper.js +6 -5
  9. package/dist/esm/modules/storage/bun-s3/helper.js.map +1 -1
  10. package/dist/esm/modules/storage/bun-s3/utility.d.ts +2 -1
  11. package/dist/esm/modules/storage/bun-s3/utility.js +4 -3
  12. package/dist/esm/modules/storage/bun-s3/utility.js.map +1 -1
  13. package/dist/esm/modules/storage/common/constants.d.ts +7 -0
  14. package/dist/esm/modules/storage/common/constants.js +5 -0
  15. package/dist/esm/modules/storage/common/constants.js.map +1 -1
  16. package/dist/esm/modules/storage/common/errors.d.ts +17 -0
  17. package/dist/esm/modules/storage/common/errors.js +14 -0
  18. package/dist/esm/modules/storage/common/errors.js.map +1 -1
  19. package/dist/esm/modules/storage/common/types.d.ts +17 -4
  20. package/dist/esm/modules/storage/common/types.js.map +1 -1
  21. package/dist/esm/modules/storage/disk/helper.d.ts +1 -0
  22. package/dist/esm/modules/storage/disk/helper.js +2 -1
  23. package/dist/esm/modules/storage/disk/helper.js.map +1 -1
  24. package/dist/esm/modules/uid/common/constants.d.ts +26 -0
  25. package/dist/esm/modules/uid/common/constants.js +27 -0
  26. package/dist/esm/modules/uid/common/constants.js.map +1 -1
  27. package/dist/esm/modules/uid/common/crc32.d.ts +22 -0
  28. package/dist/esm/modules/uid/common/crc32.js +39 -0
  29. package/dist/esm/modules/uid/common/crc32.js.map +1 -0
  30. package/dist/esm/modules/uid/common/random.d.ts +46 -0
  31. package/dist/esm/modules/uid/common/random.js +94 -0
  32. package/dist/esm/modules/uid/common/random.js.map +1 -0
  33. package/dist/esm/modules/uid/common/segments.d.ts +36 -0
  34. package/dist/esm/modules/uid/common/segments.js +81 -0
  35. package/dist/esm/modules/uid/common/segments.js.map +1 -0
  36. package/dist/esm/modules/uid/common/types.d.ts +45 -1
  37. package/dist/esm/modules/uid/common/types.js.map +1 -1
  38. package/dist/esm/modules/uid/index.d.ts +2 -0
  39. package/dist/esm/modules/uid/index.js +2 -0
  40. package/dist/esm/modules/uid/index.js.map +1 -1
  41. package/dist/esm/modules/uid/numeric.d.ts +18 -0
  42. package/dist/esm/modules/uid/numeric.js +31 -0
  43. package/dist/esm/modules/uid/numeric.js.map +1 -0
  44. package/dist/esm/modules/uid/opaque.d.ts +0 -15
  45. package/dist/esm/modules/uid/opaque.js +17 -107
  46. package/dist/esm/modules/uid/opaque.js.map +1 -1
  47. package/dist/esm/modules/uid/token.d.ts +57 -0
  48. package/dist/esm/modules/uid/token.js +218 -0
  49. package/dist/esm/modules/uid/token.js.map +1 -0
  50. package/dist/esm/modules/uid/uuid/helper.d.ts +2 -1
  51. package/dist/esm/modules/uid/uuid/helper.js +2 -1
  52. package/dist/esm/modules/uid/uuid/helper.js.map +1 -1
  53. package/dist/esm/utilities/parse.utility.d.ts +5 -0
  54. package/dist/esm/utilities/parse.utility.js +17 -1
  55. package/dist/esm/utilities/parse.utility.js.map +1 -1
  56. package/dist/esm/utilities/request.utility.d.ts +4 -0
  57. package/dist/esm/utilities/request.utility.js +10 -1
  58. package/dist/esm/utilities/request.utility.js.map +1 -1
  59. package/package.json +2 -2
@@ -1,9 +1,9 @@
1
1
  import { HTTP } from '../../common/constants/index.js';
2
2
  import { BaseHelper } from '../base.js';
3
3
  import { getError } from '../error/index.js';
4
- import { DEFAULT_UID_DELIMITER, DEFAULT_UID_LENGTH, DEFAULT_UID_MAX_ATTEMPTS, MIN_UID_ALPHABET_SIZE, UidAlphabets, UidCaseForms, } from './common/constants.js';
5
- /** How many random bytes to draw per refill, per remaining character. Rejection throws some away, so asking for exactly `length` would round-trip to the entropy source repeatedly. */
6
- const SAMPLING_OVERDRAW = 2;
4
+ import { DEFAULT_UID_LENGTH, DEFAULT_UID_MAX_ATTEMPTS, MIN_UID_ALPHABET_SIZE, UidAlphabets, UidCaseForms, } from './common/constants.js';
5
+ import { UidRandom } from './common/random.js';
6
+ import { UidSegments } from './common/segments.js';
7
7
  /** Local, not `@/utilities/promise.utility`: that module imports the logger BARREL, which reaches `node:module` and would take this browser-pure module with it. */
8
8
  const isPromiseLike = (value) => {
9
9
  return typeof value?.then === 'function';
@@ -39,13 +39,17 @@ export class OpaqueUidHelper extends BaseHelper {
39
39
  message: `[${OpaqueUidHelper.name}] length must be a positive integer | value: ${this.length}`,
40
40
  });
41
41
  }
42
- this.prefix = OpaqueUidHelper.resolvePrefix({ prefix: opts?.prefix, caseForm });
43
- this.delimiter = OpaqueUidHelper.resolveDelimiter({
42
+ this.prefix = UidSegments.resolvePrefix({
43
+ scope: OpaqueUidHelper.name,
44
+ prefix: opts?.prefix,
45
+ caseForm,
46
+ });
47
+ this.delimiter = UidSegments.resolveDelimiter({
48
+ scope: OpaqueUidHelper.name,
44
49
  delimiter: opts?.delimiter,
45
50
  hasPrefix: this.prefix.length > 0,
46
51
  alphabet: this.alphabet,
47
52
  });
48
- this.mask = (1 << Math.ceil(Math.log2(this.alphabet.length))) - 1;
49
53
  }
50
54
  nextId(opts) {
51
55
  const head = this.resolveHead({ prefix: opts?.prefix });
@@ -93,15 +97,12 @@ export class OpaqueUidHelper extends BaseHelper {
93
97
  throw this.buildExhaustedError({ maxAttempts });
94
98
  }
95
99
  resolveHead(opts) {
96
- const override = opts.prefix;
97
- if (override === '') {
98
- throw getError({
99
- statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
100
- message: `[${OpaqueUidHelper.name}][nextId] An empty prefix is not how a prefix is turned off | Construct with \`prefix: { enable: false }\``,
101
- });
102
- }
103
- const prefix = override ?? this.prefix;
104
- return prefix.length > 0 ? `${prefix}${this.delimiter}` : '';
100
+ return UidSegments.resolveHead({
101
+ scope: OpaqueUidHelper.name,
102
+ override: opts.prefix,
103
+ prefix: this.prefix,
104
+ delimiter: this.delimiter,
105
+ });
105
106
  }
106
107
  static resolveMaxAttempts(opts) {
107
108
  const maxAttempts = opts.maxAttempts ?? DEFAULT_UID_MAX_ATTEMPTS;
@@ -125,40 +126,7 @@ export class OpaqueUidHelper extends BaseHelper {
125
126
  return this.alphabet;
126
127
  }
127
128
  randomBody() {
128
- const size = this.alphabet.length;
129
- let body = '';
130
- while (body.length < this.length) {
131
- const bytes = OpaqueUidHelper.randomBytes({
132
- count: (this.length - body.length) * SAMPLING_OVERDRAW,
133
- });
134
- for (const byte of bytes) {
135
- const index = byte & this.mask;
136
- // Rejection, not wrap-around: an index past the alphabet is discarded so every character
137
- // stays equally likely.
138
- if (index >= size) {
139
- continue;
140
- }
141
- body += this.alphabet[index];
142
- if (body.length === this.length) {
143
- break;
144
- }
145
- }
146
- }
147
- return body;
148
- }
149
- /**
150
- * `crypto.getRandomValues`, never `Math.random`. Unlike `crypto.randomUUID`, this one is NOT
151
- * restricted to a secure context, so it works on a plain-http origin and inside a browser Worker.
152
- */
153
- static randomBytes(opts) {
154
- const source = globalThis.crypto;
155
- if (typeof source?.getRandomValues !== 'function') {
156
- throw getError({
157
- statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
158
- message: `[${OpaqueUidHelper.name}] No Web Crypto available | \`crypto.getRandomValues\` is required and \`Math.random\` is not an acceptable substitute for an identifier`,
159
- });
160
- }
161
- return source.getRandomValues(new Uint8Array(opts.count));
129
+ return UidRandom.sample({ alphabet: this.alphabet, length: this.length });
162
130
  }
163
131
  static hasBothCases(opts) {
164
132
  let hasUpper = false;
@@ -214,63 +182,5 @@ export class OpaqueUidHelper extends BaseHelper {
214
182
  }
215
183
  return resolved;
216
184
  }
217
- /** An enabled prefix in the wrong case defeats the reason for choosing one: an id meant to survive a case-insensitive column stops being one the moment its prefix disagrees. */
218
- static resolvePrefix(opts) {
219
- const { prefix, caseForm } = opts;
220
- if (!prefix?.enable) {
221
- return '';
222
- }
223
- const value = prefix.value ?? '';
224
- if (value.length === 0) {
225
- throw getError({
226
- statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
227
- message: `[${OpaqueUidHelper.name}] prefix is enabled but carries no value`,
228
- });
229
- }
230
- const expected = caseForm === UidCaseForms.UPPER
231
- ? value.toUpperCase()
232
- : caseForm === UidCaseForms.LOWER
233
- ? value.toLowerCase()
234
- : value;
235
- if (value !== expected) {
236
- throw getError({
237
- statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
238
- message: `[${OpaqueUidHelper.name}] prefix does not match caseForm | prefix: ${value} | caseForm: ${caseForm} | expected: ${expected}`,
239
- });
240
- }
241
- return value;
242
- }
243
- /**
244
- * Two refusals here, both because the alternative fails silently: a delimiter with no prefix is a
245
- * leading character that separates nothing, and a delimiter drawn from the alphabet makes the id
246
- * impossible to split back into prefix and body.
247
- */
248
- static resolveDelimiter(opts) {
249
- const { delimiter, hasPrefix, alphabet } = opts;
250
- if (!delimiter?.enable) {
251
- return '';
252
- }
253
- if (!hasPrefix) {
254
- throw getError({
255
- statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
256
- message: `[${OpaqueUidHelper.name}] delimiter is enabled without a prefix | It would lead the id and separate nothing | Put the character in \`prefix.value\` if that is what you want`,
257
- });
258
- }
259
- const value = delimiter.value ?? DEFAULT_UID_DELIMITER;
260
- if (value.length === 0) {
261
- throw getError({
262
- statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
263
- message: `[${OpaqueUidHelper.name}] delimiter is enabled but carries no value`,
264
- });
265
- }
266
- const shared = [...new Set(value)].filter((character) => alphabet.includes(character));
267
- if (shared.length > 0) {
268
- throw getError({
269
- statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
270
- message: `[${OpaqueUidHelper.name}] delimiter shares characters with the alphabet | shared: ${shared.join('')} | An id built with it cannot be split back into prefix and body`,
271
- });
272
- }
273
- return value;
274
- }
275
185
  }
276
186
  //# sourceMappingURL=opaque.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"opaque.js","sourceRoot":"","sources":["../../../../src/modules/uid/opaque.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAE1C,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AACpC,OAAO,EACL,qBAAqB,EACrB,kBAAkB,EAClB,wBAAwB,EACxB,qBAAqB,EACrB,YAAY,EACZ,YAAY,GACb,MAAM,oBAAoB,CAAC;AAI5B,uLAAuL;AACvL,MAAM,iBAAiB,GAAG,CAAC,CAAC;AAE5B,oKAAoK;AACpK,MAAM,aAAa,GAAG,CAAC,KAAc,EAAiC,EAAE;IACtE,OAAO,OAAQ,KAAiD,EAAE,IAAI,KAAK,UAAU,CAAC;AACxF,CAAC,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,MAAM,OAAO,eAAgB,SAAQ,UAAU;IAS7C,YAAY,IAAwB;QAClC,KAAK,CAAC,EAAE,KAAK,EAAE,eAAe,CAAC,IAAI,EAAE,CAAC,CAAC;QAEvC,MAAM,QAAQ,GAAG,IAAI,EAAE,QAAQ,IAAI,YAAY,CAAC,KAAK,CAAC;QACtD,eAAe,CAAC,mBAAmB,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC;QAElD,IAAI,CAAC,QAAQ,GAAG,eAAe,CAAC,eAAe,CAAC;YAC9C,QAAQ,EAAE,IAAI,EAAE,QAAQ,IAAI,YAAY,CAAC,SAAS;YAClD,OAAO,EAAE,IAAI,EAAE,OAAO,IAAI,EAAE;YAC5B,QAAQ;SACT,CAAC,CAAC;QAEH,IAAI,CAAC,MAAM,GAAG,IAAI,EAAE,MAAM,IAAI,kBAAkB,CAAC;QAEjD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I,sJAAsJ;aACxL,CAAC,CAAC;QACL,CAAC;QAED,MAAM,KAAK,GAAG,SAAS,CAAC,KAAK,IAAI,qBAAqB,CAAC;QAEvD,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACvB,MAAM,QAAQ,CAAC;gBACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;gBACrD,OAAO,EAAE,IAAI,eAAe,CAAC,IAAI,6CAA6C;aAC/E,CAAC,CAAC;QACL,CAAC;QAED,MAAM,MAAM,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC;QAEvF,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACtB,MAAM,QAAQ,CAAC;gBACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;gBACrD,OAAO,EAAE,IAAI,eAAe,CAAC,IAAI,6DAA6D,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,kEAAkE;aAChL,CAAC,CAAC;QACL,CAAC;QAED,OAAO,KAAK,CAAC;IACf,CAAC;CACF","sourcesContent":["import { HTTP } from '@/common/constants';\nimport type { ValueOrPromise } from '@/common/types';\nimport { BaseHelper } from '../base';\nimport { getError } from '../error';\nimport {\n DEFAULT_UID_DELIMITER,\n DEFAULT_UID_LENGTH,\n DEFAULT_UID_MAX_ATTEMPTS,\n MIN_UID_ALPHABET_SIZE,\n UidAlphabets,\n UidCaseForms,\n} from './common/constants';\nimport type { TUidCaseForm } from './common/constants';\nimport type { INextOpaqueUidOptions, IOpaqueUidOptions, IUidSegment } from './common/types';\n\n/** How many random bytes to draw per refill, per remaining character. Rejection throws some away, so asking for exactly `length` would round-trip to the entropy source repeatedly. */\nconst SAMPLING_OVERDRAW = 2;\n\n/** Local, not `@/utilities/promise.utility`: that module imports the logger BARREL, which reaches `node:module` and would take this browser-pure module with it. */\nconst isPromiseLike = (value: unknown): value is PromiseLike<boolean> => {\n return typeof (value as PromiseLike<boolean> | null | undefined)?.then === 'function';\n};\n\n/**\n * Fixed-length opaque ids, optionally prefixed - the counterpart to `SnowflakeUidHelper`.\n *\n * OPAQUE is the difference that matters, not the randomness. A Snowflake id is TRANSPARENT: its own\n * `parseId()` reads back the exact millisecond it was minted and the worker that minted it. That is\n * what you want in a log and not what you want on an invoice. Nothing can be read out of an id from\n * here. The cost is the ordering, which a Snowflake gives an index for free.\n *\n * `length` counts the BODY only. A prefix and a delimiter sit in front of it, so the finished string\n * is `prefix + delimiter + length` characters.\n *\n * Read {@link DEFAULT_UID_LENGTH} before accepting the default: six characters is an airline record\n * locator, and it needs the same scoping and retry that airlines give one.\n */\nexport class OpaqueUidHelper extends BaseHelper {\n private readonly alphabet: string;\n private readonly length: number;\n private readonly prefix: string;\n private readonly delimiter: string;\n\n /** Rejection mask: the smallest `2^n - 1` that covers every alphabet index. A plain `byte % size` would favour the first `256 % size` characters, which is a bias a caller cannot see and cannot undo. */\n private readonly mask: number;\n\n constructor(opts?: IOpaqueUidOptions) {\n super({ scope: OpaqueUidHelper.name });\n\n const caseForm = opts?.caseForm ?? UidCaseForms.UPPER;\n OpaqueUidHelper.assertKnownCaseForm({ caseForm });\n\n this.alphabet = OpaqueUidHelper.resolveAlphabet({\n alphabet: opts?.alphabet ?? UidAlphabets.CROCKFORD,\n exclude: opts?.exclude ?? '',\n caseForm,\n });\n\n this.length = opts?.length ?? DEFAULT_UID_LENGTH;\n\n if (!Number.isInteger(this.length) || this.length < 1) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] length must be a positive integer | value: ${this.length}`,\n });\n }\n\n this.prefix = OpaqueUidHelper.resolvePrefix({ prefix: opts?.prefix, caseForm });\n this.delimiter = OpaqueUidHelper.resolveDelimiter({\n delimiter: opts?.delimiter,\n hasPrefix: this.prefix.length > 0,\n alphabet: this.alphabet,\n });\n\n this.mask = (1 << Math.ceil(Math.log2(this.alphabet.length))) - 1;\n }\n\n /**\n * `prefix` replaces the configured value for this call and turns the prefix on for it; the\n * delimiter follows its own switch.\n *\n * `isAvailable` redraws until it accepts an id, up to `maxAttempts`. It LOWERS the collision rate,\n * it does not remove it: against a database the check and the insert are two statements, and\n * another request can take the id in between. The column still needs a unique index, and the\n * insert still needs to regenerate on violation.\n */\n nextId(opts?: INextOpaqueUidOptions<boolean>): string;\n nextId(opts: INextOpaqueUidOptions<Promise<boolean>>): Promise<string>;\n nextId(opts: INextOpaqueUidOptions): ValueOrPromise<string>;\n nextId(opts?: INextOpaqueUidOptions): ValueOrPromise<string> {\n const head = this.resolveHead({ prefix: opts?.prefix });\n\n const isAvailable = opts?.isAvailable;\n\n if (!isAvailable) {\n // Refused rather than ignored: without a check there is exactly ONE draw, so a caller who set\n // `maxAttempts` has configured a retry that cannot happen and has no way to notice.\n if (opts?.maxAttempts !== undefined) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}][nextId] maxAttempts has no effect without \\`isAvailable\\` | Nothing rejects a draw, so there is only ever one`,\n });\n }\n\n return `${head}${this.randomBody()}`;\n }\n\n const maxAttempts = OpaqueUidHelper.resolveMaxAttempts({ maxAttempts: opts?.maxAttempts });\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n const id = `${head}${this.randomBody()}`;\n const verdict = isAvailable(id);\n\n // The first PENDING verdict decides the shape of the whole call. Everything before it already\n // resolved, so a synchronous check never allocates a promise and `nextId()` stays a string.\n if (isPromiseLike(verdict)) {\n return this.continueAsync({ head, isAvailable, maxAttempts, attempt, id, verdict });\n }\n\n if (verdict) {\n return id;\n }\n }\n\n throw this.buildExhaustedError({ maxAttempts });\n }\n\n /** Entered only once a verdict came back pending; every later draw is awaited from here. */\n private async continueAsync(opts: {\n head: string;\n isAvailable: (id: string) => ValueOrPromise<boolean>;\n maxAttempts: number;\n attempt: number;\n id: string;\n verdict: PromiseLike<boolean>;\n }): Promise<string> {\n const { head, isAvailable, maxAttempts, attempt, id, verdict } = opts;\n\n const result = await verdict;\n\n if (result) {\n return id;\n }\n\n for (let next = attempt + 1; next <= maxAttempts; next++) {\n const candidate = `${head}${this.randomBody()}`;\n\n const result2 = await isAvailable(candidate);\n\n if (result2) {\n return candidate;\n }\n }\n\n throw this.buildExhaustedError({ maxAttempts });\n }\n\n private resolveHead(opts: { prefix?: string }): string {\n const override = opts.prefix;\n\n if (override === '') {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}][nextId] An empty prefix is not how a prefix is turned off | Construct with \\`prefix: { enable: false }\\``,\n });\n }\n\n const prefix = override ?? this.prefix;\n\n return prefix.length > 0 ? `${prefix}${this.delimiter}` : '';\n }\n\n private static resolveMaxAttempts(opts: { maxAttempts?: number }): number {\n const maxAttempts = opts.maxAttempts ?? DEFAULT_UID_MAX_ATTEMPTS;\n\n if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}][nextId] maxAttempts must be a positive integer | value: ${maxAttempts}`,\n });\n }\n\n return maxAttempts;\n }\n\n /** Bounded rather than endless: repeated rejection means the space is full, and a caller waiting forever learns that far later than a caller holding this error. */\n private buildExhaustedError(opts: { maxAttempts: number }) {\n return getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}][nextId] No available id after ${opts.maxAttempts} attempts | length: ${this.length} | alphabet: ${this.alphabet.length} | The space is crowded - raise \\`length\\``,\n });\n }\n\n /** The alphabet actually in use, after the case fold and every exclusion - what `length` is measured against. */\n getAlphabet(): string {\n return this.alphabet;\n }\n\n private randomBody(): string {\n const size = this.alphabet.length;\n let body = '';\n\n while (body.length < this.length) {\n const bytes = OpaqueUidHelper.randomBytes({\n count: (this.length - body.length) * SAMPLING_OVERDRAW,\n });\n\n for (const byte of bytes) {\n const index = byte & this.mask;\n\n // Rejection, not wrap-around: an index past the alphabet is discarded so every character\n // stays equally likely.\n if (index >= size) {\n continue;\n }\n\n body += this.alphabet[index];\n\n if (body.length === this.length) {\n break;\n }\n }\n }\n\n return body;\n }\n\n /**\n * `crypto.getRandomValues`, never `Math.random`. Unlike `crypto.randomUUID`, this one is NOT\n * restricted to a secure context, so it works on a plain-http origin and inside a browser Worker.\n */\n private static randomBytes(opts: { count: number }): Uint8Array {\n const source = globalThis.crypto;\n\n if (typeof source?.getRandomValues !== 'function') {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] No Web Crypto available | \\`crypto.getRandomValues\\` is required and \\`Math.random\\` is not an acceptable substitute for an identifier`,\n });\n }\n\n return source.getRandomValues(new Uint8Array(opts.count));\n }\n\n private static hasBothCases(opts: { alphabet: string }): boolean {\n let hasUpper = false;\n let hasLower = false;\n\n for (const character of opts.alphabet) {\n hasUpper ||= character !== character.toLowerCase();\n hasLower ||= character !== character.toUpperCase();\n\n if (hasUpper && hasLower) {\n return true;\n }\n }\n\n return false;\n }\n\n private static assertKnownCaseForm(opts: { caseForm: TUidCaseForm }): void {\n if (UidCaseForms.isValid(opts.caseForm)) {\n return;\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] Unknown caseForm | value: ${opts.caseForm} | valid: ${[...UidCaseForms.SCHEME_SET].join(', ')}`,\n });\n }\n\n /**\n * Folds case FIRST, then excludes, then de-duplicates - folding after sampling would misreport the\n * entropy and undo the alphabet's own exclusions.\n *\n * Refuses to fold a two-case alphabet at all, because folding one puts back exactly what it took\n * out: uppercasing `BASE58` turns its lowercase letters into `I` and `O`, the two it drops to keep\n * `1` and `0` unambiguous, and lowercasing it brings back `l`. Measured - the result is 35\n * characters, not the 33 an entropy calculation would predict. A single-case alphabet folds\n * cleanly because there is nothing to collide with.\n */\n private static resolveAlphabet(opts: {\n alphabet: string;\n exclude: string;\n caseForm: TUidCaseForm;\n }): string {\n const { alphabet, exclude, caseForm } = opts;\n\n if (caseForm !== UidCaseForms.MIXED && OpaqueUidHelper.hasBothCases({ alphabet })) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] caseForm '${caseForm}' cannot fold a two-case alphabet | Folding reintroduces the characters the alphabet excluded | Use \\`UidAlphabets.CROCKFORD\\` for a single-case alphabet, or \\`caseForm: '${UidCaseForms.MIXED}'\\``,\n });\n }\n\n const folded =\n caseForm === UidCaseForms.UPPER\n ? alphabet.toUpperCase()\n : caseForm === UidCaseForms.LOWER\n ? alphabet.toLowerCase()\n : alphabet;\n\n const removed = new Set(exclude);\n const resolved = [...new Set(folded)].filter((character) => !removed.has(character)).join('');\n\n if (resolved.length < MIN_UID_ALPHABET_SIZE) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] Alphabet too small | size: ${resolved.length} | minimum: ${MIN_UID_ALPHABET_SIZE} | Widen \\`alphabet\\` or shorten \\`exclude\\``,\n });\n }\n\n return resolved;\n }\n\n /** An enabled prefix in the wrong case defeats the reason for choosing one: an id meant to survive a case-insensitive column stops being one the moment its prefix disagrees. */\n private static resolvePrefix(opts: { prefix?: IUidSegment; caseForm: TUidCaseForm }): string {\n const { prefix, caseForm } = opts;\n\n if (!prefix?.enable) {\n return '';\n }\n\n const value = prefix.value ?? '';\n\n if (value.length === 0) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] prefix is enabled but carries no value`,\n });\n }\n\n const expected =\n caseForm === UidCaseForms.UPPER\n ? value.toUpperCase()\n : caseForm === UidCaseForms.LOWER\n ? value.toLowerCase()\n : value;\n\n if (value !== expected) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] prefix does not match caseForm | prefix: ${value} | caseForm: ${caseForm} | expected: ${expected}`,\n });\n }\n\n return value;\n }\n\n /**\n * Two refusals here, both because the alternative fails silently: a delimiter with no prefix is a\n * leading character that separates nothing, and a delimiter drawn from the alphabet makes the id\n * impossible to split back into prefix and body.\n */\n private static resolveDelimiter(opts: {\n delimiter?: IUidSegment;\n hasPrefix: boolean;\n alphabet: string;\n }): string {\n const { delimiter, hasPrefix, alphabet } = opts;\n\n if (!delimiter?.enable) {\n return '';\n }\n\n if (!hasPrefix) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] delimiter is enabled without a prefix | It would lead the id and separate nothing | Put the character in \\`prefix.value\\` if that is what you want`,\n });\n }\n\n const value = delimiter.value ?? DEFAULT_UID_DELIMITER;\n\n if (value.length === 0) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] delimiter is enabled but carries no value`,\n });\n }\n\n const shared = [...new Set(value)].filter((character) => alphabet.includes(character));\n\n if (shared.length > 0) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] delimiter shares characters with the alphabet | shared: ${shared.join('')} | An id built with it cannot be split back into prefix and body`,\n });\n }\n\n return value;\n }\n}\n"]}
1
+ {"version":3,"file":"opaque.js","sourceRoot":"","sources":["../../../../src/modules/uid/opaque.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAE1C,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AACpC,OAAO,EACL,kBAAkB,EAClB,wBAAwB,EACxB,qBAAqB,EACrB,YAAY,EACZ,YAAY,GACb,MAAM,oBAAoB,CAA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,CAAC,OAAO,CAAC,CAAC;QACjC,MAAM,QAAQ,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAE9F,IAAI,QAAQ,CAAC,MAAM,GAAG,qBAAqB,EAAE,CAAC;YAC5C,MAAM,QAAQ,CAAC;gBACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;gBACrD,OAAO,EAAE,IAAI,eAAe,CAAC,IAAI,gCAAgC,QAAQ,CAAC,MAAM,eAAe,qBAAqB,8CAA8C;aACnK,CAAC,CAAC;QACL,CAAC;QAED,OAAO,QAAQ,CAAC;IAClB,CAAC;CACF","sourcesContent":["import { HTTP } from '@/common/constants';\nimport type { ValueOrPromise } from '@/common/types';\nimport { BaseHelper } from '../base';\nimport { getError } from '../error';\nimport {\n DEFAULT_UID_LENGTH,\n DEFAULT_UID_MAX_ATTEMPTS,\n MIN_UID_ALPHABET_SIZE,\n UidAlphabets,\n UidCaseForms,\n} from './common/constants';\nimport type { TUidCaseForm } from './common/constants';\nimport { UidRandom } from './common/random';\nimport { UidSegments } from './common/segments';\nimport type { INextOpaqueUidOptions, IOpaqueUidOptions } from './common/types';\n\n/** Local, not `@/utilities/promise.utility`: that module imports the logger BARREL, which reaches `node:module` and would take this browser-pure module with it. */\nconst isPromiseLike = (value: unknown): value is PromiseLike<boolean> => {\n return typeof (value as PromiseLike<boolean> | null | undefined)?.then === 'function';\n};\n\n/**\n * Fixed-length opaque ids, optionally prefixed - the counterpart to `SnowflakeUidHelper`.\n *\n * OPAQUE is the difference that matters, not the randomness. A Snowflake id is TRANSPARENT: its own\n * `parseId()` reads back the exact millisecond it was minted and the worker that minted it. That is\n * what you want in a log and not what you want on an invoice. Nothing can be read out of an id from\n * here. The cost is the ordering, which a Snowflake gives an index for free.\n *\n * `length` counts the BODY only. A prefix and a delimiter sit in front of it, so the finished string\n * is `prefix + delimiter + length` characters.\n *\n * Read {@link DEFAULT_UID_LENGTH} before accepting the default: six characters is an airline record\n * locator, and it needs the same scoping and retry that airlines give one.\n */\nexport class OpaqueUidHelper extends BaseHelper {\n private readonly alphabet: string;\n private readonly length: number;\n private readonly prefix: string;\n private readonly delimiter: string;\n\n constructor(opts?: IOpaqueUidOptions) {\n super({ scope: OpaqueUidHelper.name });\n\n const caseForm = opts?.caseForm ?? UidCaseForms.UPPER;\n OpaqueUidHelper.assertKnownCaseForm({ caseForm });\n\n this.alphabet = OpaqueUidHelper.resolveAlphabet({\n alphabet: opts?.alphabet ?? UidAlphabets.CROCKFORD,\n exclude: opts?.exclude ?? '',\n caseForm,\n });\n\n this.length = opts?.length ?? DEFAULT_UID_LENGTH;\n\n if (!Number.isInteger(this.length) || this.length < 1) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] length must be a positive integer | value: ${this.length}`,\n });\n }\n\n this.prefix = UidSegments.resolvePrefix({\n scope: OpaqueUidHelper.name,\n prefix: opts?.prefix,\n caseForm,\n });\n this.delimiter = UidSegments.resolveDelimiter({\n scope: OpaqueUidHelper.name,\n delimiter: opts?.delimiter,\n hasPrefix: this.prefix.length > 0,\n alphabet: this.alphabet,\n });\n }\n\n /**\n * `prefix` replaces the configured value for this call and turns the prefix on for it; the\n * delimiter follows its own switch.\n *\n * `isAvailable` redraws until it accepts an id, up to `maxAttempts`. It LOWERS the collision rate,\n * it does not remove it: against a database the check and the insert are two statements, and\n * another request can take the id in between. The column still needs a unique index, and the\n * insert still needs to regenerate on violation.\n */\n nextId(opts?: INextOpaqueUidOptions<boolean>): string;\n nextId(opts: INextOpaqueUidOptions<Promise<boolean>>): Promise<string>;\n nextId(opts: INextOpaqueUidOptions): ValueOrPromise<string>;\n nextId(opts?: INextOpaqueUidOptions): ValueOrPromise<string> {\n const head = this.resolveHead({ prefix: opts?.prefix });\n\n const isAvailable = opts?.isAvailable;\n\n if (!isAvailable) {\n // Refused rather than ignored: without a check there is exactly ONE draw, so a caller who set\n // `maxAttempts` has configured a retry that cannot happen and has no way to notice.\n if (opts?.maxAttempts !== undefined) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}][nextId] maxAttempts has no effect without \\`isAvailable\\` | Nothing rejects a draw, so there is only ever one`,\n });\n }\n\n return `${head}${this.randomBody()}`;\n }\n\n const maxAttempts = OpaqueUidHelper.resolveMaxAttempts({ maxAttempts: opts?.maxAttempts });\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n const id = `${head}${this.randomBody()}`;\n const verdict = isAvailable(id);\n\n // The first PENDING verdict decides the shape of the whole call. Everything before it already\n // resolved, so a synchronous check never allocates a promise and `nextId()` stays a string.\n if (isPromiseLike(verdict)) {\n return this.continueAsync({ head, isAvailable, maxAttempts, attempt, id, verdict });\n }\n\n if (verdict) {\n return id;\n }\n }\n\n throw this.buildExhaustedError({ maxAttempts });\n }\n\n /** Entered only once a verdict came back pending; every later draw is awaited from here. */\n private async continueAsync(opts: {\n head: string;\n isAvailable: (id: string) => ValueOrPromise<boolean>;\n maxAttempts: number;\n attempt: number;\n id: string;\n verdict: PromiseLike<boolean>;\n }): Promise<string> {\n const { head, isAvailable, maxAttempts, attempt, id, verdict } = opts;\n\n const result = await verdict;\n\n if (result) {\n return id;\n }\n\n for (let next = attempt + 1; next <= maxAttempts; next++) {\n const candidate = `${head}${this.randomBody()}`;\n\n const result2 = await isAvailable(candidate);\n\n if (result2) {\n return candidate;\n }\n }\n\n throw this.buildExhaustedError({ maxAttempts });\n }\n\n private resolveHead(opts: { prefix?: string }): string {\n return UidSegments.resolveHead({\n scope: OpaqueUidHelper.name,\n override: opts.prefix,\n prefix: this.prefix,\n delimiter: this.delimiter,\n });\n }\n\n private static resolveMaxAttempts(opts: { maxAttempts?: number }): number {\n const maxAttempts = opts.maxAttempts ?? DEFAULT_UID_MAX_ATTEMPTS;\n\n if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}][nextId] maxAttempts must be a positive integer | value: ${maxAttempts}`,\n });\n }\n\n return maxAttempts;\n }\n\n /** Bounded rather than endless: repeated rejection means the space is full, and a caller waiting forever learns that far later than a caller holding this error. */\n private buildExhaustedError(opts: { maxAttempts: number }) {\n return getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}][nextId] No available id after ${opts.maxAttempts} attempts | length: ${this.length} | alphabet: ${this.alphabet.length} | The space is crowded - raise \\`length\\``,\n });\n }\n\n /** The alphabet actually in use, after the case fold and every exclusion - what `length` is measured against. */\n getAlphabet(): string {\n return this.alphabet;\n }\n\n private randomBody(): string {\n return UidRandom.sample({ alphabet: this.alphabet, length: this.length });\n }\n\n private static hasBothCases(opts: { alphabet: string }): boolean {\n let hasUpper = false;\n let hasLower = false;\n\n for (const character of opts.alphabet) {\n hasUpper ||= character !== character.toLowerCase();\n hasLower ||= character !== character.toUpperCase();\n\n if (hasUpper && hasLower) {\n return true;\n }\n }\n\n return false;\n }\n\n private static assertKnownCaseForm(opts: { caseForm: TUidCaseForm }): void {\n if (UidCaseForms.isValid(opts.caseForm)) {\n return;\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] Unknown caseForm | value: ${opts.caseForm} | valid: ${[...UidCaseForms.SCHEME_SET].join(', ')}`,\n });\n }\n\n /**\n * Folds case FIRST, then excludes, then de-duplicates - folding after sampling would misreport the\n * entropy and undo the alphabet's own exclusions.\n *\n * Refuses to fold a two-case alphabet at all, because folding one puts back exactly what it took\n * out: uppercasing `BASE58` turns its lowercase letters into `I` and `O`, the two it drops to keep\n * `1` and `0` unambiguous, and lowercasing it brings back `l`. Measured - the result is 35\n * characters, not the 33 an entropy calculation would predict. A single-case alphabet folds\n * cleanly because there is nothing to collide with.\n */\n private static resolveAlphabet(opts: {\n alphabet: string;\n exclude: string;\n caseForm: TUidCaseForm;\n }): string {\n const { alphabet, exclude, caseForm } = opts;\n\n if (caseForm !== UidCaseForms.MIXED && OpaqueUidHelper.hasBothCases({ alphabet })) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] caseForm '${caseForm}' cannot fold a two-case alphabet | Folding reintroduces the characters the alphabet excluded | Use \\`UidAlphabets.CROCKFORD\\` for a single-case alphabet, or \\`caseForm: '${UidCaseForms.MIXED}'\\``,\n });\n }\n\n const folded =\n caseForm === UidCaseForms.UPPER\n ? alphabet.toUpperCase()\n : caseForm === UidCaseForms.LOWER\n ? alphabet.toLowerCase()\n : alphabet;\n\n const removed = new Set(exclude);\n const resolved = [...new Set(folded)].filter((character) => !removed.has(character)).join('');\n\n if (resolved.length < MIN_UID_ALPHABET_SIZE) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${OpaqueUidHelper.name}] Alphabet too small | size: ${resolved.length} | minimum: ${MIN_UID_ALPHABET_SIZE} | Widen \\`alphabet\\` or shorten \\`exclude\\``,\n });\n }\n\n return resolved;\n }\n}\n"]}
@@ -0,0 +1,57 @@
1
+ import { BaseHelper } from '../base.js';
2
+ import type { INextTokenUidOptions, ITokenUidOptions } from './common/types.js';
3
+ /**
4
+ * Secret tokens: random bytes from the platform CSPRNG, written as base62 (the default), hex or
5
+ * base64url, optionally prefixed. Use it for a secret - a verification link, an API key, a session id, a password reset.
6
+ *
7
+ * - STORE A HASH, not the token. A database leak then leaks nothing a caller can replay.
8
+ * - COMPARE IN CONSTANT TIME with `Hash.equals` (`crypto/algorithms/hash.algorithm.ts`), never `===`.
9
+ * - Use `OpaqueUidHelper` for a short id a human reads, and `NumericUidHelper` for a code a human types.
10
+ *
11
+ * `bytes` is the entropy, not the text length: the constructor refuses anything under
12
+ * {@link MIN_TOKEN_BYTES} (128 bits). The finished string is `prefix + delimiter + body`. A base62
13
+ * body is `ceil(bytes * 8 / log2(62))` characters (32 bytes is 43), a hex body `bytes * 2`, a
14
+ * base64url body `ceil(bytes * 4 / 3)`.
15
+ *
16
+ * `checksum: true` appends a CRC-32 of the body, so `isWellFormed` can reject a mistyped token before
17
+ * any lookup. Enable it for a long-lived key a person copies, not for a one-shot link.
18
+ *
19
+ * The prefix and delimiter follow `OpaqueUidHelper`'s rules, with no `caseForm`: a token's case is
20
+ * its encoding's. A delimiter must sit outside the encoding's characters. `_` and `-` work with
21
+ * base62 and hex; base64url holds both, so it takes only a delimiter such as `.`.
22
+ */
23
+ export declare class TokenUidHelper extends BaseHelper {
24
+ private readonly bytes;
25
+ private readonly encoding;
26
+ private readonly prefix;
27
+ private readonly delimiter;
28
+ private readonly checksum;
29
+ constructor(opts?: ITokenUidOptions);
30
+ /** `prefix` replaces the configured value for this call and turns the prefix on for it; the delimiter follows its own switch. */
31
+ nextId(opts?: INextTokenUidOptions): string;
32
+ /**
33
+ * A FORMAT filter, nothing more: does `opts.key` have the configured prefix and delimiter, the body
34
+ * length and alphabet of the configured `bytes` and `encoding`, and (when enabled) a matching
35
+ * checksum. Returns `false` on anything else, never throws, including for a value that is not a
36
+ * string.
37
+ *
38
+ * It is NOT authentication. CRC-32 is public and forgeable, so anyone can build a token that passes.
39
+ * A well-formed token still has to be looked up by its HASH and compared in constant time with
40
+ * `Hash.equals`. Use this to refuse a mistyped or truncated token before spending a lookup on it.
41
+ *
42
+ * The head checked is the CONFIGURED prefix and delimiter (none when the instance has no prefix); a
43
+ * token minted with a per-call prefix is checked by an instance configured with that prefix.
44
+ */
45
+ isWellFormed(opts: {
46
+ key: string;
47
+ }): boolean;
48
+ private bodyLength;
49
+ private checksumLength;
50
+ /** The suffix for `body`: empty when the checksum is off, otherwise the CRC-32 of the body in the token's own alphabet, left-padded to a fixed width. */
51
+ private checksumOf;
52
+ private static alphabetOf;
53
+ private randomBody;
54
+ /** Hand-written, not `Buffer`: this module ships to a browser, where `Buffer` does not exist. */
55
+ private static encode;
56
+ }
57
+ //# sourceMappingURL=token.d.ts.map
@@ -0,0 +1,218 @@
1
+ import { HTTP } from '../../common/constants/index.js';
2
+ import { BaseHelper } from '../base.js';
3
+ import { getError } from '../error/index.js';
4
+ import { DEFAULT_TOKEN_BYTES, MIN_TOKEN_BYTES, UidAlphabets, UidCaseForms, UidTokenEncodings, } from './common/constants.js';
5
+ import { Crc32 } from './common/crc32.js';
6
+ import { UidRandom } from './common/random.js';
7
+ import { UidSegments } from './common/segments.js';
8
+ const BASE64URL_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
9
+ const HEX_ALPHABET = '0123456789abcdef';
10
+ const BITS_PER_BYTE = 8;
11
+ const HEX_RADIX = 16;
12
+ /** 62^6 is more than 2^32, so six base62 characters hold any CRC-32. */
13
+ const BASE62_CHECKSUM_LENGTH = 6;
14
+ /** Eight hex characters are 32 bits. */
15
+ const HEX_CHECKSUM_LENGTH = 8;
16
+ /** Bits one BASE62 character carries. */
17
+ const BASE62_BITS_PER_CHARACTER = Math.log2(UidAlphabets.BASE62.length);
18
+ /**
19
+ * Secret tokens: random bytes from the platform CSPRNG, written as base62 (the default), hex or
20
+ * base64url, optionally prefixed. Use it for a secret - a verification link, an API key, a session id, a password reset.
21
+ *
22
+ * - STORE A HASH, not the token. A database leak then leaks nothing a caller can replay.
23
+ * - COMPARE IN CONSTANT TIME with `Hash.equals` (`crypto/algorithms/hash.algorithm.ts`), never `===`.
24
+ * - Use `OpaqueUidHelper` for a short id a human reads, and `NumericUidHelper` for a code a human types.
25
+ *
26
+ * `bytes` is the entropy, not the text length: the constructor refuses anything under
27
+ * {@link MIN_TOKEN_BYTES} (128 bits). The finished string is `prefix + delimiter + body`. A base62
28
+ * body is `ceil(bytes * 8 / log2(62))` characters (32 bytes is 43), a hex body `bytes * 2`, a
29
+ * base64url body `ceil(bytes * 4 / 3)`.
30
+ *
31
+ * `checksum: true` appends a CRC-32 of the body, so `isWellFormed` can reject a mistyped token before
32
+ * any lookup. Enable it for a long-lived key a person copies, not for a one-shot link.
33
+ *
34
+ * The prefix and delimiter follow `OpaqueUidHelper`'s rules, with no `caseForm`: a token's case is
35
+ * its encoding's. A delimiter must sit outside the encoding's characters. `_` and `-` work with
36
+ * base62 and hex; base64url holds both, so it takes only a delimiter such as `.`.
37
+ */
38
+ export class TokenUidHelper extends BaseHelper {
39
+ constructor(opts) {
40
+ super({ scope: TokenUidHelper.name });
41
+ this.bytes = opts?.bytes ?? DEFAULT_TOKEN_BYTES;
42
+ if (!Number.isSafeInteger(this.bytes) || this.bytes < MIN_TOKEN_BYTES) {
43
+ throw getError({
44
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
45
+ message: `[${TokenUidHelper.name}] bytes must be an integer of at least ${MIN_TOKEN_BYTES} | value: ${this.bytes} | Fewer bytes than that can be guessed offline`,
46
+ });
47
+ }
48
+ this.encoding = opts?.encoding ?? UidTokenEncodings.BASE62;
49
+ if (!UidTokenEncodings.isValid(this.encoding)) {
50
+ throw getError({
51
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
52
+ message: `[${TokenUidHelper.name}] Unknown encoding | value: ${this.encoding} | valid: ${[...UidTokenEncodings.SCHEME_SET].join(', ')}`,
53
+ });
54
+ }
55
+ if (opts?.checksum !== undefined && typeof opts.checksum !== 'boolean') {
56
+ throw getError({
57
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
58
+ message: `[${TokenUidHelper.name}] checksum must be a boolean | value: ${String(opts.checksum)} | A config-derived "false" is truthy, so it is refused rather than read`,
59
+ });
60
+ }
61
+ this.checksum = opts?.checksum ?? false;
62
+ if (this.checksum && this.encoding === UidTokenEncodings.BASE64URL) {
63
+ throw getError({
64
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
65
+ message: `[${TokenUidHelper.name}] checksum is not available with the '${UidTokenEncodings.BASE64URL}' encoding | It has no fixed-width alphabet for the suffix | Use \`UidTokenEncodings.BASE62\` or \`HEX\``,
66
+ });
67
+ }
68
+ this.prefix = UidSegments.resolvePrefix({
69
+ scope: TokenUidHelper.name,
70
+ prefix: opts?.prefix,
71
+ caseForm: UidCaseForms.MIXED,
72
+ });
73
+ this.delimiter = UidSegments.resolveDelimiter({
74
+ scope: TokenUidHelper.name,
75
+ delimiter: opts?.delimiter,
76
+ hasPrefix: this.prefix.length > 0,
77
+ alphabet: TokenUidHelper.alphabetOf({ encoding: this.encoding }),
78
+ hint: `Use \`UidTokenEncodings.BASE62\` or \`HEX\`, or a delimiter outside the characters of '${this.encoding}'`,
79
+ });
80
+ }
81
+ /** `prefix` replaces the configured value for this call and turns the prefix on for it; the delimiter follows its own switch. */
82
+ nextId(opts) {
83
+ const head = UidSegments.resolveHead({
84
+ scope: TokenUidHelper.name,
85
+ override: opts?.prefix,
86
+ prefix: this.prefix,
87
+ delimiter: this.delimiter,
88
+ });
89
+ const body = this.randomBody();
90
+ return `${head}${body}${this.checksumOf({ body })}`;
91
+ }
92
+ /**
93
+ * A FORMAT filter, nothing more: does `opts.key` have the configured prefix and delimiter, the body
94
+ * length and alphabet of the configured `bytes` and `encoding`, and (when enabled) a matching
95
+ * checksum. Returns `false` on anything else, never throws, including for a value that is not a
96
+ * string.
97
+ *
98
+ * It is NOT authentication. CRC-32 is public and forgeable, so anyone can build a token that passes.
99
+ * A well-formed token still has to be looked up by its HASH and compared in constant time with
100
+ * `Hash.equals`. Use this to refuse a mistyped or truncated token before spending a lookup on it.
101
+ *
102
+ * The head checked is the CONFIGURED prefix and delimiter (none when the instance has no prefix); a
103
+ * token minted with a per-call prefix is checked by an instance configured with that prefix.
104
+ */
105
+ isWellFormed(opts) {
106
+ const token = opts?.key;
107
+ if (typeof token !== 'string') {
108
+ return false;
109
+ }
110
+ const head = UidSegments.resolveHead({
111
+ scope: TokenUidHelper.name,
112
+ prefix: this.prefix,
113
+ delimiter: this.delimiter,
114
+ });
115
+ if (!token.startsWith(head)) {
116
+ return false;
117
+ }
118
+ const rest = token.slice(head.length);
119
+ const bodyLength = this.bodyLength();
120
+ if (rest.length !== bodyLength + this.checksumLength()) {
121
+ return false;
122
+ }
123
+ const body = rest.slice(0, bodyLength);
124
+ const alphabet = TokenUidHelper.alphabetOf({ encoding: this.encoding });
125
+ for (const character of rest) {
126
+ if (!alphabet.includes(character)) {
127
+ return false;
128
+ }
129
+ }
130
+ return rest.slice(bodyLength) === this.checksumOf({ body });
131
+ }
132
+ bodyLength() {
133
+ switch (this.encoding) {
134
+ case UidTokenEncodings.HEX: {
135
+ return this.bytes * 2;
136
+ }
137
+ case UidTokenEncodings.BASE64URL: {
138
+ return Math.ceil((this.bytes * 4) / 3);
139
+ }
140
+ default: {
141
+ return Math.ceil((this.bytes * BITS_PER_BYTE) / BASE62_BITS_PER_CHARACTER);
142
+ }
143
+ }
144
+ }
145
+ checksumLength() {
146
+ if (!this.checksum) {
147
+ return 0;
148
+ }
149
+ return this.encoding === UidTokenEncodings.HEX ? HEX_CHECKSUM_LENGTH : BASE62_CHECKSUM_LENGTH;
150
+ }
151
+ /** The suffix for `body`: empty when the checksum is off, otherwise the CRC-32 of the body in the token's own alphabet, left-padded to a fixed width. */
152
+ checksumOf(opts) {
153
+ if (!this.checksum) {
154
+ return '';
155
+ }
156
+ let remaining = Crc32.of({ text: opts.body });
157
+ if (this.encoding === UidTokenEncodings.HEX) {
158
+ return remaining.toString(HEX_RADIX).padStart(HEX_CHECKSUM_LENGTH, '0');
159
+ }
160
+ const base = UidAlphabets.BASE62.length;
161
+ let text = '';
162
+ while (remaining > 0) {
163
+ text = UidAlphabets.BASE62[remaining % base] + text;
164
+ remaining = Math.floor(remaining / base);
165
+ }
166
+ return text.padStart(BASE62_CHECKSUM_LENGTH, UidAlphabets.BASE62[0]);
167
+ }
168
+ static alphabetOf(opts) {
169
+ switch (opts.encoding) {
170
+ case UidTokenEncodings.HEX: {
171
+ return HEX_ALPHABET;
172
+ }
173
+ case UidTokenEncodings.BASE64URL: {
174
+ return BASE64URL_ALPHABET;
175
+ }
176
+ default: {
177
+ return UidAlphabets.BASE62;
178
+ }
179
+ }
180
+ }
181
+ randomBody() {
182
+ if (this.encoding === UidTokenEncodings.BASE62) {
183
+ // Sampled, not encoded: 62 is not a power of two, so a base conversion of the bytes would be biased.
184
+ return UidRandom.sample({ alphabet: UidAlphabets.BASE62, length: this.bodyLength() });
185
+ }
186
+ return TokenUidHelper.encode({
187
+ bytes: UidRandom.bytes({ count: this.bytes }),
188
+ encoding: this.encoding,
189
+ });
190
+ }
191
+ /** Hand-written, not `Buffer`: this module ships to a browser, where `Buffer` does not exist. */
192
+ static encode(opts) {
193
+ const { bytes, encoding } = opts;
194
+ if (encoding === UidTokenEncodings.HEX) {
195
+ let hex = '';
196
+ for (const byte of bytes) {
197
+ hex += HEX_ALPHABET[byte >> 4] + HEX_ALPHABET[byte & 0x0f];
198
+ }
199
+ return hex;
200
+ }
201
+ // Three bytes are 24 bits, which is four 6-bit characters. A last group of one or two bytes
202
+ // gives two or three characters, and the `=` padding is left off.
203
+ let text = '';
204
+ for (let index = 0; index < bytes.length; index += 3) {
205
+ const chunk = (bytes[index] << 16) | ((bytes[index + 1] ?? 0) << 8) | (bytes[index + 2] ?? 0);
206
+ const remaining = bytes.length - index;
207
+ text += BASE64URL_ALPHABET[(chunk >> 18) & 0x3f] + BASE64URL_ALPHABET[(chunk >> 12) & 0x3f];
208
+ if (remaining > 1) {
209
+ text += BASE64URL_ALPHABET[(chunk >> 6) & 0x3f];
210
+ }
211
+ if (remaining > 2) {
212
+ text += BASE64URL_ALPHABET[chunk & 0x3f];
213
+ }
214
+ }
215
+ return text;
216
+ }
217
+ }
218
+ //# sourceMappingURL=token.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"token.js","sourceRoot":"","sources":["../../../../src/modules/uid/token.ts"],"names":[],"m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I,IAAI,GAAG,EAAE,CAAC;QAEd,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,KAAK,CAAC,MAAM,EAAE,KAAK,IAAI,CAAC,EAAE,CAAC;YACrD,MAAM,KAAK,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;YAC9F,MAAM,SAAS,GAAG,KAAK,CAAC,MAAM,GAAG,KAAK,CAAC;YAEvC,IAAI,IAAI,kBAAkB,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC,GAAG,IAAI,CAAC,GAAG,kBAAkB,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC;YAE5F,IAAI,SAAS,GAAG,CAAC,EAAE,CAAC;gBAClB,IAAI,IAAI,kBAAkB,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;YAClD,CAAC;YAED,IAAI,SAAS,GAAG,CAAC,EAAE,CAAC;gBAClB,IAAI,IAAI,kBAAkB,CAAC,KAAK,GAAG,IAAI,CAAC,CAAC;YAC3C,CAAC;QACH,CAAC;QAED,OAAO,IAAI,CAAC;IACd,CAAC;CACF","sourcesContent":["import { HTTP } from '@/common/constants';\nimport { BaseHelper } from '../base';\nimport { getError } from '../error';\nimport {\n DEFAULT_TOKEN_BYTES,\n MIN_TOKEN_BYTES,\n UidAlphabets,\n UidCaseForms,\n UidTokenEncodings,\n} from './common/constants';\nimport type { TUidTokenEncoding } from './common/constants';\nimport { Crc32 } from './common/crc32';\nimport { UidRandom } from './common/random';\nimport { UidSegments } from './common/segments';\nimport type { INextTokenUidOptions, ITokenUidOptions } from './common/types';\n\nconst BASE64URL_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';\nconst HEX_ALPHABET = '0123456789abcdef';\n\nconst BITS_PER_BYTE = 8;\nconst HEX_RADIX = 16;\n\n/** 62^6 is more than 2^32, so six base62 characters hold any CRC-32. */\nconst BASE62_CHECKSUM_LENGTH = 6;\n/** Eight hex characters are 32 bits. */\nconst HEX_CHECKSUM_LENGTH = 8;\n\n/** Bits one BASE62 character carries. */\nconst BASE62_BITS_PER_CHARACTER = Math.log2(UidAlphabets.BASE62.length);\n\n/**\n * Secret tokens: random bytes from the platform CSPRNG, written as base62 (the default), hex or\n * base64url, optionally prefixed. Use it for a secret - a verification link, an API key, a session id, a password reset.\n *\n * - STORE A HASH, not the token. A database leak then leaks nothing a caller can replay.\n * - COMPARE IN CONSTANT TIME with `Hash.equals` (`crypto/algorithms/hash.algorithm.ts`), never `===`.\n * - Use `OpaqueUidHelper` for a short id a human reads, and `NumericUidHelper` for a code a human types.\n *\n * `bytes` is the entropy, not the text length: the constructor refuses anything under\n * {@link MIN_TOKEN_BYTES} (128 bits). The finished string is `prefix + delimiter + body`. A base62\n * body is `ceil(bytes * 8 / log2(62))` characters (32 bytes is 43), a hex body `bytes * 2`, a\n * base64url body `ceil(bytes * 4 / 3)`.\n *\n * `checksum: true` appends a CRC-32 of the body, so `isWellFormed` can reject a mistyped token before\n * any lookup. Enable it for a long-lived key a person copies, not for a one-shot link.\n *\n * The prefix and delimiter follow `OpaqueUidHelper`'s rules, with no `caseForm`: a token's case is\n * its encoding's. A delimiter must sit outside the encoding's characters. `_` and `-` work with\n * base62 and hex; base64url holds both, so it takes only a delimiter such as `.`.\n */\nexport class TokenUidHelper extends BaseHelper {\n private readonly bytes: number;\n private readonly encoding: TUidTokenEncoding;\n private readonly prefix: string;\n private readonly delimiter: string;\n private readonly checksum: boolean;\n\n constructor(opts?: ITokenUidOptions) {\n super({ scope: TokenUidHelper.name });\n\n this.bytes = opts?.bytes ?? DEFAULT_TOKEN_BYTES;\n\n if (!Number.isSafeInteger(this.bytes) || this.bytes < MIN_TOKEN_BYTES) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${TokenUidHelper.name}] bytes must be an integer of at least ${MIN_TOKEN_BYTES} | value: ${this.bytes} | Fewer bytes than that can be guessed offline`,\n });\n }\n\n this.encoding = opts?.encoding ?? UidTokenEncodings.BASE62;\n\n if (!UidTokenEncodings.isValid(this.encoding)) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${TokenUidHelper.name}] Unknown encoding | value: ${this.encoding} | valid: ${[...UidTokenEncodings.SCHEME_SET].join(', ')}`,\n });\n }\n\n if (opts?.checksum !== undefined && typeof opts.checksum !== 'boolean') {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${TokenUidHelper.name}] checksum must be a boolean | value: ${String(opts.checksum)} | A config-derived \"false\" is truthy, so it is refused rather than read`,\n });\n }\n\n this.checksum = opts?.checksum ?? false;\n\n if (this.checksum && this.encoding === UidTokenEncodings.BASE64URL) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${TokenUidHelper.name}] checksum is not available with the '${UidTokenEncodings.BASE64URL}' encoding | It has no fixed-width alphabet for the suffix | Use \\`UidTokenEncodings.BASE62\\` or \\`HEX\\``,\n });\n }\n\n this.prefix = UidSegments.resolvePrefix({\n scope: TokenUidHelper.name,\n prefix: opts?.prefix,\n caseForm: UidCaseForms.MIXED,\n });\n this.delimiter = UidSegments.resolveDelimiter({\n scope: TokenUidHelper.name,\n delimiter: opts?.delimiter,\n hasPrefix: this.prefix.length > 0,\n alphabet: TokenUidHelper.alphabetOf({ encoding: this.encoding }),\n hint: `Use \\`UidTokenEncodings.BASE62\\` or \\`HEX\\`, or a delimiter outside the characters of '${this.encoding}'`,\n });\n }\n\n /** `prefix` replaces the configured value for this call and turns the prefix on for it; the delimiter follows its own switch. */\n nextId(opts?: INextTokenUidOptions): string {\n const head = UidSegments.resolveHead({\n scope: TokenUidHelper.name,\n override: opts?.prefix,\n prefix: this.prefix,\n delimiter: this.delimiter,\n });\n\n const body = this.randomBody();\n\n return `${head}${body}${this.checksumOf({ body })}`;\n }\n\n /**\n * A FORMAT filter, nothing more: does `opts.key` have the configured prefix and delimiter, the body\n * length and alphabet of the configured `bytes` and `encoding`, and (when enabled) a matching\n * checksum. Returns `false` on anything else, never throws, including for a value that is not a\n * string.\n *\n * It is NOT authentication. CRC-32 is public and forgeable, so anyone can build a token that passes.\n * A well-formed token still has to be looked up by its HASH and compared in constant time with\n * `Hash.equals`. Use this to refuse a mistyped or truncated token before spending a lookup on it.\n *\n * The head checked is the CONFIGURED prefix and delimiter (none when the instance has no prefix); a\n * token minted with a per-call prefix is checked by an instance configured with that prefix.\n */\n isWellFormed(opts: { key: string }): boolean {\n const token = opts?.key;\n\n if (typeof token !== 'string') {\n return false;\n }\n\n const head = UidSegments.resolveHead({\n scope: TokenUidHelper.name,\n prefix: this.prefix,\n delimiter: this.delimiter,\n });\n\n if (!token.startsWith(head)) {\n return false;\n }\n\n const rest = token.slice(head.length);\n const bodyLength = this.bodyLength();\n\n if (rest.length !== bodyLength + this.checksumLength()) {\n return false;\n }\n\n const body = rest.slice(0, bodyLength);\n const alphabet = TokenUidHelper.alphabetOf({ encoding: this.encoding });\n\n for (const character of rest) {\n if (!alphabet.includes(character)) {\n return false;\n }\n }\n\n return rest.slice(bodyLength) === this.checksumOf({ body });\n }\n\n private bodyLength(): number {\n switch (this.encoding) {\n case UidTokenEncodings.HEX: {\n return this.bytes * 2;\n }\n case UidTokenEncodings.BASE64URL: {\n return Math.ceil((this.bytes * 4) / 3);\n }\n default: {\n return Math.ceil((this.bytes * BITS_PER_BYTE) / BASE62_BITS_PER_CHARACTER);\n }\n }\n }\n\n private checksumLength(): number {\n if (!this.checksum) {\n return 0;\n }\n\n return this.encoding === UidTokenEncodings.HEX ? HEX_CHECKSUM_LENGTH : BASE62_CHECKSUM_LENGTH;\n }\n\n /** The suffix for `body`: empty when the checksum is off, otherwise the CRC-32 of the body in the token's own alphabet, left-padded to a fixed width. */\n private checksumOf(opts: { body: string }): string {\n if (!this.checksum) {\n return '';\n }\n\n let remaining = Crc32.of({ text: opts.body });\n\n if (this.encoding === UidTokenEncodings.HEX) {\n return remaining.toString(HEX_RADIX).padStart(HEX_CHECKSUM_LENGTH, '0');\n }\n\n const base = UidAlphabets.BASE62.length;\n let text = '';\n\n while (remaining > 0) {\n text = UidAlphabets.BASE62[remaining % base] + text;\n remaining = Math.floor(remaining / base);\n }\n\n return text.padStart(BASE62_CHECKSUM_LENGTH, UidAlphabets.BASE62[0]);\n }\n\n private static alphabetOf(opts: { encoding: TUidTokenEncoding }): string {\n switch (opts.encoding) {\n case UidTokenEncodings.HEX: {\n return HEX_ALPHABET;\n }\n case UidTokenEncodings.BASE64URL: {\n return BASE64URL_ALPHABET;\n }\n default: {\n return UidAlphabets.BASE62;\n }\n }\n }\n\n private randomBody(): string {\n if (this.encoding === UidTokenEncodings.BASE62) {\n // Sampled, not encoded: 62 is not a power of two, so a base conversion of the bytes would be biased.\n return UidRandom.sample({ alphabet: UidAlphabets.BASE62, length: this.bodyLength() });\n }\n\n return TokenUidHelper.encode({\n bytes: UidRandom.bytes({ count: this.bytes }),\n encoding: this.encoding,\n });\n }\n\n /** Hand-written, not `Buffer`: this module ships to a browser, where `Buffer` does not exist. */\n private static encode(opts: { bytes: Uint8Array; encoding: TUidTokenEncoding }): string {\n const { bytes, encoding } = opts;\n\n if (encoding === UidTokenEncodings.HEX) {\n let hex = '';\n\n for (const byte of bytes) {\n hex += HEX_ALPHABET[byte >> 4] + HEX_ALPHABET[byte & 0x0f];\n }\n\n return hex;\n }\n\n // Three bytes are 24 bits, which is four 6-bit characters. A last group of one or two bytes\n // gives two or three characters, and the `=` padding is left off.\n let text = '';\n\n for (let index = 0; index < bytes.length; index += 3) {\n const chunk = (bytes[index] << 16) | ((bytes[index + 1] ?? 0) << 8) | (bytes[index + 2] ?? 0);\n const remaining = bytes.length - index;\n\n text += BASE64URL_ALPHABET[(chunk >> 18) & 0x3f] + BASE64URL_ALPHABET[(chunk >> 12) & 0x3f];\n\n if (remaining > 1) {\n text += BASE64URL_ALPHABET[(chunk >> 6) & 0x3f];\n }\n\n if (remaining > 2) {\n text += BASE64URL_ALPHABET[chunk & 0x3f];\n }\n }\n\n return text;\n }\n}\n"]}
@@ -2,7 +2,8 @@ import { BaseHelper } from '../../base.js';
2
2
  import type { IUuidInspection } from './common/types.js';
3
3
  /**
4
4
  * One door for every UUID IGNIS mints: `v7()` for a database key, `v5()` for a deterministic key,
5
- * `v4()` for a random token.
5
+ * `v4()` for a random public identifier. For a secret (a verification link, an API key, a session id)
6
+ * use `TokenUidHelper` instead: a UUID v4 carries 122 random bits and a fixed, recognisable shape.
6
7
  *
7
8
  * A facade over {@link UuidV4Generator}, {@link UuidV5Generator} and {@link UuidV7Generator} - importing one of those from
8
9
  * `@venizia/ignis-helpers/uuid` leaves the other two out of a browser bundle.
@@ -5,7 +5,8 @@ import { UuidV5Generator } from './v5.js';
5
5
  import { UuidV7Generator } from './v7.js';
6
6
  /**
7
7
  * One door for every UUID IGNIS mints: `v7()` for a database key, `v5()` for a deterministic key,
8
- * `v4()` for a random token.
8
+ * `v4()` for a random public identifier. For a secret (a verification link, an API key, a session id)
9
+ * use `TokenUidHelper` instead: a UUID v4 carries 122 random bits and a fixed, recognisable shape.
9
10
  *
10
11
  * A facade over {@link UuidV4Generator}, {@link UuidV5Generator} and {@link UuidV7Generator} - importing one of those from
11
12
  * `@venizia/ignis-helpers/uuid` leaves the other two out of a browser bundle.
@@ -1 +1 @@
1
- {"version":3,"file":"helper.js","sourceRoot":"","sources":["../../../../../src/modules/uid/uuid/helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD,OAAO,EAAE,e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,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;QAEjF,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,IAAI,IAAI,CAAC,YAAY,CAAC,EAAE,CAAC;IACxD,CAAC;CACF","sourcesContent":["import { BaseHelper } from '../../base';\nimport { UUID_PATTERN } from './common/constants';\nimport type { IUuidInspection } from './common/types';\nimport { UuidV4Generator } from './v4';\nimport { UuidV5Generator } from './v5';\nimport { UuidV7Generator } from './v7';\n\n/**\n * One door for every UUID IGNIS mints: `v7()` for a database key, `v5()` for a deterministic key,\n * `v4()` for a random token.\n *\n * A facade over {@link UuidV4Generator}, {@link UuidV5Generator} and {@link UuidV7Generator} - importing one of those from\n * `@venizia/ignis-helpers/uuid` leaves the other two out of a browser bundle.\n */\nexport class UuidHelper extends BaseHelper {\n /**\n * Per module copy, not realm-wide: the facade holds no state - ordering lives in the shared v7\n * sequence - and a realm-wide slot would hand an older version's instance, and its generators,\n * to every newer caller.\n */\n private static instance?: UuidHelper;\n\n /** Random - a public identifier or a token. */\n readonly v4: () => string = UuidV4Generator.generate;\n\n /** Deterministic - same inputs, same id. Reproducible therefore not secret. */\n readonly v5: (opts: { namespace: string; name: string }) => string = UuidV5Generator.generate;\n\n /** Time-ordered - a database key. A burst past about 2048 ids per millisecond leads the wall clock. */\n readonly v7: () => string = UuidV7Generator.generate;\n\n constructor(opts?: { scope?: string }) {\n super({ scope: opts?.scope ?? UuidHelper.name });\n }\n\n static getInstance(): UuidHelper {\n UuidHelper.instance ??= new UuidHelper();\n\n return UuidHelper.instance;\n }\n\n /** Lowercase, version 1-8, RFC variant - the nil and max placeholders are refused. */\n static isValid(value: string): boolean {\n return UUID_PATTERN.test(value);\n }\n\n /** Reads the version, and for v7 the creation time; undefined when it is not a UUID. */\n inspect(opts: { value: string }): IUuidInspection | undefined {\n const { value } = opts;\n\n if (!UUID_PATTERN.test(value)) {\n return undefined;\n }\n\n const version = Number.parseInt(value[14], 16);\n\n if (version !== 7) {\n return { version };\n }\n\n const milliseconds = Number.parseInt(value.slice(0, 8) + value.slice(9, 13), 16);\n\n return { version, createdAt: new Date(milliseconds) };\n }\n}\n"]}
1
+ {"version":3,"file":"helper.js","sourceRoot":"","sources":["../../../../../src/modules/uid/uuid/helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD,OAAO,EAAE,eAAe,EAAE,MAAM,MAAM,CAAC;AACvC,OAAO,EAAE,eAAe,EAAE,MAAM,MAAM,CAAC;AACvC,OAAO,EAAE,eAAe,EAAE,MAAM,MAAM,CAAC;AAEvC;;;;;;;GAOG;AACH,MAAM,OAAO,UAAW,SAAQ,UAAU;IAiBxC,YAAY,IAAyB;QACnC,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,IAAI,UAAU,CAAC,IAAI,EAAE,CAAC,CAAC;QAVnD,+CAA+C;QACtC,OAAE,GAAiB,eAAe,CAAC,QAAQ,CAAC;QAErD,+EAA+E;QACtE,OAAE,GAA0D,eAAe,CAAC,QAAQ,CAAC;QAE9F,uGAAuG;QAC9F,OAAE,GAAiB,eAAe,CAAC,QAAQ,CAAC;IAIrD,CAAC;IAED,MAAM,CAAC,WAAW;QAChB,UAAU,CAAC,QAAQ,KAAK,IAAI,UAAU,EAAE,CAAC;QAEzC,OAAO,UAAU,CAAC,QAAQ,CAAC;IAC7B,CAAC;IAED,sFAAsF;IACtF,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAClC,CAAC;IAED,wFAAwF;IACxF,OAAO,CAAC,IAAuB;QAC7B,MAAM,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC;QAEvB,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;YAC9B,OAAO,SAAS,CAAC;QACnB,CAAC;QAED,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;QAE/C,IAAI,OAAO,KAAK,CAAC,EAAE,CAAC;YAClB,OAAO,EAAE,OAAO,EAAE,CAAC;QACrB,CAAC;QAED,MAAM,YAAY,GAAG,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;QAEjF,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,IAAI,IAAI,CAAC,YAAY,CAAC,EAAE,CAAC;IACxD,CAAC;CACF","sourcesContent":["import { BaseHelper } from '../../base';\nimport { UUID_PATTERN } from './common/constants';\nimport type { IUuidInspection } from './common/types';\nimport { UuidV4Generator } from './v4';\nimport { UuidV5Generator } from './v5';\nimport { UuidV7Generator } from './v7';\n\n/**\n * One door for every UUID IGNIS mints: `v7()` for a database key, `v5()` for a deterministic key,\n * `v4()` for a random public identifier. For a secret (a verification link, an API key, a session id)\n * use `TokenUidHelper` instead: a UUID v4 carries 122 random bits and a fixed, recognisable shape.\n *\n * A facade over {@link UuidV4Generator}, {@link UuidV5Generator} and {@link UuidV7Generator} - importing one of those from\n * `@venizia/ignis-helpers/uuid` leaves the other two out of a browser bundle.\n */\nexport class UuidHelper extends BaseHelper {\n /**\n * Per module copy, not realm-wide: the facade holds no state - ordering lives in the shared v7\n * sequence - and a realm-wide slot would hand an older version's instance, and its generators,\n * to every newer caller.\n */\n private static instance?: UuidHelper;\n\n /** Random - a public identifier or a token. */\n readonly v4: () => string = UuidV4Generator.generate;\n\n /** Deterministic - same inputs, same id. Reproducible therefore not secret. */\n readonly v5: (opts: { namespace: string; name: string }) => string = UuidV5Generator.generate;\n\n /** Time-ordered - a database key. A burst past about 2048 ids per millisecond leads the wall clock. */\n readonly v7: () => string = UuidV7Generator.generate;\n\n constructor(opts?: { scope?: string }) {\n super({ scope: opts?.scope ?? UuidHelper.name });\n }\n\n static getInstance(): UuidHelper {\n UuidHelper.instance ??= new UuidHelper();\n\n return UuidHelper.instance;\n }\n\n /** Lowercase, version 1-8, RFC variant - the nil and max placeholders are refused. */\n static isValid(value: string): boolean {\n return UUID_PATTERN.test(value);\n }\n\n /** Reads the version, and for v7 the creation time; undefined when it is not a UUID. */\n inspect(opts: { value: string }): IUuidInspection | undefined {\n const { value } = opts;\n\n if (!UUID_PATTERN.test(value)) {\n return undefined;\n }\n\n const version = Number.parseInt(value[14], 16);\n\n if (version !== 7) {\n return { version };\n }\n\n const milliseconds = Number.parseInt(value.slice(0, 8) + value.slice(9, 13), 16);\n\n return { version, createdAt: new Date(milliseconds) };\n }\n}\n"]}
@@ -12,6 +12,11 @@ export declare class ParseUtility {
12
12
  private static round;
13
13
  /** Arrays stay arrays - mapping one through the object branch would turn it into an index-keyed object - but their object elements still need their keys camelized. Dates are opaque values. */
14
14
  private static camelizeValue;
15
+ /**
16
+ * Ten uppercase base36 characters (`0-9A-Z`) from the platform CSPRNG, about 51 bits. Two draws of
17
+ * five characters, because one draw covers at most `2 ** 48` and ten base36 characters need more.
18
+ * A throwaway key for a test or a label, not a secret: use `TokenUidHelper` for a secret.
19
+ */
15
20
  static getUID(): string;
16
21
  static toCamel(opts: {
17
22
  input: string;