@apifuse/provider-sdk 2.2.0-beta.33 → 2.2.0-beta.36

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.
@@ -7,6 +7,7 @@ import {
7
7
  TurnValidationError,
8
8
  ValidationError,
9
9
  } from "../errors.js";
10
+ import type { AuthStartNoInputGuard } from "../define.js";
10
11
  import type { AuthFlowDefinition, AuthFlowInputHandler, AuthTurn, FlowContext } from "../types.js";
11
12
 
12
13
  type TurnKind = KnownAuthTurnKind;
@@ -224,6 +225,18 @@ export function validateCeremonyOutput(turn: unknown): AuthTurn {
224
225
  return turn as AuthTurn;
225
226
  }
226
227
 
228
+ /**
229
+ * Defines an auth flow while preserving its concrete type for downstream checks.
230
+ * The compile-time guard validates the inferred literal; annotating or widening
231
+ * a flow to `AuthFlowDefinition` before passing it defeats the check. Full
232
+ * enforcement requires branding, which is deferred to a future major.
233
+ */
234
+ export function defineAuthFlow<const TFlow extends AuthFlowDefinition>(
235
+ flow: TFlow & AuthStartNoInputGuard<TFlow>,
236
+ ): TFlow {
237
+ return flow;
238
+ }
239
+
227
240
  export function createOAuth2Ceremony(options: {
228
241
  authorizeUrl: string;
229
242
  tokenUrl: string;
@@ -232,7 +245,7 @@ export function createOAuth2Ceremony(options: {
232
245
  scopes: string[];
233
246
  usePKCE?: boolean;
234
247
  }): AuthFlowDefinition {
235
- return {
248
+ return defineAuthFlow({
236
249
  start: (ctx) =>
237
250
  runCeremonyHandler(
238
251
  async () => {
@@ -306,7 +319,7 @@ export function createOAuth2Ceremony(options: {
306
319
  input,
307
320
  ),
308
321
  abort: async () => validateCeremonyOutput(createTurn("abort", { hint: "OAuth flow aborted." })),
309
- };
322
+ });
310
323
  }
311
324
 
312
325
  /**
@@ -384,7 +397,7 @@ export function createDeviceFlowCeremony(options: {
384
397
  clientSecretEnvKey?: string;
385
398
  scopes: string[];
386
399
  }): AuthFlowDefinition {
387
- return {
400
+ return defineAuthFlow({
388
401
  start: (ctx) =>
389
402
  runCeremonyHandler(
390
403
  async () => {
@@ -461,7 +474,7 @@ export function createDeviceFlowCeremony(options: {
461
474
  ),
462
475
  abort: async () =>
463
476
  validateCeremonyOutput(createTurn("abort", { hint: "Device flow aborted." })),
464
- };
477
+ });
465
478
  }
466
479
 
467
480
  export function createWebAuthnCeremony(options: {
@@ -470,7 +483,7 @@ export function createWebAuthnCeremony(options: {
470
483
  verifyUrl?: string;
471
484
  timeoutMs?: number;
472
485
  }): AuthFlowDefinition {
473
- return {
486
+ return defineAuthFlow({
474
487
  start: (ctx) =>
475
488
  runCeremonyHandler(
476
489
  async () => {
@@ -529,7 +542,7 @@ export function createWebAuthnCeremony(options: {
529
542
  ),
530
543
  abort: async () =>
531
544
  validateCeremonyOutput(createTurn("abort", { hint: "WebAuthn ceremony aborted." })),
532
- };
545
+ });
533
546
  }
534
547
 
535
548
  export function createMagicLinkCeremony(options: {
@@ -539,23 +552,31 @@ export function createMagicLinkCeremony(options: {
539
552
  expiresInMs?: number;
540
553
  }): AuthFlowDefinition {
541
554
  const emailField = options.emailField ?? "email";
555
+ const buildEmailForm = () =>
556
+ buildJsonSchemaForm(
557
+ {
558
+ type: "object",
559
+ required: [emailField],
560
+ properties: {
561
+ [emailField]: { type: "string", format: "email" },
562
+ },
563
+ },
564
+ "Provide the email address to receive a magic link.",
565
+ );
542
566
 
543
- return {
544
- start: (ctx, input = {}) =>
567
+ return defineAuthFlow({
568
+ start: (ctx) =>
569
+ runCeremonyHandler(
570
+ async () => buildEmailForm(),
571
+ "Magic link start failed",
572
+ ctx,
573
+ ),
574
+ continue: (ctx, input = {}) =>
545
575
  runCeremonyHandler(
546
576
  async () => {
547
577
  const email = getString(input, emailField);
548
578
  if (!email) {
549
- return buildJsonSchemaForm(
550
- {
551
- type: "object",
552
- required: [emailField],
553
- properties: {
554
- [emailField]: { type: "string", format: "email" },
555
- },
556
- },
557
- "Provide the email address to receive a magic link.",
558
- );
579
+ return buildEmailForm();
559
580
  }
560
581
 
561
582
  await ctx.http.post(options.sendUrl, { email });
@@ -570,17 +591,10 @@ export function createMagicLinkCeremony(options: {
570
591
  timing: { suggestedPollIntervalMs: 5_000, maxWaitMs: 300_000 },
571
592
  });
572
593
  },
573
- "Magic link start failed",
594
+ "Magic link continuation failed",
574
595
  ctx,
575
596
  input,
576
597
  ),
577
- continue: async () =>
578
- validateCeremonyOutput(
579
- createTurn("poll", {
580
- hint: "Continue polling for magic link completion.",
581
- timing: { suggestedPollIntervalMs: 5_000, maxWaitMs: 300_000 },
582
- }),
583
- ),
584
598
  poll: (ctx) =>
585
599
  runCeremonyHandler(
586
600
  async () => {
@@ -616,7 +630,7 @@ export function createMagicLinkCeremony(options: {
616
630
  ),
617
631
  abort: async () =>
618
632
  validateCeremonyOutput(createTurn("abort", { hint: "Magic link flow aborted." })),
619
- };
633
+ });
620
634
  }
621
635
 
622
636
  export function createFormCeremony(options: {
@@ -624,7 +638,7 @@ export function createFormCeremony(options: {
624
638
  hint?: string;
625
639
  mapCredential?: (input: Record<string, unknown>) => JsonObject;
626
640
  }): AuthFlowDefinition {
627
- return {
641
+ return defineAuthFlow({
628
642
  start: async () =>
629
643
  validateCeremonyOutput(
630
644
  buildJsonSchemaForm(
@@ -656,7 +670,7 @@ export function createFormCeremony(options: {
656
670
  ),
657
671
  abort: async () =>
658
672
  validateCeremonyOutput(createTurn("abort", { hint: "Form ceremony aborted." })),
659
- };
673
+ });
660
674
  }
661
675
 
662
676
  export function combineCeremonies(...ceremonies: AuthFlowDefinition[]): AuthFlowDefinition {
@@ -739,7 +753,7 @@ export function createSwitchCeremony(options: {
739
753
  }): AuthFlowDefinition {
740
754
  const choiceKeys = Object.keys(options.choices);
741
755
 
742
- return {
756
+ return defineAuthFlow({
743
757
  start: async () =>
744
758
  validateCeremonyOutput(
745
759
  createTurn("multi_choice", {
@@ -811,5 +825,5 @@ export function createSwitchCeremony(options: {
811
825
  "Switch ceremony abort failed",
812
826
  ctx,
813
827
  ),
814
- };
828
+ });
815
829
  }
@@ -1,6 +1,6 @@
1
1
  FROM oven/bun:1.2-alpine
2
2
  WORKDIR /provider
3
- COPY package.json bun.lockb* ./
3
+ COPY package.json bun.lock ./
4
4
  RUN bun install --frozen-lockfile
5
5
  COPY . .
6
6
  EXPOSE 3000
package/src/define.ts CHANGED
@@ -249,17 +249,318 @@ type WebSocketOperationConfig<TInput extends SchemaLike, TOutput extends SchemaL
249
249
  ): Response | ReadableStream<Uint8Array> | Promise<Response | ReadableStream<Uint8Array>>;
250
250
  };
251
251
 
252
- type AuthStartNoInputGuard<TConfig> = TConfig extends {
252
+ type AuthStartHandlerNoInputGuard<TStart> = TStart extends (...args: infer TArgs) => unknown
253
+ ? TArgs["length"] extends 0 | 1
254
+ ? unknown
255
+ : {
256
+ "auth start handlers must not declare input parameters; return a form turn from start and receive user input in continue": never;
257
+ }
258
+ : unknown;
259
+
260
+ export type AuthStartNoInputGuard<TConfig> = TConfig extends {
253
261
  auth?: { flow?: { start: infer TStart } };
254
262
  }
255
- ? TStart extends (...args: infer TArgs) => unknown
256
- ? TArgs extends [unknown]
257
- ? unknown
258
- : {
259
- "auth start handlers must not declare input parameters; return a form turn from start and receive user input in continue": never;
263
+ ? AuthStartHandlerNoInputGuard<TStart>
264
+ : TConfig extends { start: infer TStart }
265
+ ? AuthStartHandlerNoInputGuard<TStart>
266
+ : unknown;
267
+
268
+ function splitAuthStartParameters(parameters: string): string[] | undefined {
269
+ const parts: string[] = [];
270
+ let start = 0;
271
+ let round = 0;
272
+ let square = 0;
273
+ let curly = 0;
274
+ let quote: "'" | '"' | "`" | undefined;
275
+ let escaped = false;
276
+ let lineComment = false;
277
+ let blockComment = false;
278
+ const templateDepths = [0];
279
+ templateDepths.length = 0;
280
+
281
+ for (let index = 0; index < parameters.length; index++) {
282
+ const character = parameters[index];
283
+ const nextCharacter = parameters[index + 1];
284
+ if (lineComment) {
285
+ if (character === "\n" || character === "\r") lineComment = false;
286
+ else continue;
287
+ }
288
+ if (blockComment) {
289
+ if (character === "*" && nextCharacter === "/") {
290
+ blockComment = false;
291
+ index++;
292
+ }
293
+ continue;
294
+ }
295
+ if (quote) {
296
+ if (escaped) {
297
+ escaped = false;
298
+ } else if (character === "\\") {
299
+ escaped = true;
300
+ } else if (quote === "`" && character === "$" && nextCharacter === "{") {
301
+ curly++;
302
+ templateDepths.push(curly);
303
+ quote = undefined;
304
+ index++;
305
+ } else if (character === quote) {
306
+ quote = undefined;
307
+ }
308
+ continue;
309
+ }
310
+ if (character === "'" || character === '"' || character === "`") {
311
+ quote = character;
312
+ continue;
313
+ }
314
+ if (character === "/" && nextCharacter === "/") {
315
+ lineComment = true;
316
+ index++;
317
+ continue;
318
+ }
319
+ if (character === "/" && nextCharacter === "*") {
320
+ blockComment = true;
321
+ index++;
322
+ continue;
323
+ }
324
+ if (character === "/") return undefined;
325
+ // Annex B HTML-like comments are not lexed here; give up rather than
326
+ // risk misreading the parameter list.
327
+ if (character === "<" && parameters.startsWith("!--", index + 1)) return undefined;
328
+ if (character === "-" && parameters.startsWith("->", index + 1)) return undefined;
329
+ if (character === "(") round++;
330
+ else if (character === ")") round--;
331
+ else if (character === "[") square++;
332
+ else if (character === "]") square--;
333
+ else if (character === "{") curly++;
334
+ else if (character === "}") {
335
+ if (templateDepths.at(-1) === curly) {
336
+ templateDepths.pop();
337
+ curly--;
338
+ quote = "`";
339
+ } else curly--;
340
+ } else if (character === "," && round === 0 && square === 0 && curly === 0) {
341
+ parts.push(parameters.slice(start, index));
342
+ start = index + 1;
343
+ }
344
+ if (round < 0 || square < 0 || curly < 0) return undefined;
345
+ }
346
+
347
+ if (
348
+ quote ||
349
+ blockComment ||
350
+ templateDepths.length > 0 ||
351
+ round !== 0 ||
352
+ square !== 0 ||
353
+ curly !== 0
354
+ )
355
+ return undefined;
356
+ parts.push(parameters.slice(start));
357
+ return parts;
358
+ }
359
+
360
+ function authStartParameterList(source: string): string | undefined {
361
+ let index = 0;
362
+ while (index < source.length && /\s/.test(source[index] ?? "")) index++;
363
+ if (index >= source.length) return undefined;
364
+
365
+ let openIndex = -1;
366
+ let parenthesizedArrow = false;
367
+ let asyncMethodOrArrow = false;
368
+ const skipTrivia = () => {
369
+ while (index < source.length) {
370
+ if (/\s/.test(source[index] ?? "")) {
371
+ index++;
372
+ continue;
373
+ }
374
+ if (source[index] === "/" && source[index + 1] === "/") {
375
+ index += 2;
376
+ while (index < source.length && source[index] !== "\n" && source[index] !== "\r") index++;
377
+ continue;
378
+ }
379
+ if (source[index] === "/" && source[index + 1] === "*") {
380
+ const end = source.indexOf("*/", index + 2);
381
+ if (end < 0) {
382
+ index = source.length;
383
+ return;
260
384
  }
261
- : unknown
262
- : unknown;
385
+ index = end + 2;
386
+ continue;
387
+ }
388
+ return;
389
+ }
390
+ };
391
+
392
+ const initial = source.slice(index);
393
+ const isAsync = initial.startsWith("async") && !/[\w$]/.test(initial[5] ?? "");
394
+ if (isAsync) {
395
+ index += 5;
396
+ skipTrivia();
397
+ }
398
+
399
+ const afterAsync = source.slice(index);
400
+ const isFunction = afterAsync.startsWith("function") && !/[\w$]/.test(afterAsync[8] ?? "");
401
+ if (isFunction) {
402
+ index += 8;
403
+ skipTrivia();
404
+ if (source[index] === "*") {
405
+ index++;
406
+ skipTrivia();
407
+ }
408
+ } else if (source[index] === "*") {
409
+ index++;
410
+ skipTrivia();
411
+ }
412
+
413
+ if (source[index] === "(") {
414
+ openIndex = index;
415
+ parenthesizedArrow = !isFunction;
416
+ asyncMethodOrArrow = isAsync && !isFunction;
417
+ } else if (isFunction) {
418
+ if (!/[A-Za-z_$]/.test(source[index] ?? "")) return undefined;
419
+ index++;
420
+ while (index < source.length && /[A-Za-z0-9_$]/.test(source[index] ?? "")) index++;
421
+ skipTrivia();
422
+ if (source[index] !== "(") return undefined;
423
+ openIndex = index;
424
+ } else {
425
+ const identifierStart = index;
426
+ if (!/[A-Za-z_$]/.test(source[index] ?? "")) return undefined;
427
+ index++;
428
+ while (index < source.length && /[A-Za-z0-9_$]/.test(source[index] ?? "")) index++;
429
+ const firstIdentifier = source.slice(identifierStart, index);
430
+ skipTrivia();
431
+ if (source[index] === "=" && source[index + 1] === ">") return undefined;
432
+ if (source[index] !== "(") {
433
+ if (firstIdentifier !== "get" && firstIdentifier !== "set") return undefined;
434
+ if (!/[A-Za-z_$]/.test(source[index] ?? "")) return undefined;
435
+ index++;
436
+ while (index < source.length && /[A-Za-z0-9_$]/.test(source[index] ?? "")) index++;
437
+ skipTrivia();
438
+ }
439
+ if (source[index] !== "(") return undefined;
440
+ openIndex = index;
441
+ }
442
+ if (openIndex < 0) return undefined;
443
+
444
+ let depth = 1;
445
+ let square = 0;
446
+ let curly = 0;
447
+ let quote: "'" | '"' | "`" | undefined;
448
+ let escaped = false;
449
+ let lineComment = false;
450
+ let blockComment = false;
451
+ const templateDepths = [0];
452
+ templateDepths.length = 0;
453
+ for (index = openIndex + 1; index < source.length; index++) {
454
+ const character = source[index];
455
+ const nextCharacter = source[index + 1];
456
+ if (lineComment) {
457
+ if (character === "\n" || character === "\r") lineComment = false;
458
+ else continue;
459
+ }
460
+ if (blockComment) {
461
+ if (character === "*" && nextCharacter === "/") {
462
+ blockComment = false;
463
+ index++;
464
+ }
465
+ continue;
466
+ }
467
+ if (quote) {
468
+ if (escaped) escaped = false;
469
+ else if (character === "\\") escaped = true;
470
+ else if (quote === "`" && character === "$" && nextCharacter === "{") {
471
+ curly++;
472
+ templateDepths.push(curly);
473
+ quote = undefined;
474
+ index++;
475
+ } else if (character === quote) quote = undefined;
476
+ continue;
477
+ }
478
+ if (character === "'" || character === '"' || character === "`") {
479
+ quote = character;
480
+ continue;
481
+ }
482
+ if (character === "/" && nextCharacter === "/") {
483
+ lineComment = true;
484
+ index++;
485
+ continue;
486
+ }
487
+ if (character === "/" && nextCharacter === "*") {
488
+ blockComment = true;
489
+ index++;
490
+ continue;
491
+ }
492
+ if (character === "/") return undefined;
493
+ // Annex B HTML-like comments are not lexed here; give up rather than
494
+ // risk misreading the parameter list.
495
+ if (character === "<" && source.startsWith("!--", index + 1)) return undefined;
496
+ if (character === "-" && source.startsWith("->", index + 1)) return undefined;
497
+ if (character === "(") depth++;
498
+ else if (character === ")") {
499
+ depth--;
500
+ if (depth === 0 && square === 0 && curly === 0) {
501
+ const closeIndex = index;
502
+ if (parenthesizedArrow) {
503
+ index++;
504
+ skipTrivia();
505
+ const hasArrow = source[index] === "=" && source[index + 1] === ">";
506
+ if (!hasArrow && (!asyncMethodOrArrow || source[index] !== "{")) return undefined;
507
+ }
508
+ return source.slice(openIndex + 1, closeIndex);
509
+ }
510
+ if (depth < 0) return undefined;
511
+ } else if (character === "[") square++;
512
+ else if (character === "]") {
513
+ square--;
514
+ if (square < 0) return undefined;
515
+ } else if (character === "{") curly++;
516
+ else if (character === "}") {
517
+ if (templateDepths.at(-1) === curly) {
518
+ templateDepths.pop();
519
+ curly--;
520
+ quote = "`";
521
+ } else curly--;
522
+ if (curly < 0) return undefined;
523
+ }
524
+ }
525
+ return undefined;
526
+ }
527
+
528
+ /**
529
+ * Conservative defense in depth for defaulted second parameters, which
530
+ * JavaScript intentionally omits from Function.length. Ambiguous source is
531
+ * ignored so this check can never reject a valid provider on weak evidence.
532
+ */
533
+ function authStartHasHiddenInput(start: unknown): boolean {
534
+ let source: string;
535
+ try {
536
+ source = Function.prototype.toString.call(start);
537
+ } catch {
538
+ return false;
539
+ }
540
+ if (
541
+ !source ||
542
+ source.includes("[native code]") ||
543
+ /^\s*(?:async\s+)?function\s+bound\b/.test(source)
544
+ )
545
+ return false;
546
+
547
+ const parameters = authStartParameterList(source);
548
+ if (!parameters) return false;
549
+ const parts = splitAuthStartParameters(parameters);
550
+ if (!parts || parts.length < 2) return false;
551
+
552
+ // Require ordinary, readable source formatting. This intentionally fails
553
+ // open for minified output and for transpilers that rewrite defaults.
554
+ const commaIndex = parameters.indexOf(",");
555
+ if (commaIndex < 0 || !/\s/.test(parameters[commaIndex + 1] ?? "")) return false;
556
+ const first = parts[0].trim();
557
+ const second = parts[1].trim();
558
+ const identifier = /^[_$A-Za-z][_$A-Za-z0-9]*/;
559
+ const firstName = first.match(identifier)?.[0];
560
+ const secondName = second.match(identifier)?.[0];
561
+ if (!firstName || !secondName || firstName.length < 3 || secondName.length < 3) return false;
562
+ return /\s=\s/.test(second);
563
+ }
263
564
 
264
565
  export interface ProviderConfig<TOperations extends Record<string, ProviderOperation>> {
265
566
  id: string;
@@ -510,6 +811,24 @@ function validateProviderShape(config: unknown): void {
510
811
  },
511
812
  );
512
813
  }
814
+ if (
815
+ auth &&
816
+ typeof auth === "object" &&
817
+ "flow" in auth &&
818
+ auth.flow &&
819
+ typeof auth.flow === "object" &&
820
+ "start" in auth.flow &&
821
+ typeof auth.flow.start === "function" &&
822
+ auth.flow.start.length <= 1 &&
823
+ authStartHasHiddenInput(auth.flow.start)
824
+ ) {
825
+ throw new ProviderError(
826
+ `Provider "${String(config.id)}" auth.flow.start must not declare an input parameter`,
827
+ {
828
+ fix: "Return a form turn from start(ctx), then receive user input in continue(ctx, input).",
829
+ },
830
+ );
831
+ }
513
832
  const access = config.access;
514
833
  if (access !== undefined) {
515
834
  if (!access || typeof access !== "object" || Array.isArray(access)) {
package/src/index.ts CHANGED
@@ -33,6 +33,7 @@ export {
33
33
  defineSmsOtpMatcher,
34
34
  defineStreamOperation,
35
35
  every,
36
+ type AuthStartNoInputGuard,
36
37
  type ProviderConfig,
37
38
  } from "./define.js";
38
39
  export type { DevServerOptions } from "./dev.js";
@@ -6,6 +6,7 @@ import type {
6
6
  FlowContext,
7
7
  HttpClient,
8
8
  OcrContext,
9
+ ProviderRuntimeState,
9
10
  StealthClient,
10
11
  SttContext,
11
12
  } from "../types.js";
@@ -59,6 +60,8 @@ export function createFlowContext(options: {
59
60
  providerId: string;
60
61
  connectionId?: string;
61
62
  externalRef?: string;
63
+ /** Host-agnostic: callers pass an already-scoped runtime state, which this helper forwards verbatim. */
64
+ state?: ProviderRuntimeState;
62
65
  allowedKeys: string[];
63
66
  initialContext?: Record<string, unknown>;
64
67
  ocr?: OcrContext;
@@ -71,6 +74,7 @@ export function createFlowContext(options: {
71
74
  tenantId: options.tenantId,
72
75
  providerId: options.providerId,
73
76
  http: options.http,
77
+ state: options.state,
74
78
  stealth: options.stealth,
75
79
  env: options.env,
76
80
  context: createScratchpad(options.allowedKeys, options.initialContext),
@@ -816,6 +816,10 @@ class PlaywrightBrowserPage implements BrowserPageContract {
816
816
  return await this.page.evaluate(fn);
817
817
  }
818
818
 
819
+ async userAgent(): Promise<string> {
820
+ return await this.evaluate<string>("navigator.userAgent");
821
+ }
822
+
819
823
  async waitForSelector(selector: string, options?: { timeout?: number }): Promise<void> {
820
824
  await this.page.waitForSelector(selector, options);
821
825
  }
@@ -1509,6 +1513,10 @@ class CdpPoolBrowserPage implements BrowserPageContract {
1509
1513
  return await this.evaluateWithContext<T>(fn);
1510
1514
  }
1511
1515
 
1516
+ async userAgent(): Promise<string> {
1517
+ return await this.evaluate<string>("navigator.userAgent");
1518
+ }
1519
+
1512
1520
  async evaluateInFrame<T>(frameId: string, fn: string | (() => T)): Promise<T> {
1513
1521
  await this.initialize();
1514
1522
  const contextId = await this.getFrameExecutionContextId(frameId);